diff --git a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/CapturedLogEvent.scala b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/CapturedLogEvent.scala index 6ee53a77092..0eccdeb633a 100644 --- a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/CapturedLogEvent.scala +++ b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/CapturedLogEvent.scala @@ -80,9 +80,8 @@ object CapturedLogEvent { case _ => None } - def apply(level: Level, message: String): CapturedLogEvent = { + def apply(level: Level, message: String): CapturedLogEvent = CapturedLogEvent(level, message, None, None) - } /** * Auxiliary constructor that receives Pekko's internal [[OptionVal]] as parameters and converts them to Scala's [[Option]]. @@ -93,7 +92,6 @@ object CapturedLogEvent { level: Level, message: String, errorCause: OptionVal[Throwable], - logMarker: OptionVal[Marker]): CapturedLogEvent = { + logMarker: OptionVal[Marker]): CapturedLogEvent = new CapturedLogEvent(level, message, toOption(errorCause), toOption(logMarker)) - } } diff --git a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/ActorSystemStub.scala b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/ActorSystemStub.scala index ad122712bc8..a06424c4f74 100644 --- a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/ActorSystemStub.scala +++ b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/ActorSystemStub.scala @@ -117,9 +117,8 @@ import pekko.util.FutureConverters._ override def printTree: String = "no tree for ActorSystemStub" - override def systemActorOf[U](behavior: Behavior[U], name: String, props: Props): ActorRef[U] = { + override def systemActorOf[U](behavior: Behavior[U], name: String, props: Props): ActorRef[U] = throw new UnsupportedOperationException("ActorSystemStub cannot create system actors") - } override def registerExtension[T <: Extension](ext: ExtensionId[T]): T = throw new UnsupportedOperationException("ActorSystemStub cannot register extensions") diff --git a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/BehaviorTestKitImpl.scala b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/BehaviorTestKitImpl.scala index 79e7f40292e..c2fc3ae224e 100644 --- a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/BehaviorTestKitImpl.scala +++ b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/BehaviorTestKitImpl.scala @@ -49,14 +49,12 @@ private[pekko] final class BehaviorTestKitImpl[T]( private[pekko] def as[U]: BehaviorTestKitImpl[U] = this.asInstanceOf[BehaviorTestKitImpl[U]] private var currentUncanonical = _initialBehavior - private var current = { + private var current = try { context.setCurrentActorThread() Behavior.validateAsInitial(Behavior.start(_initialBehavior, context)) - } finally { + } finally context.clearCurrentActorThread() - } - } // execute any future tasks scheduled in Actor's constructor runAllTasks() @@ -92,14 +90,13 @@ private[pekko] final class BehaviorTestKitImpl[T]( def getAllEffects(): util.List[Effect] = retrieveAllEffects().asJava - override def expectEffect(expectedEffect: Effect): Unit = { + override def expectEffect(expectedEffect: Effect): Unit = context.effectQueue.poll() match { case null => assert(expectedEffect == NoEffects, s"expected: $expectedEffect but no effects were recorded") case effect => assert(expectedEffect == effect, s"expected: $expectedEffect but found $effect") } - } - def expectEffectClass[E <: Effect](effectClass: Class[E]): E = { + def expectEffectClass[E <: Effect](effectClass: Class[E]): E = context.effectQueue.poll() match { case null if effectClass.isAssignableFrom(NoEffects.getClass) => effectClass.cast(NoEffects) case null => @@ -107,9 +104,8 @@ private[pekko] final class BehaviorTestKitImpl[T]( case effect if effectClass.isAssignableFrom(effect.getClass) => effect.asInstanceOf[E] case other => throw new AssertionError(s"expected: effect class ${effectClass.getName} but found $other") } - } - def expectEffectPF[R](f: PartialFunction[Effect, R]): R = { + def expectEffectPF[R](f: PartialFunction[Effect, R]): R = context.effectQueue.poll() match { case null if f.isDefinedAt(NoEffects) => f.apply(NoEffects) @@ -118,7 +114,6 @@ private[pekko] final class BehaviorTestKitImpl[T]( case other => throw new AssertionError(s"expected matching effect but got: $other") } - } def expectEffectType[E <: Effect](implicit classTag: ClassTag[E]): E = expectEffectClass(classTag.runtimeClass.asInstanceOf[Class[E]]) @@ -136,14 +131,13 @@ private[pekko] final class BehaviorTestKitImpl[T]( throw e } - private def runAllTasks(): Unit = { + private def runAllTasks(): Unit = context.executionContext match { case controlled: ControlledExecutor => controlled.runAll() case _ => } - } - override def run(message: T): Unit = { + override def run(message: T): Unit = try { context.setCurrentActorThread() try { @@ -153,25 +147,21 @@ private[pekko] final class BehaviorTestKitImpl[T]( // notice we pass current and not intercepted, this way Behaviors.same will be resolved to current which will be intercepted again on the next message // otherwise we would have risked intercepting an already intercepted behavior (or would have had to explicitly check if the current behavior is already intercepted by us) current = Behavior.canonicalize(currentUncanonical, current, context) - } finally { + } finally context.clearCurrentActorThread() - } runAllTasks() } catch handleException - } override def runOne(): Unit = run(selfInbox().receiveMessage()) - override def signal(signal: Signal): Unit = { + override def signal(signal: Signal): Unit = try { context.setCurrentActorThread() currentUncanonical = Behavior.interpretSignal(current, context, signal) current = Behavior.canonicalize(currentUncanonical, current, context) } catch handleException - finally { + finally context.clearCurrentActorThread() - } - } override def hasEffects(): Boolean = !context.effectQueue.isEmpty @@ -191,7 +181,7 @@ private[pekko] object BehaviorTestKitImpl { override def aroundReceive( ctx: TypedActorContext[Any], msg: Any, - target: BehaviorInterceptor.ReceiveTarget[Any]): Behavior[Any] = { + target: BehaviorInterceptor.ReceiveTarget[Any]): Behavior[Any] = msg match { case AdaptWithRegisteredMessageAdapter(msgToAdapt) => val fn = ctx @@ -206,7 +196,6 @@ private[pekko] object BehaviorTestKitImpl { target.apply(ctx, adaptedMsg) case t => target.apply(ctx, t) } - } def inteceptBehaviour[T](behavior: Behavior[T], ctx: TypedActorContext[T]): Behavior[T] = Behavior diff --git a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/CapturingAppender.scala b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/CapturingAppender.scala index 9fc2d5e7f0f..91636d9704b 100644 --- a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/CapturingAppender.scala +++ b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/CapturingAppender.scala @@ -84,9 +84,8 @@ import pekko.annotation.InternalApi import pekko.util.ccompat.JavaConverters._ val logbackLogger = getLogbackLogger(classOf[CapturingAppender].getName + "Delegate") val appenders = logbackLogger.iteratorForAppenders().asScala.filterNot(_ == this).toList - for (event <- buffer; appender <- appenders) { + for (event <- buffer; appender <- appenders) appender.doAppend(event) - } clear() } diff --git a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/ControlledExecutor.scala b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/ControlledExecutor.scala index 2b6a671a7d5..ba53f3c795d 100644 --- a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/ControlledExecutor.scala +++ b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/ControlledExecutor.scala @@ -32,11 +32,9 @@ private[pekko] final class ControlledExecutor extends ExecutionContextExecutor { def runAll(): Unit = while (!tasks.isEmpty()) runOne() - def execute(task: Runnable): Unit = { + def execute(task: Runnable): Unit = tasks.add(task) - } - def reportFailure(cause: Throwable): Unit = { + def reportFailure(cause: Throwable): Unit = cause.printStackTrace() - } } diff --git a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/EffectfulActorContext.scala b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/EffectfulActorContext.scala index 6e38d388777..30799284eb4 100644 --- a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/EffectfulActorContext.scala +++ b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/EffectfulActorContext.scala @@ -127,7 +127,7 @@ import scala.reflect.ClassTag override def cancelAll(): Unit = activeTimers.foreach(cancel) - private def sendAction(key: Any): () => Unit = () => { + private def sendAction(key: Any): () => Unit = () => activeTimers.get(key).foreach { case Effect.TimerScheduled(_, msg, _, mode, _) => mode match { @@ -138,8 +138,6 @@ import scala.reflect.ClassTag self ! msg } - } - def startTimer(key: Any, msg: T, delay: FiniteDuration, mode: Effect.TimerScheduled.TimerMode) = { val effect = Effect.TimerScheduled(key, msg, delay, mode, activeTimers.keySet(key))(sendAction(key)) activeTimers += (key -> effect) diff --git a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/LogbackUtil.scala b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/LogbackUtil.scala index 1673224e14c..4b024383671 100644 --- a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/LogbackUtil.scala +++ b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/LogbackUtil.scala @@ -30,7 +30,7 @@ import scala.annotation.tailrec getLogbackLoggerInternal(loggerName, 50) @tailrec - private def getLogbackLoggerInternal(loggerName: String, count: Int): ch.qos.logback.classic.Logger = { + private def getLogbackLoggerInternal(loggerName: String, count: Int): ch.qos.logback.classic.Logger = LoggerFactory.getLogger(loggerNameOrRoot(loggerName)) match { case logger: ch.qos.logback.classic.Logger => logger case _: org.slf4j.helpers.SubstituteLogger if count > 0 => @@ -43,9 +43,8 @@ import scala.annotation.tailrec throw new IllegalArgumentException( s"Requires Logback logger for [$loggerName], it was a [${other.getClass.getName}]") } - } - def convertLevel(level: ch.qos.logback.classic.Level): Level = { + def convertLevel(level: ch.qos.logback.classic.Level): Level = level.levelInt match { case ch.qos.logback.classic.Level.TRACE_INT => Level.TRACE case ch.qos.logback.classic.Level.DEBUG_INT => Level.DEBUG @@ -55,5 +54,4 @@ import scala.annotation.tailrec case _ => throw new IllegalArgumentException("Level " + level.levelStr + ", " + level.levelInt + " is unknown.") } - } } diff --git a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/LoggingTestKitImpl.scala b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/LoggingTestKitImpl.scala index 555c4c4c220..694f1ec33a0 100644 --- a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/LoggingTestKitImpl.scala +++ b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/LoggingTestKitImpl.scala @@ -58,7 +58,7 @@ import pekko.testkit.TestKit @volatile // JMM does not guarantee visibility for non-final fields private var todo = occurrences - def matches(event: LoggingEvent): Boolean = { + def matches(event: LoggingEvent): Boolean = logLevel.forall(_ == event.level) && source.forall(_ == sourceOrEmpty(event)) && messageContains.forall(messageOrEmpty(event).contains) && @@ -67,8 +67,7 @@ import pekko.testkit.TestKit mdc.forall { case (key, value) => event.mdc.contains(key) && event.mdc(key) == value } && custom.forall(f => f(event)) - // loggerName is handled when installing the filter, in `expect` - } + // loggerName is handled when installing the filter, in `expect` private def messageOrEmpty(event: LoggingEvent): String = if (event.message == null) "" else event.message @@ -76,24 +75,22 @@ import pekko.testkit.TestKit private def sourceOrEmpty(event: LoggingEvent): String = event.mdc.getOrElse("pekkoSource", "") - def apply(event: LoggingEvent): Boolean = { + def apply(event: LoggingEvent): Boolean = if (matches(event)) { if (todo != Int.MaxValue) todo -= 1 true } else false - } private def awaitDone(max: Duration): Boolean = { if (todo != Int.MaxValue && todo > 0) TestKit.awaitCond(todo <= 0, max, noThrow = true) todo == Int.MaxValue || todo == 0 } - private def awaitNoExcess(max: Duration): Boolean = { + private def awaitNoExcess(max: Duration): Boolean = if (todo == 0) !TestKit.awaitCond(todo < 0, max, noThrow = true) else todo > 0 - } override def expect[T](code: => T)(implicit system: ActorSystem[_]): T = { val effectiveLoggerName = loggerName.getOrElse("") @@ -127,11 +124,10 @@ import pekko.testkit.TestKit override def intercept[T](code: => T)(implicit system: ActorSystem[_]): T = expect(code)(system) - private def checkLogback(system: ActorSystem[_]): Unit = { + private def checkLogback(system: ActorSystem[_]): Unit = if (!system.dynamicAccess.classIsOnClasspath("ch.qos.logback.classic.spi.ILoggingEvent")) { throw new IllegalStateException("LoggingEventFilter requires logback-classic dependency in classpath.") } - } override def withOccurrences(newOccurrences: Int): LoggingTestKitImpl = copy(occurrences = newOccurrences) diff --git a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/StubbedActorContext.scala b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/StubbedActorContext.scala index 51314acafcb..547f58336a3 100644 --- a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/StubbedActorContext.scala +++ b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/StubbedActorContext.scala @@ -74,13 +74,11 @@ private[pekko] final class FunctionRef[-T](override val path: ActorPath, send: ( currentBehaviorProvider: () => Behavior[T]) extends ActorContextImpl[T] { - def this(system: ActorSystemStub, name: String, currentBehaviorProvider: () => Behavior[T]) = { + def this(system: ActorSystemStub, name: String, currentBehaviorProvider: () => Behavior[T]) = this(system, (system.path / name).withUid(rnd().nextInt()), currentBehaviorProvider) - } - def this(name: String, currentBehaviorProvider: () => Behavior[T]) = { + def this(name: String, currentBehaviorProvider: () => Behavior[T]) = this(new ActorSystemStub("StubbedActorContext"), name, currentBehaviorProvider) - } /** * INTERNAL API @@ -141,21 +139,16 @@ private[pekko] final class FunctionRef[-T](override val path: ActorPath, send: ( _children -= child.path.name } } - override def watch[U](other: ActorRef[U]): Unit = { + override def watch[U](other: ActorRef[U]): Unit = checkCurrentActorThread() - } - override def watchWith[U](other: ActorRef[U], message: T): Unit = { + override def watchWith[U](other: ActorRef[U], message: T): Unit = checkCurrentActorThread() - } - override def unwatch[U](other: ActorRef[U]): Unit = { + override def unwatch[U](other: ActorRef[U]): Unit = checkCurrentActorThread() - } - override def setReceiveTimeout(d: FiniteDuration, message: T): Unit = { + override def setReceiveTimeout(d: FiniteDuration, message: T): Unit = checkCurrentActorThread() - } - override def cancelReceiveTimeout(): Unit = { + override def cancelReceiveTimeout(): Unit = checkCurrentActorThread() - } override def scheduleOnce[U](delay: FiniteDuration, target: ActorRef[U], message: U): classic.Cancellable = new classic.Cancellable { @@ -223,15 +216,13 @@ private[pekko] final class FunctionRef[-T](override val path: ActorPath, send: ( logger } - override def setLoggerName(name: String): Unit = { + override def setLoggerName(name: String): Unit = // nop as we don't track logger checkCurrentActorThread() - } - override def setLoggerName(clazz: Class[_]): Unit = { + override def setLoggerName(clazz: Class[_]): Unit = // nop as we don't track logger checkCurrentActorThread() - } /** * The log entries logged through context.log.{debug, info, warn, error} are captured and can be inspected through @@ -243,15 +234,13 @@ private[pekko] final class FunctionRef[-T](override val path: ActorPath, send: ( .iterator() .asScala .map { evt => - { - val marker: Option[Marker] = Option(evt.getMarkers).flatMap(_.asScala.headOption) - CapturedLogEvent( - level = evt.getLevel, - message = MessageFormatter.arrayFormat(evt.getMessage, evt.getArgumentArray).getMessage, - cause = Option(evt.getThrowable), - marker = marker) + val marker: Option[Marker] = Option(evt.getMarkers).flatMap(_.asScala.headOption) + CapturedLogEvent( + level = evt.getLevel, + message = MessageFormatter.arrayFormat(evt.getMessage, evt.getArgumentArray).getMessage, + cause = Option(evt.getThrowable), + marker = marker) - } } .toList } diff --git a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/TestAppender.scala b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/TestAppender.scala index ddfe5f34458..62011797e93 100644 --- a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/TestAppender.scala +++ b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/TestAppender.scala @@ -110,14 +110,13 @@ import java.util.Collections filter(loggingEvent) } - private def filter(event: LoggingEvent): Boolean = { + private def filter(event: LoggingEvent): Boolean = filters.exists(f => - try { + try f.apply(event) - } catch { + catch { case _: Exception => false }) - } def addTestFilter(filter: LoggingTestKitImpl): Unit = synchronized { filters ::= filter diff --git a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/TestProbeImpl.scala b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/TestProbeImpl.scala index e39be95ba2a..5bc0f73a4b8 100644 --- a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/TestProbeImpl.scala +++ b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/internal/TestProbeImpl.scala @@ -409,9 +409,8 @@ private[pekko] final class TestProbeImpl[M](name: String, system: ActorSystem[_] private def assertFail(msg: String): Nothing = throw new AssertionError(msg) - override def stop(): Unit = { + override def stop(): Unit = testActor.asInstanceOf[ActorRef[AnyRef]] ! Stop - } def tell(m: M) = testActor.tell(m) diff --git a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/javadsl/ActorTestKit.scala b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/javadsl/ActorTestKit.scala index 6b067707564..9ca019419f3 100644 --- a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/javadsl/ActorTestKit.scala +++ b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/javadsl/ActorTestKit.scala @@ -122,9 +122,8 @@ object ActorTestKit { * an error is printed to stdout when the system did not shutdown but * no exception is thrown. */ - def shutdown(system: ActorSystem[_], duration: Duration, throwIfShutdownTimesOut: Boolean): Unit = { + def shutdown(system: ActorSystem[_], duration: Duration, throwIfShutdownTimesOut: Boolean): Unit = TestKitUtils.shutdown(system, duration.asScala, throwIfShutdownTimesOut) - } /** * Shutdown the given [[pekko.actor.typed.ActorSystem]] and block until it shuts down, diff --git a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/javadsl/BehaviorTestKit.scala b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/javadsl/BehaviorTestKit.scala index 385b6549e2f..8b92e12ae24 100644 --- a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/javadsl/BehaviorTestKit.scala +++ b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/javadsl/BehaviorTestKit.scala @@ -45,9 +45,8 @@ object BehaviorTestKit { * JAVA API */ @ApiMayChange - def create[T](initialBehavior: Behavior[T], name: String): BehaviorTestKit[T] = { + def create[T](initialBehavior: Behavior[T], name: String): BehaviorTestKit[T] = create(initialBehavior, name, ActorSystemStub.config.defaultReference) - } /** * JAVA API diff --git a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/javadsl/LogCapturing.scala b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/javadsl/LogCapturing.scala index 57028154c03..418368e7ba7 100644 --- a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/javadsl/LogCapturing.scala +++ b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/javadsl/LogCapturing.scala @@ -50,9 +50,9 @@ final class LogCapturing extends TestRule { private val myLogger = LoggerFactory.getLogger(classOf[LogCapturing]) - override def apply(base: Statement, description: Description): Statement = { + override def apply(base: Statement, description: Description): Statement = new Statement { - override def evaluate(): Unit = { + override def evaluate(): Unit = try { myLogger.info(s"Logging started for test [${description.getClassName}: ${description.getMethodName}]") base.evaluate() @@ -68,10 +68,7 @@ final class LogCapturing extends TestRule { s"<-- [${Console.BLUE}${description.getClassName}: ${description.getMethodName}${Console.RESET}] " + s"End of log messages of test that failed with ${e.getMessage}") throw e - } finally { + } finally capturingAppender.clear() - } - } } - } } diff --git a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/javadsl/LogCapturingExtension.scala b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/javadsl/LogCapturingExtension.scala index e4fd37c41eb..d6574874bf8 100644 --- a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/javadsl/LogCapturingExtension.scala +++ b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/javadsl/LogCapturingExtension.scala @@ -45,9 +45,7 @@ final class LogCapturingExtension extends InvocationInterceptor { s"<-- [${Console.BLUE}${testClassName}: ${testMethodName}${Console.RESET}] " + s"End of log messages of test that failed with ${e.getMessage}") throw e - } finally { - + } finally capturingAppender.clear() - } } } diff --git a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/javadsl/TestKitJUnit5Extension.scala b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/javadsl/TestKitJUnit5Extension.scala index 50d63af7609..9e053bb7954 100644 --- a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/javadsl/TestKitJUnit5Extension.scala +++ b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/javadsl/TestKitJUnit5Extension.scala @@ -31,19 +31,18 @@ final class TestKitJUnit5Extension() extends AfterAllCallback with BeforeTestExe override def beforeTestExecution(context: ExtensionContext): Unit = { val testInstance: Option[AnyRef] = if (context.getTestInstance.isPresent) Some(context.getTestInstance.get()) else None - testInstance.map(instance => { + testInstance.map { instance => val annotations = AnnotationSupport.findAnnotatedFieldValues(instance, classOf[JUnit5TestKit]) val fieldValue = annotations.stream().findFirst().orElseThrow(() => throw new IllegalArgumentException("Could not find field annotated with @JUnit5TestKit")) testKit = Some(fieldValue.asInstanceOf[ActorTestKit]) - }) + } } /** * Shutdown testKit */ - override def afterAll(context: ExtensionContext): Unit = { + override def afterAll(context: ExtensionContext): Unit = testKit.get.shutdownTestKit() - } } diff --git a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/javadsl/TestKitJunitResource.scala b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/javadsl/TestKitJunitResource.scala index ad7e445b6bb..35d03e50cb6 100644 --- a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/javadsl/TestKitJunitResource.scala +++ b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/javadsl/TestKitJunitResource.scala @@ -188,8 +188,7 @@ final class TestKitJunitResource(_kit: ActorTestKit) extends ExternalResource { */ def serializationTestKit: SerializationTestKit = testKit.serializationTestKit - override def after(): Unit = { + override def after(): Unit = testKit.shutdownTestKit() - } } diff --git a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/scaladsl/ActorTestKit.scala b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/scaladsl/ActorTestKit.scala index ffad923a50d..2b17829aebc 100644 --- a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/scaladsl/ActorTestKit.scala +++ b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/scaladsl/ActorTestKit.scala @@ -217,12 +217,11 @@ final class ActorTestKit private[pekko] ( def scheduler: Scheduler = system.scheduler - def shutdownTestKit(): Unit = { + def shutdownTestKit(): Unit = ActorTestKit.shutdown( system, testKitSettings.DefaultActorSystemShutdownTimeout, testKitSettings.ThrowOnShutdownTimeout) - } /** * Spawn the given behavior. This is created as a child of the test kit @@ -262,11 +261,11 @@ final class ActorTestKit private[pekko] ( * Other actors will not be stopped by this method. */ def stop[T](ref: ActorRef[T], max: FiniteDuration = timeout.duration): Unit = - try { + try Await.result(internalTestKitGuardian.ask { (x: ActorRef[ActorTestKitGuardian.Ack.type]) => ActorTestKitGuardian.StopActor(ref, x) }(Timeout(max), scheduler), max) - } catch { + catch { case _: TimeoutException => assert(false, s"timeout ($max) during stop() waiting for actor [${ref.path}] to stop") } diff --git a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/scaladsl/BehaviorTestKit.scala b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/scaladsl/BehaviorTestKit.scala index a69b05778b6..22a7347af0f 100644 --- a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/scaladsl/BehaviorTestKit.scala +++ b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/scaladsl/BehaviorTestKit.scala @@ -35,9 +35,8 @@ object BehaviorTestKit { val uid = ThreadLocalRandom.current().nextInt() new BehaviorTestKitImpl(system, (system.path / name).withUid(uid), initialBehavior) } - def apply[T](initialBehavior: Behavior[T], name: String): BehaviorTestKit[T] = { + def apply[T](initialBehavior: Behavior[T], name: String): BehaviorTestKit[T] = apply(initialBehavior, name, ActorSystemStub.config.defaultReference) - } def apply[T](initialBehavior: Behavior[T]): BehaviorTestKit[T] = apply(initialBehavior, "testkit") diff --git a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/scaladsl/LogCapturing.scala b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/scaladsl/LogCapturing.scala index 9241c9fdcb4..ef7fc479201 100644 --- a/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/scaladsl/LogCapturing.scala +++ b/actor-testkit-typed/src/main/scala/org/apache/pekko/actor/testkit/typed/scaladsl/LogCapturing.scala @@ -46,17 +46,15 @@ trait LogCapturing extends BeforeAndAfterAll { self: TestSuite => private val myLogger = LoggerFactory.getLogger(classOf[LogCapturing]) - override protected def afterAll(): Unit = { - try { + override protected def afterAll(): Unit = + try super.afterAll() - } catch { + catch { case NonFatal(e) => myLogger.error("Exception from afterAll", e) capturingAppender.flush() - } finally { + } finally capturingAppender.clear() - } - } /** * If true, the logs will be cleared after each test. diff --git a/actor-testkit-typed/src/test/scala/docs/org/apache/pekko/actor/testkit/typed/scaladsl/AsyncTestingExampleSpec.scala b/actor-testkit-typed/src/test/scala/docs/org/apache/pekko/actor/testkit/typed/scaladsl/AsyncTestingExampleSpec.scala index 386b6a674e1..521a9025d70 100644 --- a/actor-testkit-typed/src/test/scala/docs/org/apache/pekko/actor/testkit/typed/scaladsl/AsyncTestingExampleSpec.scala +++ b/actor-testkit-typed/src/test/scala/docs/org/apache/pekko/actor/testkit/typed/scaladsl/AsyncTestingExampleSpec.scala @@ -55,13 +55,11 @@ object AsyncTestingExampleSpec { class Producer(publisher: ActorRef[Message])(implicit scheduler: Scheduler) { - def produce(messages: Int)(implicit timeout: Timeout): Unit = { + def produce(messages: Int)(implicit timeout: Timeout): Unit = (0 until messages).foreach(publish) - } - private def publish(i: Int)(implicit timeout: Timeout): Future[Try[Int]] = { + private def publish(i: Int)(implicit timeout: Timeout): Future[Try[Int]] = publisher.ask(ref => Message(i, ref)) - } } // #under-test-2 diff --git a/actor-testkit-typed/src/test/scala/org/apache/pekko/actor/testkit/typed/scaladsl/ActorTestKitSpec.scala b/actor-testkit-typed/src/test/scala/org/apache/pekko/actor/testkit/typed/scaladsl/ActorTestKitSpec.scala index c3cdc0eb79b..7e780969ef6 100644 --- a/actor-testkit-typed/src/test/scala/org/apache/pekko/actor/testkit/typed/scaladsl/ActorTestKitSpec.scala +++ b/actor-testkit-typed/src/test/scala/org/apache/pekko/actor/testkit/typed/scaladsl/ActorTestKitSpec.scala @@ -49,34 +49,34 @@ class ActorTestKitSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike wi "generate a default name from the test class" in { val testkit2 = ActorTestKit() - try { + try testkit2.system.name should ===("ActorTestKitSpec") - } finally testkit2.shutdownTestKit() + finally testkit2.shutdownTestKit() } "use name from given class name with replaced package name" in { val testkit2 = ActorTestKit(classOf[Vector[_]].getName) - try { + try // removing package name and such testkit2.system.name should ===("Vector") - } finally testkit2.shutdownTestKit() + finally testkit2.shutdownTestKit() } "use sanitized name if passed invalid characters" in { val testkit2 = ActorTestKit("actor~!sys-tem&Name#1%(with*invalid^ch@racter$)`") - try { + try // replacing invalid characters with underscore testkit2.system.name should ===("actor__sys-tem_Name_1__with_invalid_ch_racter___") - } finally testkit2.shutdownTestKit() + finally testkit2.shutdownTestKit() } "use the same name if passed valid ActorSystem name" in { val validActorSystemNameChars = "abcdefghijklmnopqrstuvwxyz-ABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789_" val testkit2 = ActorTestKit(validActorSystemNameChars) - try { + try // all characters should be the same testkit2.system.name should ===(validActorSystemNameChars) - } finally testkit2.shutdownTestKit() + finally testkit2.shutdownTestKit() } "spawn an actor" in { @@ -164,16 +164,16 @@ class MyConcreteDerivateSpec extends MyBaseSpec { "generate a default name from the test class" in { val testkit2 = ActorTestKit() - try { + try testkit2.system.name should ===("MyConcreteDerivateSpec") - } finally testkit2.shutdownTestKit() + finally testkit2.shutdownTestKit() } "use name from given class name" in { val testkit2 = ActorTestKit(classOf[Vector[_]].getName) - try { + try testkit2.system.name should ===("Vector") - } finally testkit2.shutdownTestKit() + finally testkit2.shutdownTestKit() } } @@ -182,9 +182,8 @@ class MyConcreteDerivateSpec extends MyBaseSpec { class CompositionSpec extends AnyWordSpec with Matchers with BeforeAndAfterAll with LogCapturing { val testKit = ActorTestKit() - override def afterAll(): Unit = { + override def afterAll(): Unit = testKit.shutdownTestKit() - } "generate a default name from the test class" in { testKit.system.name should ===("CompositionSpec") diff --git a/actor-testkit-typed/src/test/scala/org/apache/pekko/actor/testkit/typed/scaladsl/BehaviorTestKitSpec.scala b/actor-testkit-typed/src/test/scala/org/apache/pekko/actor/testkit/typed/scaladsl/BehaviorTestKitSpec.scala index 9b531e75bc9..7646c172d6c 100644 --- a/actor-testkit-typed/src/test/scala/org/apache/pekko/actor/testkit/typed/scaladsl/BehaviorTestKitSpec.scala +++ b/actor-testkit-typed/src/test/scala/org/apache/pekko/actor/testkit/typed/scaladsl/BehaviorTestKitSpec.scala @@ -97,9 +97,8 @@ object BehaviorTestKitSpec { } Behaviors.same case SpawnAdapterWithName(name) => - context.spawnMessageAdapter({ (r: Reproduce) => - SpawnAnonymous(r.times) - }, name) + context.spawnMessageAdapter((r: Reproduce) => + SpawnAnonymous(r.times), name) Behaviors.same case SpawnAndWatchUnwatch(name) => val c = context.spawn(Child.initial, name) diff --git a/actor-testkit-typed/src/test/scala/org/apache/pekko/actor/testkit/typed/scaladsl/GreeterMain.scala b/actor-testkit-typed/src/test/scala/org/apache/pekko/actor/testkit/typed/scaladsl/GreeterMain.scala index 456298d3308..43b7e4d5761 100644 --- a/actor-testkit-typed/src/test/scala/org/apache/pekko/actor/testkit/typed/scaladsl/GreeterMain.scala +++ b/actor-testkit-typed/src/test/scala/org/apache/pekko/actor/testkit/typed/scaladsl/GreeterMain.scala @@ -28,9 +28,8 @@ object Greeter { object GreeterBot { - def apply(max: Int): Behavior[Greeter.Greeted] = { + def apply(max: Int): Behavior[Greeter.Greeted] = bot(0, max) - } private def bot(greetingCounter: Int, max: Int): Behavior[Greeter.Greeted] = Behaviors.receive { (context, message) => diff --git a/actor-tests/src/test/scala/org/apache/pekko/PekkoExceptionSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/PekkoExceptionSpec.scala index 79439d1cb44..ad735398921 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/PekkoExceptionSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/PekkoExceptionSpec.scala @@ -36,7 +36,6 @@ class PekkoExceptionSpec extends AnyWordSpec with Matchers { } } - def verify(clazz: java.lang.Class[_]): Unit = { + def verify(clazz: java.lang.Class[_]): Unit = clazz.getConstructor(Array(classOf[String]): _*) - } } diff --git a/actor-tests/src/test/scala/org/apache/pekko/actor/ActorConfigurationVerificationSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/actor/ActorConfigurationVerificationSpec.scala index 5e5546324e2..4dfc2249747 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/actor/ActorConfigurationVerificationSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/actor/ActorConfigurationVerificationSpec.scala @@ -51,9 +51,8 @@ class ActorConfigurationVerificationSpec with BeforeAndAfterEach { import ActorConfigurationVerificationSpec._ - override def atStartup(): Unit = { + override def atStartup(): Unit = system.eventStream.publish(Mute(EventFilter[ConfigurationException](""))) - } "An Actor configured with a BalancingDispatcher" must { "fail verification with a ConfigurationException if also configured with a RoundRobinPool" in { diff --git a/actor-tests/src/test/scala/org/apache/pekko/actor/ActorCreationPerfSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/actor/ActorCreationPerfSpec.scala index 140a821f02c..1192f40dc7a 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/actor/ActorCreationPerfSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/actor/ActorCreationPerfSpec.scala @@ -102,9 +102,8 @@ object ActorCreationPerfSpec { case IsAlive => sender() ! Alive case Create(number, propsCreator) => - for (_ <- 1 to number) { + for (_ <- 1 to number) context.actorOf(propsCreator.apply()) - } sender() ! Created case WaitForChildren => context.children.foreach(_ ! IsAlive) @@ -204,9 +203,8 @@ class ActorCreationPerfSpec s"measure synchronous blocked time for $name" taggedAs PerformanceTest in { // note: measuring per-actor-memory-use in this scenario is skewed as the Actor contains references to counters etc! // for measuring actor size use refer to the `runWithoutCounter` method - for (i <- 1 to nrOfRepeats) { + for (i <- 1 to nrOfRepeats) runWithCounterInside(name, s"${scenarioName}_driver_inside_$i", nrOfActors, propsCreator) - } reportAndClearMetrics() } @@ -234,20 +232,20 @@ class ActorCreationPerfSpec val props1 = Props[EmptyActor]() registerTests("Props[EmptyActor] with same Props", () => props1) - registerTests("Props(new EmptyActor) new", () => { Props(new EmptyActor) }) + registerTests("Props(new EmptyActor) new", () => Props(new EmptyActor)) val props2 = Props(new EmptyActor) - registerTests("Props(new EmptyActor) same", () => { props2 }) + registerTests("Props(new EmptyActor) same", () => props2) - registerTests("Props(classOf[EmptyArgsActor], ...) new", () => { Props(classOf[EmptyArgsActor], 4711, 1729) }) + registerTests("Props(classOf[EmptyArgsActor], ...) new", () => Props(classOf[EmptyArgsActor], 4711, 1729)) val props3 = Props(classOf[EmptyArgsActor], 4711, 1729) - registerTests("Props(classOf[EmptyArgsActor], ...) same", () => { props3 }) + registerTests("Props(classOf[EmptyArgsActor], ...) same", () => props3) - registerTests("Props(new EmptyArgsActor(...)) new", () => { Props(new EmptyArgsActor(4711, 1729)) }) + registerTests("Props(new EmptyArgsActor(...)) new", () => Props(new EmptyArgsActor(4711, 1729))) val props4 = Props(new EmptyArgsActor(4711, 1729)) - registerTests("Props(new EmptyArgsActor(...)) same", () => { props4 }) + registerTests("Props(new EmptyArgsActor(...)) same", () => props4) } override def afterTermination() = shutdownMetrics() diff --git a/actor-tests/src/test/scala/org/apache/pekko/actor/ActorLifeCycleSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/actor/ActorLifeCycleSpec.scala index fe0dd5a139e..ab955c3b548 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/actor/ActorLifeCycleSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/actor/ActorLifeCycleSpec.scala @@ -32,8 +32,8 @@ object ActorLifeCycleSpec { def report(msg: Any) = testActor ! message(msg) def message(msg: Any): (Any, String, Int) = (msg, id, currentGen) val currentGen = generationProvider.getAndIncrement() - override def preStart(): Unit = { report("preStart") } - override def postStop(): Unit = { report("postStop") } + override def preStart(): Unit = report("preStart") + override def postStop(): Unit = report("postStop") def receive = { case "status" => sender() ! message("OK") } } @@ -51,8 +51,8 @@ class ActorLifeCycleSpec extends PekkoSpec with BeforeAndAfterEach with Implicit system.actorOf(Props(classOf[Supervisor], OneForOneStrategy(maxNrOfRetries = 3)(List(classOf[Exception])))) val gen = new AtomicInteger(0) val restarterProps = Props(new LifeCycleTestActor(testActor, id, gen) { - override def preRestart(reason: Throwable, message: Option[Any]): Unit = { report("preRestart") } - override def postRestart(reason: Throwable): Unit = { report("postRestart") } + override def preRestart(reason: Throwable, message: Option[Any]): Unit = report("preRestart") + override def postRestart(reason: Throwable): Unit = report("postRestart") }).withDeploy(Deploy.local) val restarter = Await.result((supervisor ? restarterProps).mapTo[ActorRef], timeout.duration) @@ -130,7 +130,7 @@ class ActorLifeCycleSpec extends PekkoSpec with BeforeAndAfterEach with Implicit "log failures in postStop" in { val a = system.actorOf(Props(new Actor { def receive = Actor.emptyBehavior - override def postStop(): Unit = { throw new Exception("hurrah") } + override def postStop(): Unit = throw new Exception("hurrah") })) EventFilter[Exception]("hurrah", occurrences = 1).intercept { a ! PoisonPill @@ -141,7 +141,7 @@ class ActorLifeCycleSpec extends PekkoSpec with BeforeAndAfterEach with Implicit final case class Become(recv: ActorContext => Receive) val a = system.actorOf(Props(new Actor { def receive = { - case Become(beh) => { context.become(beh(context), discardOld = false); sender() ! "ok" } + case Become(beh) => context.become(beh(context), discardOld = false); sender() ! "ok" case _ => sender() ! 42 } })) @@ -181,9 +181,9 @@ class ActorLifeCycleSpec extends PekkoSpec with BeforeAndAfterEach with Implicit val supervisor = system.actorOf(Props(classOf[Supervisor], supervisorStrategy)) Await.result((supervisor ? childProps).mapTo[ActorRef], timeout.duration) - (0 to maxRetryNum).foreach(i => { + (0 to maxRetryNum).foreach { i => expectMsg(("preStart", id, i)) - }) + } expectNoMessage() system.stop(supervisor) } @@ -210,7 +210,7 @@ class ActorLifeCycleSpec extends PekkoSpec with BeforeAndAfterEach with Implicit // when the flatMap thunk is run. Previously, the context was nulled when the actor // was terminated. This isn't done any more. Still, the pattern of `import context.dispatcher` // is discouraged as closing over `context` is unsafe in general. - .flatMap(x => Future { x + "ng" } /* implicitly: (this.context.dispatcher) */ ) + .flatMap(x => Future(x + "ng") /* implicitly: (this.context.dispatcher) */ ) .recover { case _: NullPointerException => "npe" } .pipeTo(replyTo) } diff --git a/actor-tests/src/test/scala/org/apache/pekko/actor/ActorPathSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/actor/ActorPathSpec.scala index a7573979fbf..f1ae3d0f1f5 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/actor/ActorPathSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/actor/ActorPathSpec.scala @@ -48,11 +48,11 @@ class ActorPathSpec extends AnyWordSpec with Matchers { } "throw exception upon malformed paths" in { - intercept[MalformedURLException] { ActorPath.fromString("") } - intercept[MalformedURLException] { ActorPath.fromString("://hallo") } - intercept[MalformedURLException] { ActorPath.fromString("s://dd@:12") } - intercept[MalformedURLException] { ActorPath.fromString("s://dd@h:hd") } - intercept[MalformedURLException] { ActorPath.fromString("a://l:1/b") } + intercept[MalformedURLException](ActorPath.fromString("")) + intercept[MalformedURLException](ActorPath.fromString("://hallo")) + intercept[MalformedURLException](ActorPath.fromString("s://dd@:12")) + intercept[MalformedURLException](ActorPath.fromString("s://dd@h:hd")) + intercept[MalformedURLException](ActorPath.fromString("a://l:1/b")) } "create correct toString" in { diff --git a/actor-tests/src/test/scala/org/apache/pekko/actor/ActorRefSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/actor/ActorRefSpec.scala index ebf47bed86d..8313da7845f 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/actor/ActorRefSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/actor/ActorRefSpec.scala @@ -35,11 +35,10 @@ object ActorRefSpec { var replyTo: ActorRef = null def receive = { - case "complexRequest" => { + case "complexRequest" => replyTo = sender() val worker = context.actorOf(Props[WorkerActor]()) worker ! "work" - } case "complexRequest2" => val worker = context.actorOf(Props[WorkerActor]()) worker ! ReplyTo(sender()) @@ -51,15 +50,13 @@ object ActorRefSpec { class WorkerActor() extends Actor { import context.system def receive = { - case "work" => { + case "work" => work() sender() ! "workDone" context.stop(self) - } - case ReplyTo(replyTo) => { + case ReplyTo(replyTo) => work() replyTo ! "complexReply" - } } private def work(): Unit = Thread.sleep(1.second.dilated.toMillis) @@ -71,12 +68,10 @@ object ActorRefSpec { case "complex" => replyActor ! "complexRequest" case "complex2" => replyActor ! "complexRequest2" case "simple" => replyActor ! "simpleRequest" - case "complexReply" => { + case "complexReply" => latch.countDown() - } - case "simpleReply" => { + case "simpleReply" => latch.countDown() - } } } diff --git a/actor-tests/src/test/scala/org/apache/pekko/actor/ActorSelectionSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/actor/ActorSelectionSpec.scala index c74d783bdaa..83c20a2ca2a 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/actor/ActorSelectionSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/actor/ActorSelectionSpec.scala @@ -87,13 +87,12 @@ class ActorSelectionSpec extends PekkoSpec with DefaultTimeout { def identify(path: String): Option[ActorRef] = identify(system.actorSelection(path)) def identify(path: ActorPath): Option[ActorRef] = identify(system.actorSelection(path)) - def askNode(node: ActorRef, query: Query): Option[ActorRef] = { + def askNode(node: ActorRef, query: Query): Option[ActorRef] = Await.result(node ? query, timeout.duration) match { case ref: ActorRef => Some(ref) case selection: ActorSelection => identify(selection) case _ => throw new RuntimeException() } - } "An ActorSystem" must { @@ -195,9 +194,8 @@ class ActorSelectionSpec extends PekkoSpec with DefaultTimeout { val all = Seq(c1, c2, c21) "select actors by their path" in { - def check(looker: ActorRef, pathOf: ActorRef, result: ActorRef): Unit = { + def check(looker: ActorRef, pathOf: ActorRef, result: ActorRef): Unit = askNode(looker, SelectPath(pathOf.path)) should ===(Some(result)) - } for { looker <- all target <- all @@ -262,7 +260,7 @@ class ActorSelectionSpec extends PekkoSpec with DefaultTimeout { val lookup = askNode(looker, query) lookup should ===(result) } - def check(looker: ActorRef): Unit = { + def check(looker: ActorRef): Unit = for ((l, r) <- Seq( SelectString("a/b/c") -> None, SelectString("pekko://all-systems/Nobody") -> None, @@ -270,7 +268,6 @@ class ActorSelectionSpec extends PekkoSpec with DefaultTimeout { SelectPath(looker.path.child("hallo")) -> None, // test Java API SelectPath(looker.path.descendant(Seq("a", "b").asJava)) -> None) // test Java API ) checkOne(looker, l, r) - } for (looker <- all) check(looker) } diff --git a/actor-tests/src/test/scala/org/apache/pekko/actor/ActorSystemDispatcherSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/actor/ActorSystemDispatcherSpec.scala index 82620268eb0..2282a089cd4 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/actor/ActorSystemDispatcherSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/actor/ActorSystemDispatcherSpec.scala @@ -69,9 +69,8 @@ class ActorSystemDispatchersSpec extends PekkoSpec(ConfigFactory.parseString(""" ecProbe.expectMsg(1.second, "called") probe.expectMsg(1.second, "pong") - } finally { + } finally shutdown(system2) - } } "not use passed in ExecutionContext if executor is configured" in { @@ -92,9 +91,8 @@ class ActorSystemDispatchersSpec extends PekkoSpec(ConfigFactory.parseString(""" ecProbe.expectNoMessage() probe.expectMsg(1.second, "ping") - } finally { + } finally shutdown(system2) - } } def userGuardianDispatcher(system: ActorSystem): String = { @@ -108,14 +106,13 @@ class ActorSystemDispatchersSpec extends PekkoSpec(ConfigFactory.parseString(""" ConfigFactory.parseString(""" pekko.actor.internal-dispatcher = pekko.actor.default-dispatcher """)) - try { + try // that the user guardian runs on the overridden dispatcher instead of internal // isn't really a guarantee any internal actor has been made running on the right one // but it's better than no test coverage at all userGuardianDispatcher(sys) should ===("pekko.actor.default-dispatcher") - } finally { + finally shutdown(sys) - } } "provide internal execution context instance through BootstrapSetup" in { @@ -144,9 +141,8 @@ class ActorSystemDispatchersSpec extends PekkoSpec(ConfigFactory.parseString(""" ecProbe.expectMsg(1.second, "called") probe.expectMsg(1.second, "pong") - } finally { + } finally shutdown(system2) - } } "use an internal dispatcher for the guardian by default" in { @@ -162,9 +158,9 @@ class ActorSystemDispatchersSpec extends PekkoSpec(ConfigFactory.parseString(""" Some(Props.empty), ActorSystemSetup.empty) sys.start() - try { + try userGuardianDispatcher(sys) should ===("pekko.actor.default-dispatcher") - } finally shutdown(sys) + finally shutdown(sys) } "provide a good error on an dispatcher alias loop in the config" in { diff --git a/actor-tests/src/test/scala/org/apache/pekko/actor/ActorSystemSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/actor/ActorSystemSpec.scala index c8af272fa9a..f232e0557d1 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/actor/ActorSystemSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/actor/ActorSystemSpec.scala @@ -215,13 +215,12 @@ class ActorSystemSpec extends PekkoSpec(ActorSystemSpec.config) with ImplicitSen val count = 10 val latch = TestLatch(count) - for (i <- 1 to count) { + for (i <- 1 to count) system2.registerOnTermination { Thread.sleep((i % 3).millis.dilated.toMillis) result.add(i) latch.countDown() } - } system2.terminate() Await.ready(latch, 5 seconds) @@ -241,7 +240,7 @@ class ActorSystemSpec extends PekkoSpec(ActorSystemSpec.config) with ImplicitSen callbackWasRun = true } import system.dispatcher - system2.scheduler.scheduleOnce(200.millis.dilated) { system2.terminate() } + system2.scheduler.scheduleOnce(200.millis.dilated)(system2.terminate()) Await.ready(system2.whenTerminated, 5 seconds) callbackWasRun should ===(true) @@ -265,7 +264,7 @@ class ActorSystemSpec extends PekkoSpec(ActorSystemSpec.config) with ImplicitSen Await.ready(system2.terminate(), 10 seconds) intercept[RejectedExecutionException] { - system2.registerOnTermination { println("IF YOU SEE THIS THEN THERE'S A BUG HERE") } + system2.registerOnTermination(println("IF YOU SEE THIS THEN THERE'S A BUG HERE")) }.getMessage should ===("ActorSystem already terminated.") } @@ -276,7 +275,7 @@ class ActorSystemSpec extends PekkoSpec(ActorSystemSpec.config) with ImplicitSen try { system2.terminate() - system2.registerOnTermination { count.incrementAndGet() } + system2.registerOnTermination(count.incrementAndGet()) } catch { case _: RejectedExecutionException => count.incrementAndGet() } @@ -300,7 +299,7 @@ class ActorSystemSpec extends PekkoSpec(ActorSystemSpec.config) with ImplicitSen "reliable deny creation of actors while shutting down" in { val system = ActorSystem() import system.dispatcher - system.scheduler.scheduleOnce(100 millis) { system.terminate() } + system.scheduler.scheduleOnce(100 millis)(system.terminate()) var failing = false var created = Vector.empty[ActorRef] while (!system.whenTerminated.isCompleted) { diff --git a/actor-tests/src/test/scala/org/apache/pekko/actor/ActorTimeoutSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/actor/ActorTimeoutSpec.scala index 94c2f464c81..1dd3ed5098c 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/actor/ActorTimeoutSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/actor/ActorTimeoutSpec.scala @@ -35,13 +35,13 @@ class ActorTimeoutSpec extends PekkoSpec { implicit val timeout = Timeout(testTimeout) val echo = system.actorOf(Props.empty) val f = echo ? "hallo" - intercept[AskTimeoutException] { Await.result(f, testTimeout + leeway) } + intercept[AskTimeoutException](Await.result(f, testTimeout + leeway)) } "use explicitly supplied timeout" in { val echo = system.actorOf(Props.empty) val f = echo.?("hallo")(testTimeout) - intercept[AskTimeoutException] { Await.result(f, testTimeout + leeway) } + intercept[AskTimeoutException](Await.result(f, testTimeout + leeway)) } } } diff --git a/actor-tests/src/test/scala/org/apache/pekko/actor/ActorWithBoundedStashSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/actor/ActorWithBoundedStashSpec.scala index e8a1ec7d2dd..3507ac3df78 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/actor/ActorWithBoundedStashSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/actor/ActorWithBoundedStashSpec.scala @@ -107,9 +107,8 @@ class ActorWithBoundedStashSpec with ImplicitSender { import ActorWithBoundedStashSpec._ - override def atStartup(): Unit = { + override def atStartup(): Unit = system.eventStream.publish(Mute(EventFilter.warning(pattern = ".*received dead letter from.*hello.*"))) - } override def beforeEach(): Unit = system.eventStream.subscribe(testActor, classOf[DeadLetter]) diff --git a/actor-tests/src/test/scala/org/apache/pekko/actor/ActorWithStashSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/actor/ActorWithStashSpec.scala index 636117cd85c..6d1f53770b4 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/actor/ActorWithStashSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/actor/ActorWithStashSpec.scala @@ -111,9 +111,8 @@ object ActorWithStashSpec { class ActorWithStashSpec extends PekkoSpec with DefaultTimeout with BeforeAndAfterEach { import ActorWithStashSpec._ - override def atStartup(): Unit = { + override def atStartup(): Unit = system.eventStream.publish(Mute(EventFilter[Exception]("Crashing..."))) - } override def beforeEach() = state.finished.reset() diff --git a/actor-tests/src/test/scala/org/apache/pekko/actor/ConsistencySpec.scala b/actor-tests/src/test/scala/org/apache/pekko/actor/ConsistencySpec.scala index b4777152a32..88b57a0a407 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/actor/ConsistencySpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/actor/ConsistencySpec.scala @@ -74,11 +74,10 @@ class ConsistencySpec extends PekkoSpec(ConsistencySpec.config) { val props = Props[ConsistencyCheckingActor]().withDispatcher("consistency-dispatcher") val actors = Vector.fill(noOfActors)(system.actorOf(props)) - for (i <- 0L until 10000L) { + for (i <- 0L until 10000L) actors.foreach(_.tell(i, testActor)) - } - for (a <- actors) { a.tell("done", testActor) } + for (a <- actors) a.tell("done", testActor) for (_ <- actors) expectMsg(5 minutes, "done") } diff --git a/actor-tests/src/test/scala/org/apache/pekko/actor/CoordinatedShutdownSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/actor/CoordinatedShutdownSpec.scala index d2d75544212..8c82c3590fe 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/actor/CoordinatedShutdownSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/actor/CoordinatedShutdownSpec.scala @@ -538,9 +538,8 @@ class CoordinatedShutdownSpec Await.result(CoordinatedShutdown(sys).run(CustomReason), 10.seconds) should ===(Done) sys.whenTerminated.isCompleted should ===(true) CoordinatedShutdown(sys).shutdownReason() should ===(Some(CustomReason)) - } finally { + } finally shutdown(sys) - } } "be run by ActorSystem.terminate" in { @@ -549,9 +548,8 @@ class CoordinatedShutdownSpec Await.result(sys.terminate(), 10.seconds) sys.whenTerminated.isCompleted should ===(true) CoordinatedShutdown(sys).shutdownReason() should ===(Some(CoordinatedShutdown.ActorSystemTerminateReason)) - } finally { + } finally shutdown(sys) - } } "not be run by ActorSystem.terminate when run-by-actor-system-terminate=off" in { @@ -564,9 +562,8 @@ class CoordinatedShutdownSpec Await.result(sys.terminate(), 10.seconds) sys.whenTerminated.isCompleted should ===(true) CoordinatedShutdown(sys).shutdownReason() should ===(None) - } finally { + } finally shutdown(sys) - } } "not allow terminate-actor-system=off && run-by-actor-system-terminate=on" in { @@ -682,11 +679,10 @@ class CoordinatedShutdownSpec } } """)) - try { + try block(system, CoordinatedShutdown(system)) - } finally { + finally TestKit.shutdownActorSystem(system) - } } "support actor termination tasks with a stop message" in { diff --git a/actor-tests/src/test/scala/org/apache/pekko/actor/ExtensionSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/actor/ExtensionSpec.scala index a5b6ca78ec4..2b3f66c8b92 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/actor/ExtensionSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/actor/ExtensionSpec.scala @@ -42,9 +42,8 @@ object FailingTestExtension extends ExtensionId[FailingTestExtension] with Exten object InstanceCountingExtension extends ExtensionId[InstanceCountingExtension] with ExtensionIdProvider { val createCount = new AtomicInteger(0) - override def createExtension(system: ExtendedActorSystem): InstanceCountingExtension = { + override def createExtension(system: ExtendedActorSystem): InstanceCountingExtension = new InstanceCountingExtension - } override def lookup: ExtensionId[_ <: Extension] = this } diff --git a/actor-tests/src/test/scala/org/apache/pekko/actor/FSMActorSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/actor/FSMActorSpec.scala index 5138864c2c3..a8f3d7172cd 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/actor/FSMActorSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/actor/FSMActorSpec.scala @@ -50,36 +50,31 @@ object FSMActorSpec { startWith(Locked, CodeState("", code)) when(Locked) { - case Event(digit: Char, CodeState(soFar, code)) => { + case Event(digit: Char, CodeState(soFar, code)) => soFar + digit match { case incomplete if incomplete.length < code.length => stay().using(CodeState(incomplete, code)) - case codeTry if codeTry == code => { + case codeTry if codeTry == code => doUnlock() goto(Open).using(CodeState("", code)).forMax(timeout) - } - case _ => { + case _ => stay().using(CodeState("", code)) - } } - } case Event("hello", _) => stay().replying("world") case Event("bye", _) => stop(FSM.Shutdown) } when(Open) { - case Event(StateTimeout, _) => { + case Event(StateTimeout, _) => doLock() goto(Locked) - } } whenUnhandled { - case Event(msg, _) => { + case Event(msg, _) => log.warning("unhandled event " + msg + " in state " + stateName + " with data " + stateData) unhandledLatch.open() stay() - } } onTransition { @@ -193,9 +188,9 @@ class FSMActorSpec extends PekkoSpec(Map("pekko.actor.debug.fsm" -> true)) with * It is necessary here because of the path-dependent type fsm.StopEvent. */ lazy val fsm = new Actor with FSM[Int, Null] { - override def preStart() = { started.countDown() } + override def preStart() = started.countDown() startWith(1, null) - when(1) { FSM.NullFunction } + when(1)(FSM.NullFunction) onTermination { case x => testActor ! x } @@ -238,10 +233,9 @@ class FSMActorSpec extends PekkoSpec(Map("pekko.actor.debug.fsm" -> true)) with for (timerName <- timerNames) startSingleTimer(timerName, (), 10 seconds) } onTermination { - case _ => { + case _ => checkTimersActive(false) testActor ! "stopped" - } } }) @@ -266,7 +260,7 @@ class FSMActorSpec extends PekkoSpec(Map("pekko.actor.debug.fsm" -> true)) with .parseMap(Map("pekko.loglevel" -> "DEBUG", "pekko.actor.debug.fsm" -> true).asJava) .withFallback(system.settings.config) val fsmEventSystem = ActorSystem("fsmEvent", config) - try { + try new TestKit(fsmEventSystem) { EventFilter.debug(occurrences = 5).intercept { val fsm = TestActorRef(new Actor with LoggingFSM[Int, Null] { @@ -307,9 +301,8 @@ class FSMActorSpec extends PekkoSpec(Map("pekko.actor.debug.fsm" -> true)) with system.eventStream.unsubscribe(testActor) } } - } finally { + finally TestKit.shutdownActorSystem(fsmEventSystem) - } } "fill rolling event log and hand it out" in { @@ -380,9 +373,8 @@ class FSMActorSpec extends PekkoSpec(Map("pekko.actor.debug.fsm" -> true)) with fsm ! OverrideTimeoutToInf p.expectMsg(OverrideTimeoutToInf) p.expectNoMessage(1.seconds) - } finally { + } finally TestKit.shutdownActorSystem(sys) - } } } diff --git a/actor-tests/src/test/scala/org/apache/pekko/actor/FSMTransitionSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/actor/FSMTransitionSpec.scala index 35c092e0406..198c14f9f81 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/actor/FSMTransitionSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/actor/FSMTransitionSpec.scala @@ -48,7 +48,7 @@ object FSMTransitionSpec { case Event("reply", _) => stay().replying("reply") } initialize() - override def preRestart(reason: Throwable, msg: Option[Any]): Unit = { target ! "restarted" } + override def preRestart(reason: Throwable, msg: Option[Any]): Unit = target ! "restarted" } class OtherFSM(target: ActorRef) extends Actor with FSM[Int, Int] { @@ -165,9 +165,9 @@ class FSMTransitionSpec extends PekkoSpec with ImplicitSender { } when(1) { case Event("test", _) => - try { + try sender() ! s"failed: $nextStateData" - } catch { + catch { case _: IllegalStateException => sender() ! "ok" } stay() diff --git a/actor-tests/src/test/scala/org/apache/pekko/actor/HotSwapSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/actor/HotSwapSpec.scala index 40e7e21d1e2..8631f4064d1 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/actor/HotSwapSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/actor/HotSwapSpec.scala @@ -126,7 +126,7 @@ class HotSwapSpec extends PekkoSpec with ImplicitSender { expectMsg("swapped") a ! "state" expectMsg("1") - EventFilter[Exception](message = "Crash (expected)!", occurrences = 1).intercept { a ! "crash" } + EventFilter[Exception](message = "Crash (expected)!", occurrences = 1).intercept(a ! "crash") a ! "state" expectMsg("0") } diff --git a/actor-tests/src/test/scala/org/apache/pekko/actor/ReceiveTimeoutSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/actor/ReceiveTimeoutSpec.scala index e00687a9007..e15cf02413c 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/actor/ReceiveTimeoutSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/actor/ReceiveTimeoutSpec.scala @@ -38,18 +38,16 @@ object ReceiveTimeoutSpec { } class RestartingChild(probe: ActorRef, restarting: AtomicBoolean) extends Actor { - override def preStart(): Unit = { + override def preStart(): Unit = if (restarting.get) { probe ! "restarting" context.setReceiveTimeout(500.millis) } else { probe ! "starting" } - } - override def postStop(): Unit = { + override def postStop(): Unit = probe ! "stopping" - } def receive = { case "crash" => @@ -70,9 +68,8 @@ object ReceiveTimeoutSpec { context.stop(self) } - override def postStop(): Unit = { + override def postStop(): Unit = probe ! "stopping" - } } } @@ -146,7 +143,7 @@ class ReceiveTimeoutSpec extends PekkoSpec() { } })) - intercept[TimeoutException] { Await.ready(timeoutLatch, 1 second) } + intercept[TimeoutException](Await.ready(timeoutLatch, 1 second)) system.stop(timeoutActor) } @@ -244,7 +241,7 @@ class ReceiveTimeoutSpec extends PekkoSpec() { timeoutActor ! TransparentTick - intercept[TimeoutException] { Await.ready(timeoutLatch, 1 second) } + intercept[TimeoutException](Await.ready(timeoutLatch, 1 second)) system.stop(timeoutActor) } @@ -263,7 +260,7 @@ class ReceiveTimeoutSpec extends PekkoSpec() { timeoutActor ! TransparentTick - intercept[TimeoutException] { Await.ready(timeoutLatch, initialTimeout * 2) } + intercept[TimeoutException](Await.ready(timeoutLatch, initialTimeout * 2)) system.stop(timeoutActor) } diff --git a/actor-tests/src/test/scala/org/apache/pekko/actor/RestartStrategySpec.scala b/actor-tests/src/test/scala/org/apache/pekko/actor/RestartStrategySpec.scala index 0e7dec918f9..62c8c3cb841 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/actor/RestartStrategySpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/actor/RestartStrategySpec.scala @@ -32,9 +32,8 @@ import pekko.testkit.TestLatch @nowarn class RestartStrategySpec extends PekkoSpec with DefaultTimeout { - override def atStartup(): Unit = { + override def atStartup(): Unit = system.eventStream.publish(Mute(EventFilter[Exception]("Crashing..."))) - } object Ping object Crash @@ -58,16 +57,14 @@ class RestartStrategySpec extends PekkoSpec with DefaultTimeout { case Crash => throw new Exception("Crashing...") } - override def postRestart(reason: Throwable) = { + override def postRestart(reason: Throwable) = if (!restartLatch.isOpen) restartLatch.open() else secondRestartLatch.open() - } - override def postStop() = { + override def postStop() = stopLatch.open() - } }) val employee = Await.result((boss ? employeeProps).mapTo[ActorRef], timeout.duration) @@ -100,9 +97,8 @@ class RestartStrategySpec extends PekkoSpec with DefaultTimeout { case Crash => throw new Exception("Crashing...") } - override def postRestart(reason: Throwable) = { + override def postRestart(reason: Throwable) = countDownLatch.countDown() - } }) val employee = Await.result((boss ? employeeProps).mapTo[ActorRef], timeout.duration) @@ -130,20 +126,18 @@ class RestartStrategySpec extends PekkoSpec with DefaultTimeout { if (!pingLatch.isOpen) pingLatch.open() else secondPingLatch.open() case Crash => throw new Exception("Crashing...") } - override def postRestart(reason: Throwable) = { + override def postRestart(reason: Throwable) = if (!restartLatch.isOpen) restartLatch.open() else if (!secondRestartLatch.isOpen) secondRestartLatch.open() else thirdRestartLatch.open() - } - override def postStop() = { + override def postStop() = if (restartLatch.isOpen) { secondRestartLatch.open() } - } }) val employee = Await.result((boss ? employeeProps).mapTo[ActorRef], timeout.duration) @@ -185,16 +179,14 @@ class RestartStrategySpec extends PekkoSpec with DefaultTimeout { case Ping => countDownLatch.countDown() case Crash => throw new Exception("Crashing...") } - override def postRestart(reason: Throwable) = { + override def postRestart(reason: Throwable) = if (!restartLatch.isOpen) restartLatch.open() else secondRestartLatch.open() - } - override def postStop() = { + override def postStop() = stopLatch.open() - } }) val employee = Await.result((boss ? employeeProps).mapTo[ActorRef], timeout.duration) @@ -241,13 +233,11 @@ class RestartStrategySpec extends PekkoSpec with DefaultTimeout { case Crash => throw new Exception("Crashing...") } - override def postRestart(reason: Throwable) = { + override def postRestart(reason: Throwable) = restartLatch.open() - } - override def postStop() = { + override def postStop() = stopLatch.open() - } }) val employee = Await.result((boss ? employeeProps).mapTo[ActorRef], timeout.duration) diff --git a/actor-tests/src/test/scala/org/apache/pekko/actor/SchedulerSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/actor/SchedulerSpec.scala index bb9eef056bd..2be79dffecf 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/actor/SchedulerSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/actor/SchedulerSpec.scala @@ -169,11 +169,10 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit val barrier = TestLatch() import system.dispatcher val job = system.scheduler.scheduleOnce(timeout)(barrier.countDown()) - try { + try Await.ready(barrier, 5000.millis) - } finally { + finally job.cancel() - } } "survive being stressed without cancellation" taggedAs TimingTest in { @@ -195,9 +194,8 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit } } val histogram = latencies.groupBy(_ / 100000000L) - for (k <- histogram.keys.toSeq.sorted) { + for (k <- histogram.keys.toSeq.sorted) system.log.info(f"${k * 100}%3d: ${histogram(k).size}") - } } } @@ -308,9 +306,9 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit val initialDelay = 200.millis.dilated val delay = 10.millis.dilated val timeout = collectCancellable(scheduleAdapter.schedule(initialDelay, delay, - () => { + () => ticks.incrementAndGet() - })) + )) Thread.sleep(10.millis.dilated.toMillis) timeout.cancel() Thread.sleep((initialDelay + 100.millis.dilated).toMillis) @@ -324,9 +322,9 @@ trait SchedulerSpec extends BeforeAndAfterEach with DefaultTimeout with Implicit val initialDelay = 90.millis.dilated val delay = 500.millis.dilated val timeout = collectCancellable(scheduleAdapter.schedule(initialDelay, delay, - () => { + () => ticks.incrementAndGet() - })) + )) Thread.sleep((initialDelay + 200.millis.dilated).toMillis) timeout.cancel() Thread.sleep((delay + 100.millis.dilated).toMillis) @@ -483,9 +481,8 @@ class LightArrayRevolverSchedulerSpec extends PekkoSpec(SchedulerSpec.testConfRe } } val histogram = latencies.groupBy(_ / 100000000L) - for (k <- histogram.keys.toSeq.sorted) { + for (k <- histogram.keys.toSeq.sorted) system.log.info(f"${k * 100}%3d: ${histogram(k).size}") - } expectNoMessage(1.second) } @@ -757,15 +754,15 @@ class LightArrayRevolverSchedulerSpec extends PekkoSpec(SchedulerSpec.testConfRe trait Driver { def wakeUp(d: FiniteDuration): Unit def expectWait(): FiniteDuration - def expectWait(d: FiniteDuration): Unit = { expectWait() should ===(d) } + def expectWait(d: FiniteDuration): Unit = expectWait() should ===(d) def probe: TestProbe def step: FiniteDuration def close(): Unit } val localEC = new ExecutionContext { - def execute(runnable: Runnable): Unit = { runnable.run() } - def reportFailure(t: Throwable): Unit = { t.printStackTrace() } + def execute(runnable: Runnable): Unit = runnable.run() + def reportFailure(t: Throwable): Unit = t.printStackTrace() } @nowarn @@ -777,10 +774,9 @@ class LightArrayRevolverSchedulerSpec extends PekkoSpec(SchedulerSpec.testConfRe @volatile var time: Long = start val sched = new LightArrayRevolverScheduler(config.withFallback(system.settings.config), log, tf) { - override protected def clock(): Long = { + override protected def clock(): Long = // println(s"clock=$time") time - } override protected def getShutdownTimeout: FiniteDuration = (10 seconds).dilated diff --git a/actor-tests/src/test/scala/org/apache/pekko/actor/SupervisorHierarchySpec.scala b/actor-tests/src/test/scala/org/apache/pekko/actor/SupervisorHierarchySpec.scala index 2ed576a222e..292d1791acf 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/actor/SupervisorHierarchySpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/actor/SupervisorHierarchySpec.scala @@ -55,9 +55,8 @@ object SupervisorHierarchySpec { } // test relies on keeping children around during restart override def preRestart(cause: Throwable, msg: Option[Any]): Unit = {} - override def postRestart(reason: Throwable) = { + override def postRestart(reason: Throwable) = countDown.countDown() - } } class Resumer extends Actor { @@ -193,7 +192,7 @@ object SupervisorHierarchySpec { } var preRestartCalled = false - override def preRestart(cause: Throwable, msg: Option[Any]): Unit = { + override def preRestart(cause: Throwable, msg: Option[Any]): Unit = // do not scrap children if (preRestartCalled) abort("preRestart called twice") else { @@ -214,7 +213,6 @@ object SupervisorHierarchySpec { case _ => stateCache.put(self.path, stateCache.get(self.path).copy(log = log)) } } - } val unwrap: PartialFunction[Throwable, (Throwable, Throwable)] = { case x @ PostRestartException(_, f: Failure, _) => (f, x) @@ -262,13 +260,13 @@ object SupervisorHierarchySpec { abort("invariant violated: " + state.kids.size + " != " + context.children.size) } cause match { - case f: Failure if f.failPost > 0 => { f.failPost -= 1; throw f } - case PostRestartException(`self`, f: Failure, _) if f.failPost > 0 => { f.failPost -= 1; throw f } + case f: Failure if f.failPost > 0 => f.failPost -= 1; throw f + case PostRestartException(`self`, f: Failure, _) if f.failPost > 0 => f.failPost -= 1; throw f case _ => } } - override def postStop(): Unit = { + override def postStop(): Unit = if (failed || suspended) { listener ! ErrorLog("not resumed (" + failed + ", " + suspended + ")", log) val state = stateCache.get(self) @@ -276,7 +274,6 @@ object SupervisorHierarchySpec { } else { stateCache.put(self.path, HierarchyState(log, Map(), null)) } - } def check(msg: Any): Boolean = { suspended = false @@ -304,7 +301,7 @@ object SupervisorHierarchySpec { setFlags(f.directive) stateCache.put(self.path, stateCache.get(self.path).copy(failConstr = f.copy())) throw f - case "ping" => { Thread.sleep((random.nextFloat() * 1.03).toLong); sender() ! "pong" } + case "ping" => Thread.sleep((random.nextFloat() * 1.03).toLong); sender() ! "pong" case Dump(0) => abort("dump") case Dump(level) => context.children.foreach(_ ! Dump(level - 1)) case Terminated(ref) => @@ -344,7 +341,7 @@ object SupervisorHierarchySpec { } } override def isDefinedAt(msg: Any) = handler.isDefinedAt(msg) - override def apply(msg: Any) = { if (check(msg)) handler(msg) } + override def apply(msg: Any) = if (check(msg)) handler(msg) } } @@ -458,17 +455,14 @@ object SupervisorHierarchySpec { var hierarchy: ActorRef = _ - override def preRestart(cause: Throwable, msg: Option[Any]): Unit = { + override def preRestart(cause: Throwable, msg: Option[Any]): Unit = throw ActorKilledException("I want to DIE") - } - override def postRestart(cause: Throwable): Unit = { + override def postRestart(cause: Throwable): Unit = throw ActorKilledException("I said I wanted to DIE, dammit!") - } - override def postStop(): Unit = { + override def postStop(): Unit = testActor ! "stressTestStopped" - } // number of Work packages to execute for the test startWith(Idle, size * 1000) @@ -683,7 +677,7 @@ object SupervisorHierarchySpec { case this.Event(Died(_), _) => stay() } - def getErrors(target: ActorRef, depth: Int): Unit = { + def getErrors(target: ActorRef, depth: Int): Unit = target match { case l: LocalActorRef => l.underlying.actor match { @@ -695,9 +689,8 @@ object SupervisorHierarchySpec { } case _ => throw new IllegalArgumentException() } - } - def getErrorsUp(target: ActorRef): Unit = { + def getErrorsUp(target: ActorRef): Unit = target match { case l: LocalActorRef => l.underlying.actor match { @@ -707,7 +700,6 @@ object SupervisorHierarchySpec { if (target != hierarchy) getErrorsUp(l.getParent) case _ => throw new IllegalArgumentException() } - } def printErrors(): Unit = { errors.collect { @@ -887,12 +879,10 @@ class SupervisorHierarchySpec extends PekkoSpec(SupervisorHierarchySpec.config) if (ca < 6) { throw new IllegalArgumentException("OH NO!") } - override def preStart() = { + override def preStart() = preStartCalled.incrementAndGet() - } - override def postRestart(reason: Throwable) = { + override def postRestart(reason: Throwable) = postRestartCalled.incrementAndGet() - } override def receive = { case m => sender() ! m } diff --git a/actor-tests/src/test/scala/org/apache/pekko/actor/SupervisorMiscSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/actor/SupervisorMiscSpec.scala index cb6941f62da..a29dd5f3a17 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/actor/SupervisorMiscSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/actor/SupervisorMiscSpec.scala @@ -52,7 +52,7 @@ class SupervisorMiscSpec extends PekkoSpec(SupervisorMiscSpec.config) with Defau new Supervisor(OneForOneStrategy(maxNrOfRetries = 3, withinTimeRange = 5 seconds)(List(classOf[Exception]))))) val workerProps = Props(new Actor { - override def postRestart(cause: Throwable): Unit = { countDownLatch.countDown() } + override def postRestart(cause: Throwable): Unit = countDownLatch.countDown() def receive = { case "status" => this.sender() ! "OK" case _ => this.context.stop(self) diff --git a/actor-tests/src/test/scala/org/apache/pekko/actor/SupervisorSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/actor/SupervisorSpec.scala index 22801ed2e1d..7b6c9afd57d 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/actor/SupervisorSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/actor/SupervisorSpec.scala @@ -65,9 +65,8 @@ object SupervisorSpec { throw e } - override def postRestart(reason: Throwable): Unit = { + override def postRestart(reason: Throwable): Unit = sendTo ! reason.getMessage - } } class Master(sendTo: ActorRef) extends Actor { @@ -96,9 +95,8 @@ object SupervisorSpec { } class Child(cnt: Int) extends Actor { - override def preStart(): Unit = { + override def preStart(): Unit = if (cnt == 0) throw new RuntimeException("deliberate test failure") - } def receive = { case PingMessage => @@ -205,9 +203,8 @@ class SupervisorSpec (pingpong1, pingpong2, pingpong3, topSupervisor) } - override def atStartup(): Unit = { + override def atStartup(): Unit = system.eventStream.publish(Mute(EventFilter[RuntimeException](ExceptionMessage))) - } override def beforeEach() = {} @@ -219,13 +216,13 @@ class SupervisorSpec def kill(pingPongActor: ActorRef) = { val result = pingPongActor.?(DieReply)(DilatedTimeout) expectMsg(Timeout, ExceptionMessage) // this is sent from PingPongActor's postRestart() - intercept[RuntimeException] { Await.result(result, DilatedTimeout) } + intercept[RuntimeException](Await.result(result, DilatedTimeout)) } def killExpectNoRestart(pingPongActor: ActorRef) = { val result = pingPongActor.?(DieReply)(DilatedTimeout) expectNoMessage(500 milliseconds) - intercept[RuntimeException] { Await.result(result, DilatedTimeout) } + intercept[RuntimeException](Await.result(result, DilatedTimeout)) } "A supervisor" must { @@ -254,7 +251,7 @@ class SupervisorSpec override def preStart(): Unit = { preStarts += 1; testActor ! ("preStart" + preStarts) } override def postStop(): Unit = { postStops += 1; testActor ! ("postStop" + postStops) } def receive = { - case "crash" => { testActor ! "crashed"; throw new RuntimeException("Expected") } + case "crash" => testActor ! "crashed"; throw new RuntimeException("Expected") case "ping" => sender() ! "pong" } } @@ -293,7 +290,7 @@ class SupervisorSpec "not restart temporary actor" in { val (temporaryActor, _) = temporaryActorAllForOne - intercept[RuntimeException] { Await.result(temporaryActor.?(DieReply)(DilatedTimeout), DilatedTimeout) } + intercept[RuntimeException](Await.result(temporaryActor.?(DieReply)(DilatedTimeout), DilatedTimeout)) expectNoMessage(1 second) } @@ -426,9 +423,8 @@ class SupervisorSpec val init = inits.getAndIncrement() if (init % 3 == 1) throw new IllegalStateException("Don't wanna!") - override def preRestart(cause: Throwable, msg: Option[Any]): Unit = { + override def preRestart(cause: Throwable, msg: Option[Any]): Unit = if (init % 3 == 0) throw new IllegalStateException("Don't wanna!") - } def receive = { case Ping => sender() ! PongMessage @@ -467,7 +463,7 @@ class SupervisorSpec val child = context.watch(context.actorOf(Props(new Actor { override def postRestart(reason: Throwable): Unit = testActor ! "child restarted" def receive = { - case l: TestLatch => { Await.ready(l, 5 seconds); throw new IllegalStateException("OHNOES") } + case l: TestLatch => Await.ready(l, 5 seconds); throw new IllegalStateException("OHNOES") case "test" => sender() ! "child green" } }), "child")) @@ -554,9 +550,8 @@ class SupervisorSpec case _ => SupervisorStrategy.Stop } - override def preStart(): Unit = { + override def preStart(): Unit = childRef = context.actorOf(Props(new Child(cnt.getAndIncrement())), "child") - } def receive = { case msg if msg == PingMessage && childRef != null => diff --git a/actor-tests/src/test/scala/org/apache/pekko/actor/SupervisorTreeSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/actor/SupervisorTreeSpec.scala index 6c442d9784b..7c5c846792e 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/actor/SupervisorTreeSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/actor/SupervisorTreeSpec.scala @@ -35,7 +35,7 @@ class SupervisorTreeSpec extends PekkoSpec with ImplicitSender with DefaultTimeo def receive = { case p: Props => sender() ! context.actorOf(p) } - override def preRestart(cause: Throwable, msg: Option[Any]): Unit = { testActor ! self.path } + override def preRestart(cause: Throwable, msg: Option[Any]): Unit = testActor ! self.path }) val headActor = system.actorOf(p) val middleActor = Await.result((headActor ? p).mapTo[ActorRef], timeout.duration) diff --git a/actor-tests/src/test/scala/org/apache/pekko/actor/Ticket669Spec.scala b/actor-tests/src/test/scala/org/apache/pekko/actor/Ticket669Spec.scala index dc298923d0f..86b063339ad 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/actor/Ticket669Spec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/actor/Ticket669Spec.scala @@ -30,9 +30,8 @@ class Ticket669Spec extends PekkoSpec with BeforeAndAfterAll with ImplicitSender import Ticket669Spec._ // TODO: does this really make sense? - override def atStartup(): Unit = { + override def atStartup(): Unit = Thread.interrupted() // remove interrupted status. - } "A supervised actor with lifecycle PERMANENT" should { "be able to reply on failure during preRestart" in { @@ -67,12 +66,10 @@ object Ticket669Spec { case _ => throw new Exception("test") } - override def preRestart(reason: scala.Throwable, msg: Option[Any]): Unit = { + override def preRestart(reason: scala.Throwable, msg: Option[Any]): Unit = sender() ! "failure1" - } - override def postStop(): Unit = { + override def postStop(): Unit = sender() ! "failure2" - } } } diff --git a/actor-tests/src/test/scala/org/apache/pekko/actor/TimerSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/actor/TimerSpec.scala index 2d51cf27eec..6e6665cdfa2 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/actor/TimerSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/actor/TimerSpec.scala @@ -52,23 +52,20 @@ object TimerSpec { else timers.startSingleTimer("T", Tick(bumpCount), interval) - override def preRestart(reason: Throwable, message: Option[Any]): Unit = { + override def preRestart(reason: Throwable, message: Option[Any]): Unit = monitor ! GotPreRestart(timers.isTimerActive("T")) - // don't call super.preRestart to avoid postStop - } + // don't call super.preRestart to avoid postStop - override def postStop(): Unit = { + override def postStop(): Unit = monitor ! GotPostStop(timers.isTimerActive("T")) - } def bump(): Unit = { bumpCount += 1 timers.startTimerWithFixedDelay("T", Tick(bumpCount), interval) } - def autoReceive(): Unit = { + def autoReceive(): Unit = timers.startSingleTimer("A", PoisonPill, interval) - } override def receive = { case Tick(n) => diff --git a/actor-tests/src/test/scala/org/apache/pekko/actor/TypedActorSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/actor/TypedActorSpec.scala index 828fd86c510..5370016f233 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/actor/TypedActorSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/actor/TypedActorSpec.scala @@ -147,9 +147,8 @@ object TypedActorSpec { } @nowarn - def futureComposePigdogFrom(foo: Foo): Future[String] = { + def futureComposePigdogFrom(foo: Foo): Future[String] = foo.futurePigdog(500 millis).map(_.toUpperCase) - } def optionPigdog(): Option[String] = Some(pigdog()) @@ -165,9 +164,8 @@ object TypedActorSpec { var internalNumber = 0 - def incr(): Unit = { + def incr(): Unit = internalNumber += 1 - } def read() = internalNumber } @@ -219,12 +217,11 @@ object TypedActorSpec { override def postRestart(reason: Throwable): Unit = ensureContextAvailable(for (_ <- 1 to 7) latch.countDown()) - override def onReceive(msg: Any, sender: ActorRef): Unit = { + override def onReceive(msg: Any, sender: ActorRef): Unit = ensureContextAvailable(msg match { case "pigdog" => sender ! "dogpig" case _ => }) - } } trait F { @@ -369,9 +366,8 @@ class TypedActorSpec "be able to call multiple Future-returning methods non-blockingly" in within(timeout.duration) { val t = newFooBar val futures = for (i <- 1 to 20) yield (i, t.futurePigdog(20 millis, i)) - for ((i, f) <- futures) { + for ((i, f) <- futures) Await.result(f, remaining) should ===("Pigdog" + i) - } mustStop(t) } @@ -422,14 +418,14 @@ class TypedActorSpec t.failingPigdog() t.read() should ===(1) // Make sure state is not reset after failure - intercept[IllegalStateException] { Await.result(t.failingFuturePigdog(), 2 seconds) }.getMessage should ===( + intercept[IllegalStateException](Await.result(t.failingFuturePigdog(), 2 seconds)).getMessage should ===( "expected") t.read() should ===(1) // Make sure state is not reset after failure - intercept[IllegalStateException] { t.failingJOptionPigdog() }.getMessage should ===("expected") + intercept[IllegalStateException](t.failingJOptionPigdog()).getMessage should ===("expected") t.read() should ===(1) // Make sure state is not reset after failure - intercept[IllegalStateException] { t.failingOptionPigdog() }.getMessage should ===("expected") + intercept[IllegalStateException](t.failingOptionPigdog()).getMessage should ===("expected") t.read() should ===(1) // Make sure state is not reset after failure @@ -440,12 +436,12 @@ class TypedActorSpec "be restarted on failure" in { filterEvents(EventFilter[IllegalStateException]("expected")) { val t = newFooBar(Duration(2, "s")) - intercept[IllegalStateException] { t.failingOptionPigdog() }.getMessage should ===("expected") + intercept[IllegalStateException](t.failingOptionPigdog()).getMessage should ===("expected") t.optionPigdog() should ===(Some("Pigdog")) mustStop(t) val ta: F = pekko.actor.TypedActor(system).typedActorOf(TypedProps[FI]()) - intercept[IllegalStateException] { ta.f(true) }.getMessage should ===("expected") + intercept[IllegalStateException](ta.f(true)).getMessage should ===("expected") ta.f(false) should ===(1) mustStop(ta) diff --git a/actor-tests/src/test/scala/org/apache/pekko/actor/UidClashTest.scala b/actor-tests/src/test/scala/org/apache/pekko/actor/UidClashTest.scala index f489142d8dd..54af4029f5e 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/actor/UidClashTest.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/actor/UidClashTest.scala @@ -64,13 +64,12 @@ object UidClashTest { case RestartedSafely => context.parent ! RestartedSafely } - override def preRestart(reason: Throwable, message: Option[Any]): Unit = { + override def preRestart(reason: Throwable, message: Option[Any]): Unit = context.children.foreach { child => oldActor = child context.unwatch(child) context.stop(child) } - } override def preStart(): Unit = context.watch(context.actorOf(Props.empty, "child")) diff --git a/actor-tests/src/test/scala/org/apache/pekko/actor/dispatch/ActorModelSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/actor/dispatch/ActorModelSpec.scala index 1a64adbdc10..839d406f830 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/actor/dispatch/ActorModelSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/actor/dispatch/ActorModelSpec.scala @@ -76,37 +76,34 @@ object ActorModelSpec { def interceptor = context.dispatcher.asInstanceOf[MessageDispatcherInterceptor] - def ack(): Unit = { + def ack(): Unit = if (!busy.switchOn(())) { throw new Exception("isolation violated") } else { interceptor.getStats(self).msgsProcessed.incrementAndGet() } - } - override def postRestart(reason: Throwable): Unit = { + override def postRestart(reason: Throwable): Unit = interceptor.getStats(self).restarts.incrementAndGet() - } def receive = { - case AwaitLatch(latch) => { ack(); latch.await(); busy.switchOff(()) } - case Meet(sign, wait) => { ack(); sign.countDown(); wait.await(); busy.switchOff(()) } - case Wait(time) => { ack(); Thread.sleep(time); busy.switchOff(()) } - case WaitAck(time, l) => { ack(); Thread.sleep(time); l.countDown(); busy.switchOff(()) } - case Reply(msg) => { ack(); sender() ! msg; busy.switchOff(()) } - case TryReply(msg) => { ack(); sender().tell(msg, null); busy.switchOff(()) } - case Forward(to, msg) => { ack(); to.forward(msg); busy.switchOff(()) } - case CountDown(latch) => { ack(); latch.countDown(); busy.switchOff(()) } - case Increment(count) => { ack(); count.incrementAndGet(); busy.switchOff(()) } - case CountDownNStop(l) => { ack(); l.countDown(); context.stop(self); busy.switchOff(()) } - case Restart => { ack(); busy.switchOff(()); throw new Exception("Restart requested") } - case Interrupt => { + case AwaitLatch(latch) => ack(); latch.await(); busy.switchOff(()) + case Meet(sign, wait) => ack(); sign.countDown(); wait.await(); busy.switchOff(()) + case Wait(time) => ack(); Thread.sleep(time); busy.switchOff(()) + case WaitAck(time, l) => ack(); Thread.sleep(time); l.countDown(); busy.switchOff(()) + case Reply(msg) => ack(); sender() ! msg; busy.switchOff(()) + case TryReply(msg) => ack(); sender().tell(msg, null); busy.switchOff(()) + case Forward(to, msg) => ack(); to.forward(msg); busy.switchOff(()) + case CountDown(latch) => ack(); latch.countDown(); busy.switchOff(()) + case Increment(count) => ack(); count.incrementAndGet(); busy.switchOff(()) + case CountDownNStop(l) => ack(); l.countDown(); context.stop(self); busy.switchOff(()) + case Restart => ack(); busy.switchOff(()); throw new Exception("Restart requested") + case Interrupt => ack(); sender() ! Status.Failure(new ActorInterruptedException(new InterruptedException("Ping!"))); busy.switchOff(()); throw new InterruptedException("Ping!") - } - case InterruptNicely(msg) => { ack(); sender() ! msg; busy.switchOff(()); Thread.currentThread().interrupt() } - case ThrowException(e: Throwable) => { ack(); busy.switchOff(()); throw e } - case DoubleStop => { ack(); context.stop(self); context.stop(self); busy.switchOff } + case InterruptNicely(msg) => ack(); sender() ! msg; busy.switchOff(()); Thread.currentThread().interrupt() + case ThrowException(e: Throwable) => ack(); busy.switchOff(()); throw e + case DoubleStop => ack(); context.stop(self); context.stop(self); busy.switchOff } } @@ -128,7 +125,7 @@ object ActorModelSpec { val stats = new ConcurrentHashMap[ActorRef, InterceptorStats] val stops = new AtomicLong(0) - def getStats(actorRef: ActorRef) = { + def getStats(actorRef: ActorRef) = stats.get(actorRef) match { case null => val is = new InterceptorStats @@ -139,8 +136,6 @@ object ActorModelSpec { case existing => existing } - } - protected[pekko] abstract override def suspend(actor: ActorCell): Unit = { getStats(actor.self).suspensions.incrementAndGet() super.suspend(actor) @@ -176,9 +171,9 @@ object ActorModelSpec { def assertDispatcher(dispatcher: MessageDispatcherInterceptor)(stops: Long = dispatcher.stops.get())( implicit system: ActorSystem): Unit = { val deadline = System.currentTimeMillis + dispatcher.shutdownTimeout.toMillis * 5 - try { + try await(deadline)(stops == dispatcher.stops.get) - } catch { + catch { case e: Throwable => system.eventStream.publish( Error( @@ -191,15 +186,13 @@ object ActorModelSpec { } } - def assertCountDown(latch: CountDownLatch, wait: Long, hint: String): Unit = { + def assertCountDown(latch: CountDownLatch, wait: Long, hint: String): Unit = if (!latch.await(wait, TimeUnit.MILLISECONDS)) fail("Failed to count down within " + wait + " millis (count at " + latch.getCount + "). " + hint) - } - def assertNoCountDown(latch: CountDownLatch, wait: Long, hint: String): Unit = { + def assertNoCountDown(latch: CountDownLatch, wait: Long, hint: String): Unit = if (latch.await(wait, TimeUnit.MILLISECONDS)) fail("Expected count down to fail after " + wait + " millis. " + hint) - } def statsFor(actorRef: ActorRef, dispatcher: MessageDispatcher = null) = dispatcher.asInstanceOf[MessageDispatcherInterceptor].getStats(actorRef) @@ -211,9 +204,8 @@ object ActorModelSpec { unregisters: Long = 0, msgsReceived: Long = 0, msgsProcessed: Long = 0, - restarts: Long = 0)(implicit system: ActorSystem): Unit = { + restarts: Long = 0)(implicit system: ActorSystem): Unit = assertRef(actorRef, dispatcher)(suspensions, resumes, registers, unregisters, msgsReceived, msgsProcessed, restarts) - } def assertRef(actorRef: ActorRef, dispatcher: MessageDispatcher = null)( suspensions: Long = statsFor(actorRef, dispatcher).suspensions.get(), @@ -269,12 +261,11 @@ abstract class ActorModelSpec(config: String) extends PekkoSpec(config) with Def def newTestActor(dispatcher: String) = system.actorOf(Props[DispatcherActor]().withDispatcher(dispatcher)) - def awaitStarted(ref: ActorRef): Unit = { + def awaitStarted(ref: ActorRef): Unit = awaitCond(ref match { case r: RepointableRef => r.isStarted case _ => true }, 1 second, 10 millis) - } protected def interceptedDispatcher(): MessageDispatcherInterceptor protected def dispatcherType: String @@ -297,11 +288,11 @@ abstract class ActorModelSpec(config: String) extends PekkoSpec(config) with Def msgsProcessed = 0, restarts = 0) - for (i <- 1 to 10) yield Future { i } + for (i <- 1 to 10) yield Future(i) assertDispatcher(dispatcher)(stops = 2) val a2 = newTestActor(dispatcher.id) - for (i <- 1 to 10) yield Future { i } + for (i <- 1 to 10) yield Future(i) assertDispatcher(dispatcher)(stops = 2) @@ -334,20 +325,18 @@ abstract class ActorModelSpec(config: String) extends PekkoSpec(config) with Def val counter = new CountDownLatch(200) val a = newTestActor(dispatcher.id) - for (_ <- 1 to 10) { + for (_ <- 1 to 10) spawn { - for (_ <- 1 to 20) { + for (_ <- 1 to 20) a ! WaitAck(1, counter) - } } - } assertCountDown(counter, 3.seconds.dilated.toMillis, "Should process 200 messages") assertRefDefaultZero(a)(registers = 1, msgsReceived = 200, msgsProcessed = 200) system.stop(a) } - def spawn(f: => Unit): Unit = { + def spawn(f: => Unit): Unit = (new Thread { override def run(): Unit = try f @@ -355,7 +344,6 @@ abstract class ActorModelSpec(config: String) extends PekkoSpec(config) with Def case e: Throwable => system.eventStream.publish(Error(e, "spawn", this.getClass, "error in spawned thread")) } }).start() - } "not process messages for a suspended actor" in { implicit val dispatcher = interceptedDispatcher() @@ -511,7 +499,7 @@ abstract class ActorModelSpec(config: String) extends PekkoSpec(config) with Def object DispatcherModelSpec { import ActorModelSpec._ - val config = { + val config = """ boss { executor = thread-pool-executor @@ -523,7 +511,6 @@ object DispatcherModelSpec { test-dispatcher-%s { type = "org.apache.pekko.actor.dispatch.DispatcherModelSpec$MessageDispatcherInterceptorConfigurator" }""".format(n)).mkString - } class MessageDispatcherInterceptorConfigurator(config: Config, prerequisites: DispatcherPrerequisites) extends MessageDispatcherConfigurator(config, prerequisites) { @@ -548,12 +535,11 @@ class DispatcherModelSpec extends ActorModelSpec(DispatcherModelSpec.config) { val dispatcherCount = new AtomicInteger() - override def interceptedDispatcher(): MessageDispatcherInterceptor = { + override def interceptedDispatcher(): MessageDispatcherInterceptor = // use new id for each test, since the MessageDispatcherInterceptor holds state system.dispatchers .lookup("test-dispatcher-" + dispatcherCount.incrementAndGet()) .asInstanceOf[MessageDispatcherInterceptor] - } override def dispatcherType = "Dispatcher" @@ -591,7 +577,7 @@ object BalancingDispatcherModelSpec { import ActorModelSpec._ // TODO check why throughput=1 here? (came from old test) - val config = { + val config = """ boss { executor = thread-pool-executor @@ -605,7 +591,6 @@ object BalancingDispatcherModelSpec { type = "org.apache.pekko.actor.dispatch.BalancingDispatcherModelSpec$BalancingMessageDispatcherInterceptorConfigurator" throughput=1 }""".format(n)).mkString - } class BalancingMessageDispatcherInterceptorConfigurator(config: Config, prerequisites: DispatcherPrerequisites) extends BalancingDispatcherConfigurator(config, prerequisites) { @@ -631,12 +616,11 @@ class BalancingDispatcherModelSpec extends ActorModelSpec(BalancingDispatcherMod val dispatcherCount = new AtomicInteger() - override def interceptedDispatcher(): MessageDispatcherInterceptor = { + override def interceptedDispatcher(): MessageDispatcherInterceptor = // use new id for each test, since the MessageDispatcherInterceptor holds state system.dispatchers .lookup("test-balancing-dispatcher-" + dispatcherCount.incrementAndGet()) .asInstanceOf[MessageDispatcherInterceptor] - } override def dispatcherType = "Balancing Dispatcher" diff --git a/actor-tests/src/test/scala/org/apache/pekko/actor/dispatch/BalancingDispatcherSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/actor/dispatch/BalancingDispatcherSpec.scala index 08e0bf2ab94..9a3a2b54c10 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/actor/dispatch/BalancingDispatcherSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/actor/dispatch/BalancingDispatcherSpec.scala @@ -37,24 +37,23 @@ class BalancingDispatcherSpec extends PekkoSpec(BalancingDispatcherSpec.config) var invocationCount = 0 def receive = { - case _: Int => { + case _: Int => Thread.sleep(delay) invocationCount += 1 finishedCounter.countDown() - } } } class FirstActor extends Actor { - def receive = { case _ => {} } + def receive = { case _ => } } class SecondActor extends Actor { - def receive = { case _ => {} } + def receive = { case _ => } } class ParentActor extends Actor { - def receive = { case _ => {} } + def receive = { case _ => } } class ChildActor extends ParentActor {} @@ -72,14 +71,13 @@ class BalancingDispatcherSpec extends PekkoSpec(BalancingDispatcherSpec.config) var sentToFast = 0 - for (i <- 1 to 100) { + for (i <- 1 to 100) // send most work to slow actor if (i % 20 == 0) { fast ! i sentToFast += 1 } else slow ! i - } // now send some messages to actors to keep the dispatcher dispatching messages for (i <- 1 to 10) { diff --git a/actor-tests/src/test/scala/org/apache/pekko/actor/dispatch/DispatcherActorSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/actor/dispatch/DispatcherActorSpec.scala index 36eb3b875dc..32b229befc6 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/actor/dispatch/DispatcherActorSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/actor/dispatch/DispatcherActorSpec.scala @@ -94,7 +94,7 @@ class DispatcherActorSpec extends PekkoSpec(DispatcherActorSpec.config) with Def val slowOne = system.actorOf(Props(new Actor { def receive = { - case "hogexecutor" => { sender() ! "OK"; start.await() } + case "hogexecutor" => sender() ! "OK"; start.await() case "ping" => if (works.get) latch.countDown() } }).withDispatcher(throughputDispatcher)) @@ -128,8 +128,8 @@ class DispatcherActorSpec extends PekkoSpec(DispatcherActorSpec.config) with Def val slowOne = system.actorOf(Props(new Actor { def receive = { - case "hogexecutor" => { ready.countDown(); start.await() } - case "ping" => { works.set(false); context.stop(self) } + case "hogexecutor" => ready.countDown(); start.await() + case "ping" => works.set(false); context.stop(self) } }).withDispatcher(throughputDispatcher)) diff --git a/actor-tests/src/test/scala/org/apache/pekko/actor/dispatch/DispatcherActorsSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/actor/dispatch/DispatcherActorsSpec.scala index cb2e0faff06..c8f8f080fdf 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/actor/dispatch/DispatcherActorsSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/actor/dispatch/DispatcherActorsSpec.scala @@ -26,18 +26,16 @@ class DispatcherActorsSpec extends PekkoSpec { class SlowActor(finishedCounter: CountDownLatch) extends Actor { def receive = { - case _: Int => { + case _: Int => Thread.sleep(50) // slow actor finishedCounter.countDown() - } } } class FastActor(finishedCounter: CountDownLatch) extends Actor { def receive = { - case _: Int => { + case _: Int => finishedCounter.countDown() - } } } @@ -49,14 +47,12 @@ class DispatcherActorsSpec extends PekkoSpec { val f = system.actorOf(Props(new FastActor(fFinished))) // send a lot of stuff to s - for (i <- 1 to 50) { + for (i <- 1 to 50) s ! i - } // send some messages to f - for (i <- 1 to 10) { + for (i <- 1 to 10) f ! i - } // now assert that f is finished while s is still busy fFinished.await() diff --git a/actor-tests/src/test/scala/org/apache/pekko/actor/setup/ActorSystemSetupSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/actor/setup/ActorSystemSetupSpec.scala index b4dbcd31ef4..180d392f0cd 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/actor/setup/ActorSystemSetupSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/actor/setup/ActorSystemSetupSpec.scala @@ -72,9 +72,8 @@ class ActorSystemSetupSpec extends AnyWordSpec with Matchers { (system.settings.setup.get[DummySetup]: Option[Setup]) should ===(Some(setup)) - } finally { + } finally TestKit.shutdownActorSystem(system) - } } } diff --git a/actor-tests/src/test/scala/org/apache/pekko/dispatch/ExecutionContextSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/dispatch/ExecutionContextSpec.scala index 0463b8c595d..619b2a9882b 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/dispatch/ExecutionContextSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/dispatch/ExecutionContextSpec.scala @@ -47,9 +47,8 @@ class ExecutionContextSpec extends PekkoSpec with DefaultTimeout { val jExecutorService: ExecutionContextExecutorService = ExecutionContexts.fromExecutorService(es) jExecutorService should not be null - } finally { + } finally es.shutdown - } } "be able to use Batching" in { @@ -97,7 +96,7 @@ class ExecutionContextSpec extends PekkoSpec with DefaultTimeout { (1 to 100).foreach { _ => batchable { val deadlock = TestLatch(1) - batchable { deadlock.open() } + batchable(deadlock.open()) Await.ready(deadlock, timeout.duration) latch.countDown() } @@ -120,11 +119,11 @@ class ExecutionContextSpec extends PekkoSpec with DefaultTimeout { } val r = p.map { _ => // trigger the resubmitUnbatched() call - blocking { () } + blocking(()) // make sure that the other task runs to completion before continuing Thread.sleep(500) // now try again to blockOn() - blocking { () } + blocking(()) } p.onComplete { _ => () @@ -154,13 +153,12 @@ class ExecutionContextSpec extends PekkoSpec with DefaultTimeout { val ec = pekko.dispatch.ExecutionContexts.parasitic var x = 0 ec.execute(new Runnable { - override def run = { + override def run = ec.execute(new Runnable { override def run = blocking { x = 1 } }) - } }) x should be(1) } @@ -214,7 +212,7 @@ class ExecutionContextSpec extends PekkoSpec with DefaultTimeout { val counter = new AtomicInteger(0) def perform(f: Int => Int) = sec.execute(new Runnable { def run = counter.set(f(counter.get)) }) perform(_ + 1) - perform(x => { sec.suspend(); x * 2 }) + perform { x => sec.suspend(); x * 2 } awaitCond(counter.get == 2) perform(_ + 4) perform(_ * 2) @@ -234,7 +232,7 @@ class ExecutionContextSpec extends PekkoSpec with DefaultTimeout { val counter = new AtomicInteger(0) val underlying = new ExecutionContext { override def execute(r: Runnable): Unit = { submissions.incrementAndGet(); ExecutionContext.global.execute(r) } - override def reportFailure(t: Throwable): Unit = { ExecutionContext.global.reportFailure(t) } + override def reportFailure(t: Throwable): Unit = ExecutionContext.global.reportFailure(t) } val throughput = 25 val sec = SerializedSuspendableExecutionContext(throughput)(underlying) @@ -270,7 +268,7 @@ class ExecutionContextSpec extends PekkoSpec with DefaultTimeout { val counter = new AtomicInteger(0) val underlying = new ExecutionContext { override def execute(r: Runnable): Unit = { submissions.incrementAndGet(); ExecutionContext.global.execute(r) } - override def reportFailure(t: Throwable): Unit = { ExecutionContext.global.reportFailure(t) } + override def reportFailure(t: Throwable): Unit = ExecutionContext.global.reportFailure(t) } val throughput = 25 val sec = SerializedSuspendableExecutionContext(throughput)(underlying) @@ -280,7 +278,7 @@ class ExecutionContextSpec extends PekkoSpec with DefaultTimeout { (1 to 10).foreach { _ => perform(identity) } - perform(x => { sec.suspend(); x * 2 }) + perform { x => sec.suspend(); x * 2 } perform(_ + 8) sec.size() should ===(13) sec.resume() diff --git a/actor-tests/src/test/scala/org/apache/pekko/dispatch/MailboxConfigSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/dispatch/MailboxConfigSpec.scala index 02ae1a5624b..b66b70403e5 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/dispatch/MailboxConfigSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/dispatch/MailboxConfigSpec.scala @@ -161,7 +161,7 @@ abstract class MailboxSpec extends PekkoSpec with BeforeAndAfterAll with BeforeA val ps = for (i <- (1 to enqueueN by step).toList) yield createProducer(i, Math.min(enqueueN, i + step - 1)) if (parallel == false) - ps.foreach { Await.ready(_, remainingOrDefault) } + ps.foreach(Await.ready(_, remainingOrDefault)) ps } diff --git a/actor-tests/src/test/scala/org/apache/pekko/dispatch/StablePriorityDispatcherSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/dispatch/StablePriorityDispatcherSpec.scala index 88caa4c8fe4..8a5432d9b50 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/dispatch/StablePriorityDispatcherSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/dispatch/StablePriorityDispatcherSpec.scala @@ -101,7 +101,7 @@ class StablePriorityDispatcherSpec extends PekkoSpec(StablePriorityDispatcherSpe // Low messages should come out first, and in priority order. High messages follow - they are equal priority and // should come out in the same order in which they were sent. val lo = (1 to 100) toList - val hi = shuffled.filter { _ > 100 } + val hi = shuffled.filter(_ > 100) (expectMsgType[List[Int]]: List[Int]) should ===(lo ++ hi) } } diff --git a/actor-tests/src/test/scala/org/apache/pekko/event/AddressTerminatedTopicBenchSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/event/AddressTerminatedTopicBenchSpec.scala index 92155843844..ea2ce6173be 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/event/AddressTerminatedTopicBenchSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/event/AddressTerminatedTopicBenchSpec.scala @@ -28,9 +28,8 @@ object AddressTerminatedTopicBenchSpec { AddressTerminatedTopic(context.system).subscribe(self) testActor ! "started" - override def postStop(): Unit = { + override def postStop(): Unit = AddressTerminatedTopic(context.system).unsubscribe(self) - } def receive = Actor.emptyBehavior } @@ -55,9 +54,8 @@ class AddressTerminatedTopicBenchSpec extends PekkoSpec("pekko.loglevel=INFO") { val t2 = System.nanoTime() shutdown(sys, 10.seconds, verifySystemShutdown = true) log.info("Stopping {} actors took {} ms", num, (System.nanoTime() - t2).nanos.toMillis) - } finally { + } finally shutdown(sys) - } } } diff --git a/actor-tests/src/test/scala/org/apache/pekko/event/EventStreamSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/event/EventStreamSpec.scala index ac19fb1c182..1e3020aaab2 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/event/EventStreamSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/event/EventStreamSpec.scala @@ -54,7 +54,7 @@ object EventStreamSpec { bus.subscribe(context.self, classOf[SetTarget]) bus.subscribe(context.self, classOf[UnhandledMessage]) sender() ! Logging.LoggerInitialized - case SetTarget(ref) => { dst = ref; dst ! "OK" } + case SetTarget(ref) => dst = ref; dst ! "OK" case e: Logging.LogEvent => dst ! e case u: UnhandledMessage => dst ! u } @@ -101,15 +101,15 @@ class EventStreamSpec extends PekkoSpec(EventStreamSpec.config) { "not allow null as subscriber" in { val bus = new EventStream(system, true) - intercept[IllegalArgumentException] { bus.subscribe(null, classOf[M]) }.getMessage should ===( + intercept[IllegalArgumentException](bus.subscribe(null, classOf[M])).getMessage should ===( "subscriber is null") } "not allow null as unsubscriber" in { val bus = new EventStream(system, true) - intercept[IllegalArgumentException] { bus.unsubscribe(null, classOf[M]) }.getMessage should ===( + intercept[IllegalArgumentException](bus.unsubscribe(null, classOf[M])).getMessage should ===( "subscriber is null") - intercept[IllegalArgumentException] { bus.unsubscribe(null) }.getMessage should ===("subscriber is null") + intercept[IllegalArgumentException](bus.unsubscribe(null)).getMessage should ===("subscriber is null") } "be able to log unhandled messages" in { @@ -125,9 +125,8 @@ class EventStreamSpec extends PekkoSpec(EventStreamSpec.config) { sys.deadLetters.getClass, "unhandled message from " + sys.deadLetters + ": 42")) sys.eventStream.unsubscribe(testActor) - } finally { + } finally shutdown(sys) - } } "manage log levels" in { @@ -319,9 +318,8 @@ class EventStreamSpec extends PekkoSpec(EventStreamSpec.config) { a1.expectNoMessage(1.second) a2.expectMsg(tm) - } finally { + } finally shutdown(sys) - } } "unsubscribe the actor, when it subscribes already in terminated state" in { @@ -350,9 +348,8 @@ class EventStreamSpec extends PekkoSpec(EventStreamSpec.config) { es.subscribe(terminated, classOf[A]) should ===(true) } fishForDebugMessage(probe, s"unsubscribing $terminated from all channels") - } finally { + } finally shutdown(sys) - } } "not allow initializing a TerminatedUnsubscriber twice" in { @@ -367,9 +364,8 @@ class EventStreamSpec extends PekkoSpec(EventStreamSpec.config) { refWillBeUsedAsUnsubscriber should equal(false) - } finally { + } finally shutdown(sys) - } } "unwatch an actor from unsubscriber when that actor unsubscribes from the stream" in { @@ -387,9 +383,8 @@ class EventStreamSpec extends PekkoSpec(EventStreamSpec.config) { es.unsubscribe(a2.ref) fishForDebugMessage(a1, s"unwatching ${a2.ref}") - } finally { + } finally shutdown(sys) - } } "unwatch an actor from unsubscriber when that actor unsubscribes from channels it subscribed" in { @@ -424,9 +419,8 @@ class EventStreamSpec extends PekkoSpec(EventStreamSpec.config) { es.unsubscribe(a2.ref, classOf[T]) should equal(false) - } finally { + } finally shutdown(sys) - } } } @@ -440,11 +434,10 @@ class EventStreamSpec extends PekkoSpec(EventStreamSpec.config) { msg.foreach(expectMsg(_)) } - private def fishForDebugMessage(a: TestProbe, messagePrefix: String): Unit = { + private def fishForDebugMessage(a: TestProbe, messagePrefix: String): Unit = a.fishForMessage(hint = "expected debug message prefix: " + messagePrefix) { case Logging.Debug(_, _, msg: String) if msg.startsWith(messagePrefix) => true case _ => false } - } } diff --git a/actor-tests/src/test/scala/org/apache/pekko/event/LoggerSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/event/LoggerSpec.scala index 409027a5e9c..445e5837812 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/event/LoggerSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/event/LoggerSpec.scala @@ -109,15 +109,15 @@ object LoggerSpec { ref ! "OK" case event: LogEvent if !event.mdc.isEmpty => print(event) - target.foreach { _ ! event } + target.foreach(_ ! event) case event: LogEvent => print(event) - target.foreach { _ ! event.message } + target.foreach(_ ! event.message) } } class SlowLogger extends Logging.DefaultLogger { - override def aroundReceive(r: Receive, msg: Any): Unit = { + override def aroundReceive(r: Receive, msg: Any): Unit = msg match { case event: LogEvent => if (event.message.toString.startsWith("msg1")) @@ -126,7 +126,6 @@ object LoggerSpec { case _ => super.aroundReceive(r, msg) } - } } class ActorWithMDC extends Actor with DiagnosticActorLogging { @@ -172,9 +171,8 @@ class LoggerSpec extends AnyWordSpec with Matchers { } else { probe.expectNoMessage(0.5.seconds.dilated) } - } finally { + } finally TestKit.shutdownActorSystem(system) - } } out } @@ -230,9 +228,8 @@ class LoggerSpec extends AnyWordSpec with Matchers { system.log.warning("log it") probe1.expectMsg("log it") probe2.expectMsg("log it") - } finally { + } finally TestKit.shutdownActorSystem(system) - } } } } @@ -272,9 +269,8 @@ class LoggerSpec extends AnyWordSpec with Matchers { case w @ Warning(_, _, "Current Message removed from MDC") if w.mdc.size == 1 && w.mdc("requestId") == 4 => } - } finally { + } finally TestKit.shutdownActorSystem(system) - } } } @@ -347,11 +343,10 @@ class LoggerSpec extends AnyWordSpec with Matchers { "Ticket 3165 - serialize-messages and dual-entry serialization of LogEvent" must { "not cause StackOverflowError" in { implicit val s = ActorSystem("foo", ticket3165Config) - try { + try SerializationExtension(s).serialize(Warning("foo", classOf[String])) - } finally { + finally TestKit.shutdownActorSystem(s) - } } } } diff --git a/actor-tests/src/test/scala/org/apache/pekko/event/LoggingReceiveSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/event/LoggingReceiveSpec.scala index 503c6842dda..05d902ddcec 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/event/LoggingReceiveSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/event/LoggingReceiveSpec.scala @@ -58,11 +58,10 @@ class LoggingReceiveSpec extends AnyWordSpec with BeforeAndAfterAll { appAuto.eventStream.publish(filter) appLifecycle.eventStream.publish(filter) - def ignoreMute(t: TestKit): Unit = { + def ignoreMute(t: TestKit): Unit = t.ignoreMsg { case (_: TestEvent.Mute | _: TestEvent.UnMute) => true } - } override def afterAll(): Unit = { TestKit.shutdownActorSystem(appLogging) @@ -294,7 +293,7 @@ class LoggingReceiveSpec extends AnyWordSpec with BeforeAndAfterAll { def expectMsgAllPF(messages: Int)(matchers: PartialFunction[AnyRef, Int]): Set[Int] = { val max = remainingOrDefault - @tailrec def receiveNMatching(gotMatching: Set[Int], unknown: Vector[Any]): Set[Int] = { + @tailrec def receiveNMatching(gotMatching: Set[Int], unknown: Vector[Any]): Set[Int] = if (unknown.size >= 20) throw new IllegalStateException(s"Got too many unknown messages: [${unknown.mkString(", ")}]") else if (gotMatching.size == messages) gotMatching @@ -307,7 +306,6 @@ class LoggingReceiveSpec extends AnyWordSpec with BeforeAndAfterAll { if (matchers.isDefinedAt(msg)) receiveNMatching(gotMatching + matchers(msg), Vector.empty) else receiveNMatching(gotMatching, unknown :+ msg) // unknown message, just ignore } - } val set = receiveNMatching(Set.empty, Vector.empty) assert(set == (0 until messages).toSet) set diff --git a/actor-tests/src/test/scala/org/apache/pekko/event/jul/JavaLoggerSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/event/jul/JavaLoggerSpec.scala index 87625c2cf49..35cf5d2c4fa 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/event/jul/JavaLoggerSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/event/jul/JavaLoggerSpec.scala @@ -51,9 +51,8 @@ class JavaLoggerSpec extends PekkoSpec(JavaLoggerSpec.config) { val logger = logging.Logger.getLogger(classOf[JavaLoggerSpec.LogProducer].getName) logger.setUseParentHandlers(false) // turn off output of test LogRecords logger.addHandler(new logging.Handler { - def publish(record: logging.LogRecord): Unit = { + def publish(record: logging.LogRecord): Unit = testActor ! record - } def flush(): Unit = {} def close(): Unit = {} diff --git a/actor-tests/src/test/scala/org/apache/pekko/io/InetAddressDnsResolverSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/io/InetAddressDnsResolverSpec.scala index a4241270a47..f1d031b64e8 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/io/InetAddressDnsResolverSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/io/InetAddressDnsResolverSpec.scala @@ -113,9 +113,8 @@ class InetAddressDnsResolverSpec extends PekkoSpec(""" try { System.setProperty(property, testValue) test - } finally { + } finally oldValue.foreach(v => System.setProperty(property, v)) - } } private def withNewSecurityProperty[T](property: String, testValue: String)(test: => T): T = { @@ -123,9 +122,8 @@ class InetAddressDnsResolverSpec extends PekkoSpec(""" try { Security.setProperty(property, testValue) test - } finally { + } finally oldValue.foreach(v => Security.setProperty(property, v)) - } } } diff --git a/actor-tests/src/test/scala/org/apache/pekko/io/TcpConnectionSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/io/TcpConnectionSpec.scala index 1c654892143..01db993e2ed 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/io/TcpConnectionSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/io/TcpConnectionSpec.scala @@ -257,9 +257,8 @@ class TcpConnectionSpec extends PekkoSpec(""" val writer = Files.newBufferedWriter(tmpFile) val oneKByteOfF = Array.fill[Char](1000)('F') // 10 mb of f:s in a file - for (_ <- 0 to 10000) { + for (_ <- 0 to 10000) writer.write(oneKByteOfF) - } writer.flush() writer.close() try { @@ -268,9 +267,8 @@ class TcpConnectionSpec extends PekkoSpec(""" writer.send(connectionActor, WritePath(tmpFile, 0, size, Ack)) pullFromServerSide(size, 1000000) writer.expectMsg(Ack) - } finally { + } finally fs.close() - } } } @@ -859,7 +857,7 @@ class TcpConnectionSpec extends PekkoSpec(""" connectionActor ! PoisonPill watch(connectionActor) expectTerminated(connectionActor) - an[IOException] should be thrownBy { socket.getInputStream.read() } + an[IOException] should be thrownBy socket.getInputStream.read() } catch { case e: SocketTimeoutException => // thrown by serverSocket.accept, this may happen if network is offline @@ -893,19 +891,17 @@ class TcpConnectionSpec extends PekkoSpec(""" var registerCallReceiver = TestProbe() var interestCallReceiver = TestProbe() - def ignoreWindowsWorkaroundForTicket15766(): Unit = { + def ignoreWindowsWorkaroundForTicket15766(): Unit = // Due to the Windows workaround of #15766 we need to set an OP_CONNECT to reliably detect connection resets if (Helpers.isWindows) interestCallReceiver.expectMsg(OP_CONNECT) - } - def run(body: => Unit): Unit = { + def run(body: => Unit): Unit = try { setServerSocketOptions() localServerChannel.socket.bind(serverAddress) localServerChannel.configureBlocking(false) body } finally localServerChannel.close() - } def register(channel: SelectableChannel, initialOps: Int)(implicit channelActor: ActorRef): Unit = registerCallReceiver.ref.tell(Registration(channel, initialOps), channelActor) @@ -977,13 +973,12 @@ class TcpConnectionSpec extends PekkoSpec(""" lazy val serverSelectionKey = registerChannel(serverSideChannel, "server") lazy val defaultbuffer = ByteBuffer.allocate(TestSize) - def windowsWorkaroundToDetectAbort(): Unit = { + def windowsWorkaroundToDetectAbort(): Unit = // Due to a Windows quirk we need to set an OP_CONNECT to reliably detect connection resets, see #1576 if (Helpers.isWindows) { serverSelectionKey.interestOps(OP_CONNECT) nioSelector.select(10) } - } override def ignoreWindowsWorkaroundForTicket15766(): Unit = { super.ignoreWindowsWorkaroundForTicket15766() diff --git a/actor-tests/src/test/scala/org/apache/pekko/io/TcpIntegrationSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/io/TcpIntegrationSpec.scala index f02bb50beeb..cd1f355a431 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/io/TcpIntegrationSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/io/TcpIntegrationSpec.scala @@ -195,9 +195,9 @@ class TcpIntegrationSpec extends PekkoSpec(""" val connectionActor = connectCommander.lastSender connectCommander.send(connectionActor, PoisonPill) failAfter(3 seconds) { - try { + try accept.getInputStream.read() should ===(-1) - } catch { + catch { case _: IOException => // this is also fine } } diff --git a/actor-tests/src/test/scala/org/apache/pekko/io/dns/AsyncDnsResolverIntegrationSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/io/dns/AsyncDnsResolverIntegrationSpec.scala index 1f7e658b580..7fe5f3dcbd9 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/io/dns/AsyncDnsResolverIntegrationSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/io/dns/AsyncDnsResolverIntegrationSpec.scala @@ -203,7 +203,7 @@ class AsyncDnsResolverIntegrationSpec } } - def resolve(name: String, requestType: RequestType = Ip()): DnsProtocol.Resolved = { + def resolve(name: String, requestType: RequestType = Ip()): DnsProtocol.Resolved = try { (IO(Dns) ? DnsProtocol.Resolve(name, requestType)).mapTo[DnsProtocol.Resolved].futureValue } catch { @@ -211,7 +211,6 @@ class AsyncDnsResolverIntegrationSpec dumpNameserverLogs() throw e } - } } } diff --git a/actor-tests/src/test/scala/org/apache/pekko/io/dns/DockerBindDnsService.scala b/actor-tests/src/test/scala/org/apache/pekko/io/dns/DockerBindDnsService.scala index 066f27fb395..0d193e5aaf2 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/io/dns/DockerBindDnsService.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/io/dns/DockerBindDnsService.scala @@ -55,12 +55,12 @@ abstract class DockerBindDnsService(config: Config) extends PekkoSpec(config) wi // https://github.com/sameersbn/docker-bind/pull/61 val image = "raboof/bind:9.11.3-20180713-nochown" - try { + try client .pullImageCmd(image) .start() .awaitCompletion() - } catch { + catch { case NonFatal(_) => log.warning(s"Failed to pull docker image [$image], is docker running?") return @@ -86,12 +86,12 @@ abstract class DockerBindDnsService(config: Config) extends PekkoSpec(config) wi .exec() .asScala .find((c: Container) => c.getNames().exists(_.contains(containerName))) - .foreach((c: Container) => { + .foreach { (c: Container) => if ("running" == c.getState()) { client.killContainerCmd(c.getId()).exec() } client.removeContainerCmd(c.getId()).exec() - }) + } val creation = containerCommand.exec() if (creation.getWarnings() != null) @@ -112,7 +112,7 @@ abstract class DockerBindDnsService(config: Config) extends PekkoSpec(config) wi } def dumpNameserverLogs(): Unit = { - id.foreach(id => { + id.foreach { id => val reader = new StringBuilderLogReader client .logContainerCmd(id) @@ -121,8 +121,8 @@ abstract class DockerBindDnsService(config: Config) extends PekkoSpec(config) wi .awaitCompletion() log.info("Nameserver std out: {} ", reader.toString()) - }) - id.foreach(id => { + } + id.foreach { id => val reader = new StringBuilderLogReader client .logContainerCmd(id) @@ -130,7 +130,7 @@ abstract class DockerBindDnsService(config: Config) extends PekkoSpec(config) wi .exec(reader) .awaitCompletion() log.info("Nameserver std err: {} ", reader.toString()) - }) + } } override def afterTermination(): Unit = { diff --git a/actor-tests/src/test/scala/org/apache/pekko/io/dns/internal/AsyncDnsResolverSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/io/dns/internal/AsyncDnsResolverSpec.scala index 2c504f6bca8..3bb5476b216 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/io/dns/internal/AsyncDnsResolverSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/io/dns/internal/AsyncDnsResolverSpec.scala @@ -304,8 +304,7 @@ class AsyncDnsResolverSpec extends PekkoSpec(""" def resolver(clients: List[ActorRef], config: Config): ActorRef = { val settings = new DnsSettings(system.asInstanceOf[ExtendedActorSystem], config) system.actorOf(Props(new AsyncDnsResolver(settings, new SimpleDnsCache(), - (_, _) => { - clients - }, IdGenerator()))) + (_, _) => + clients, IdGenerator()))) } } diff --git a/actor-tests/src/test/scala/org/apache/pekko/io/dns/internal/DnsClientSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/io/dns/internal/DnsClientSpec.scala index 11c4910de9a..a5c77e3560c 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/io/dns/internal/DnsClientSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/io/dns/internal/DnsClientSpec.scala @@ -279,7 +279,7 @@ package internal { msg.answerRecs.foreach(write(_, ret)) } - def write(msg: ResourceRecord, ret: ByteStringBuilder): Unit = { + def write(msg: ResourceRecord, ret: ByteStringBuilder): Unit = msg match { case ARecord(name, ttl, ip) => DomainName.write(ret, name) @@ -291,6 +291,5 @@ package internal { case _ => throw new IllegalStateException(s"Tests cannot write messages of type ${msg.getClass}") } - } } } diff --git a/actor-tests/src/test/scala/org/apache/pekko/io/dns/internal/ResolvConfParserSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/io/dns/internal/ResolvConfParserSpec.scala index 2858f47e86a..9383688f55b 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/io/dns/internal/ResolvConfParserSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/io/dns/internal/ResolvConfParserSpec.scala @@ -18,9 +18,8 @@ import org.scalatest.wordspec.AnyWordSpec class ResolvConfParserSpec extends AnyWordSpec with Matchers { - private def parse(str: String): ResolvConf = { + private def parse(str: String): ResolvConf = ResolvConfParser.parseLines(str.linesIterator) - } "The ResolvConfParser" should { diff --git a/actor-tests/src/test/scala/org/apache/pekko/pattern/BackoffOnRestartSupervisorSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/pattern/BackoffOnRestartSupervisorSpec.scala index d739891d619..9266772be0a 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/pattern/BackoffOnRestartSupervisorSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/pattern/BackoffOnRestartSupervisorSpec.scala @@ -157,9 +157,8 @@ class BackoffOnRestartSupervisorSpec extends PekkoSpec(""" sender() ! "PONG" } - override def postStop(): Unit = { + override def postStop(): Unit = latch.await(3, TimeUnit.SECONDS) - } } "accept commands while child is terminating" in { diff --git a/actor-tests/src/test/scala/org/apache/pekko/pattern/CircuitBreakerSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/pattern/CircuitBreakerSpec.scala index e1c125eab8f..0ddef891b2c 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/pattern/CircuitBreakerSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/pattern/CircuitBreakerSpec.scala @@ -60,18 +60,18 @@ object CircuitBreakerSpec { .onClose(closedLatch.countDown()) .onHalfOpen(halfOpenLatch.countDown()) .onOpen(openLatch.countDown()) - .onCallSuccess(value => { + .onCallSuccess { value => probe.ref ! CBSuccess(value.nanos) callSuccessLatch.countDown() - }) - .onCallFailure(value => { + } + .onCallFailure { value => probe.ref ! CBFailure(value.nanos) callFailureLatch.countDown() - }) - .onCallTimeout(value => { + } + .onCallTimeout { value => probe.ref ! CBTimeout(value.nanos) callTimeoutLatch.countDown() - }) + } .onCallBreakerOpen(callBreakerOpenLatch.countDown()) } @@ -137,24 +137,24 @@ class CircuitBreakerSpec extends PekkoSpec(""" "throw exceptions when called before reset timeout" taggedAs TimingTest in { val breaker = longResetTimeoutCb() - intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) } + intercept[TestException](breaker().withSyncCircuitBreaker(throwException)) checkLatch(breaker.openLatch) - val e = intercept[CircuitBreakerOpenException] { breaker().withSyncCircuitBreaker(sayHi) } + val e = intercept[CircuitBreakerOpenException](breaker().withSyncCircuitBreaker(sayHi)) e.remainingDuration should be > Duration.Zero e.remainingDuration should be <= longResetTimeout } "transition to half-open on reset timeout" taggedAs TimingTest in { val breaker = shortResetTimeoutCb() - intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) } + intercept[TestException](breaker().withSyncCircuitBreaker(throwException)) checkLatch(breaker.halfOpenLatch) } "still be in open state after calling success method" taggedAs TimingTest in { val breaker = longResetTimeoutCb() - intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) } + intercept[TestException](breaker().withSyncCircuitBreaker(throwException)) checkLatch(breaker.openLatch) breaker().succeed() breaker().isOpen should ===(true) @@ -162,7 +162,7 @@ class CircuitBreakerSpec extends PekkoSpec(""" "still be in open state after calling fail method" taggedAs TimingTest in { val breaker = longResetTimeoutCb() - intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) } + intercept[TestException](breaker().withSyncCircuitBreaker(throwException)) checkLatch(breaker.openLatch) breaker().fail() breaker().isOpen should ===(true) @@ -170,22 +170,22 @@ class CircuitBreakerSpec extends PekkoSpec(""" "invoke onHalfOpen during transition to half-open state" taggedAs TimingTest in { val breaker = shortResetTimeoutCb() - intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) } + intercept[TestException](breaker().withSyncCircuitBreaker(throwException)) checkLatch(breaker.halfOpenLatch) } "invoke onCallBreakerOpen when called before reset timeout" taggedAs TimingTest in { val breaker = longResetTimeoutCb() - intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) } + intercept[TestException](breaker().withSyncCircuitBreaker(throwException)) checkLatch(breaker.openLatch) - intercept[CircuitBreakerOpenException] { breaker().withSyncCircuitBreaker(sayHi) } + intercept[CircuitBreakerOpenException](breaker().withSyncCircuitBreaker(sayHi)) checkLatch(breaker.callBreakerOpenLatch) } "invoke onCallFailure when call results in exception" taggedAs TimingTest in { val breaker = longResetTimeoutCb() - intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) } + intercept[TestException](breaker().withSyncCircuitBreaker(throwException)) checkLatch(breaker.callFailureLatch) val failure = breaker.probe.expectMsgType[CBFailure] @@ -196,7 +196,7 @@ class CircuitBreakerSpec extends PekkoSpec(""" "A synchronous circuit breaker that is half-open" must { "pass through next call and close on success" taggedAs TimingTest in { val breaker = shortResetTimeoutCb() - intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) } + intercept[TestException](breaker().withSyncCircuitBreaker(throwException)) checkLatch(breaker.halfOpenLatch) assert("hi" == breaker().withSyncCircuitBreaker(sayHi)) checkLatch(breaker.closedLatch) @@ -205,29 +205,29 @@ class CircuitBreakerSpec extends PekkoSpec(""" "pass through next call and close on exception" when { "exception is defined as call succeeded" taggedAs TimingTest in { val breaker = shortResetTimeoutCb() - intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) } + intercept[TestException](breaker().withSyncCircuitBreaker(throwException)) checkLatch(breaker.halfOpenLatch) val allReturnIsSuccess: Try[String] => Boolean = _ => false - intercept[TestException] { breaker().withSyncCircuitBreaker(throwException, allReturnIsSuccess) } + intercept[TestException](breaker().withSyncCircuitBreaker(throwException, allReturnIsSuccess)) checkLatch(breaker.closedLatch) } } "open on exception in call" taggedAs TimingTest in { val breaker = shortResetTimeoutCb() - intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) } + intercept[TestException](breaker().withSyncCircuitBreaker(throwException)) checkLatch(breaker.halfOpenLatch) breaker.openLatch.reset() - intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) } + intercept[TestException](breaker().withSyncCircuitBreaker(throwException)) checkLatch(breaker.openLatch) } "open on even number" when { "even number is defined as failure" taggedAs TimingTest in { val breaker = shortResetTimeoutCb() - intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) } + intercept[TestException](breaker().withSyncCircuitBreaker(throwException)) checkLatch(breaker.halfOpenLatch) breaker.openLatch.reset() breaker().withSyncCircuitBreaker(2, evenNumberIsFailure) @@ -237,7 +237,7 @@ class CircuitBreakerSpec extends PekkoSpec(""" "open on calling fail method" taggedAs TimingTest in { val breaker = shortResetTimeoutCb() - intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) } + intercept[TestException](breaker().withSyncCircuitBreaker(throwException)) checkLatch(breaker.halfOpenLatch) breaker.openLatch.reset() breaker().fail() @@ -246,7 +246,7 @@ class CircuitBreakerSpec extends PekkoSpec(""" "close on calling success method" taggedAs TimingTest in { val breaker = shortResetTimeoutCb() - intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) } + intercept[TestException](breaker().withSyncCircuitBreaker(throwException)) checkLatch(breaker.halfOpenLatch) breaker().succeed() checkLatch(breaker.closedLatch) @@ -255,7 +255,7 @@ class CircuitBreakerSpec extends PekkoSpec(""" "pass through next call and invoke onCallSuccess on success" taggedAs TimingTest in { val breaker = shortResetTimeoutCb() - intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) } + intercept[TestException](breaker().withSyncCircuitBreaker(throwException)) checkLatch(breaker.halfOpenLatch) breaker.probe.expectMsgType[CBFailure] @@ -269,13 +269,13 @@ class CircuitBreakerSpec extends PekkoSpec(""" "pass through next call and invoke onCallFailure on failure" taggedAs TimingTest in { val breaker = shortResetTimeoutCb() - intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) } + intercept[TestException](breaker().withSyncCircuitBreaker(throwException)) checkLatch(breaker.halfOpenLatch) checkLatch(breaker.callFailureLatch) breaker.callFailureLatch.reset() - intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) } + intercept[TestException](breaker().withSyncCircuitBreaker(throwException)) checkLatch(breaker.callFailureLatch) breaker.probe.expectMsgType[CBFailure] @@ -286,10 +286,10 @@ class CircuitBreakerSpec extends PekkoSpec(""" "pass through next call and invoke onCallTimeout on timeout" taggedAs TimingTest in { val breaker = shortCallTimeoutCb() - intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) } + intercept[TestException](breaker().withSyncCircuitBreaker(throwException)) checkLatch(breaker.halfOpenLatch) - intercept[TimeoutException] { breaker().withSyncCircuitBreaker(Thread.sleep(200.millis.dilated.toMillis)) } + intercept[TimeoutException](breaker().withSyncCircuitBreaker(Thread.sleep(200.millis.dilated.toMillis))) checkLatch(breaker.callTimeoutLatch) breaker.probe.expectMsgType[CBFailure] @@ -300,11 +300,11 @@ class CircuitBreakerSpec extends PekkoSpec(""" "pass through next call and invoke onCallBreakerOpen while executing other" taggedAs TimingTest in { val breaker = shortResetTimeoutCb() - intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) } + intercept[TestException](breaker().withSyncCircuitBreaker(throwException)) checkLatch(breaker.halfOpenLatch) breaker().withCircuitBreaker(Future(Thread.sleep(250.millis.dilated.toMillis))) - intercept[CircuitBreakerOpenException] { breaker().withSyncCircuitBreaker(sayHi) } + intercept[CircuitBreakerOpenException](breaker().withSyncCircuitBreaker(sayHi)) checkLatch(breaker.callBreakerOpenLatch) } @@ -312,7 +312,7 @@ class CircuitBreakerSpec extends PekkoSpec(""" "pass through next call and invoke onCallSuccess after transition to open state" taggedAs TimingTest in { val breaker = shortResetTimeoutCb() - intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) } + intercept[TestException](breaker().withSyncCircuitBreaker(throwException)) checkLatch(breaker.halfOpenLatch) breaker().withSyncCircuitBreaker(Future.successful(sayHi)) @@ -329,7 +329,7 @@ class CircuitBreakerSpec extends PekkoSpec(""" "increment failure count on failure" taggedAs TimingTest in { val breaker = longCallTimeoutCb() breaker().currentFailureCount should ===(0) - intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) } + intercept[TestException](breaker().withSyncCircuitBreaker(throwException)) checkLatch(breaker.openLatch) breaker().currentFailureCount should ===(1) } @@ -359,7 +359,7 @@ class CircuitBreakerSpec extends PekkoSpec(""" breaker().currentFailureCount should ===(0) intercept[TestException] { val ct = Thread.currentThread() // Ensure that the thunk is executed in the tests thread - breaker().withSyncCircuitBreaker { if (Thread.currentThread() eq ct) throwException else "fail" } + breaker().withSyncCircuitBreaker(if (Thread.currentThread() eq ct) throwException else "fail") } breaker().currentFailureCount should ===(1) breaker().withSyncCircuitBreaker(sayHi) @@ -372,7 +372,7 @@ class CircuitBreakerSpec extends PekkoSpec(""" breaker().currentFailureCount should ===(0) intercept[TestException] { val ct = Thread.currentThread() // Ensure that the thunk is executed in the tests thread - breaker().withSyncCircuitBreaker { if (Thread.currentThread() eq ct) throwException else "fail" } + breaker().withSyncCircuitBreaker(if (Thread.currentThread() eq ct) throwException else "fail") } breaker().currentFailureCount should ===(1) @@ -395,7 +395,7 @@ class CircuitBreakerSpec extends PekkoSpec(""" breaker().currentFailureCount should ===(0) intercept[TestException] { val ct = Thread.currentThread() // Ensure that the thunk is executed in the tests thread - breaker().withSyncCircuitBreaker { if (Thread.currentThread() eq ct) throwException else "fail" } + breaker().withSyncCircuitBreaker(if (Thread.currentThread() eq ct) throwException else "fail") } breaker().currentFailureCount should ===(1) breaker().succeed() @@ -469,7 +469,7 @@ class CircuitBreakerSpec extends PekkoSpec(""" checkLatch(breaker.openLatch) - intercept[CircuitBreakerOpenException] { Await.result(breaker().withCircuitBreaker(Future(sayHi)), awaitTimeout) } + intercept[CircuitBreakerOpenException](Await.result(breaker().withCircuitBreaker(Future(sayHi)), awaitTimeout)) } "transition to half-open on reset timeout" taggedAs TimingTest in { @@ -483,7 +483,7 @@ class CircuitBreakerSpec extends PekkoSpec(""" breaker().withCircuitBreaker(Future(throwException)) checkLatch(breaker.openLatch) - val e1 = intercept[CircuitBreakerOpenException] { breaker().withSyncCircuitBreaker(sayHi) } + val e1 = intercept[CircuitBreakerOpenException](breaker().withSyncCircuitBreaker(sayHi)) val shortRemainingDuration = e1.remainingDuration Thread.sleep(1000.millis.dilated.toMillis) @@ -494,7 +494,7 @@ class CircuitBreakerSpec extends PekkoSpec(""" breaker().withCircuitBreaker(Future(throwException)) checkLatch(breaker.openLatch) - val e2 = intercept[CircuitBreakerOpenException] { breaker().withSyncCircuitBreaker(sayHi) } + val e2 = intercept[CircuitBreakerOpenException](breaker().withSyncCircuitBreaker(sayHi)) val longRemainingDuration = e2.remainingDuration shortRemainingDuration should be < longRemainingDuration @@ -503,7 +503,7 @@ class CircuitBreakerSpec extends PekkoSpec(""" "invoke onHalfOpen during transition to half-open state" taggedAs TimingTest in { val breaker = shortResetTimeoutCb() - intercept[TestException] { Await.result(breaker().withCircuitBreaker(Future(throwException)), awaitTimeout) } + intercept[TestException](Await.result(breaker().withCircuitBreaker(Future(throwException)), awaitTimeout)) checkLatch(breaker.halfOpenLatch) } @@ -553,14 +553,14 @@ class CircuitBreakerSpec extends PekkoSpec(""" breaker().withCircuitBreaker(Future(throwException)) checkLatch(breaker.halfOpenLatch) breaker.openLatch.reset() - intercept[TestException] { Await.result(breaker().withCircuitBreaker(Future(throwException)), awaitTimeout) } + intercept[TestException](Await.result(breaker().withCircuitBreaker(Future(throwException)), awaitTimeout)) checkLatch(breaker.openLatch) } "re-open on even number" when { "even number is defined as failure" taggedAs TimingTest in { val breaker = shortResetTimeoutCb() - intercept[TestException] { breaker().withSyncCircuitBreaker(throwException) } + intercept[TestException](breaker().withSyncCircuitBreaker(throwException)) checkLatch(breaker.halfOpenLatch) breaker.openLatch.reset() Await.result(breaker().withCircuitBreaker(Future(2), evenNumberIsFailure), awaitTimeout) @@ -653,7 +653,7 @@ class CircuitBreakerSpec extends PekkoSpec(""" "increment failure count on exception" taggedAs TimingTest in { val breaker = longCallTimeoutCb() - intercept[TestException] { Await.result(breaker().withCircuitBreaker(Future(throwException)), awaitTimeout) } + intercept[TestException](Await.result(breaker().withCircuitBreaker(Future(throwException)), awaitTimeout)) checkLatch(breaker.openLatch) breaker().currentFailureCount should ===(1) } @@ -772,13 +772,13 @@ class CircuitBreakerSpec extends PekkoSpec(""" "be closed after throw allowable exception" taggedAs TimingTest in { breaker.resetAll() - intercept[AllowException] { Await.result(cb.withCircuitBreaker(Future(throwAllowException)), awaitTimeout) } + intercept[AllowException](Await.result(cb.withCircuitBreaker(Future(throwAllowException)), awaitTimeout)) checkLatch(breaker.callSuccessLatch) } "be open after throw exception and half-open after reset timeout" taggedAs TimingTest in { breaker.resetAll() - intercept[TestException] { Await.result(cb.withCircuitBreaker(Future(throwException)), awaitTimeout) } + intercept[TestException](Await.result(cb.withCircuitBreaker(Future(throwException)), awaitTimeout)) checkLatch(breaker.openLatch) Thread.sleep(250.millis.dilated(system).toMillis) checkLatch(breaker.halfOpenLatch) diff --git a/actor-tests/src/test/scala/org/apache/pekko/pattern/CircuitBreakerStressSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/pattern/CircuitBreakerStressSpec.scala index 2123862d05c..8353593ec96 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/pattern/CircuitBreakerStressSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/pattern/CircuitBreakerStressSpec.scala @@ -80,9 +80,8 @@ class CircuitBreakerStressSpec extends PekkoSpec with ImplicitSender { val stressActors = Vector.fill(3) { system.actorOf(Props(classOf[StressActor], breaker)) } - for (_ <- 0 to 1000; a <- stressActors) { + for (_ <- 0 to 1000; a <- stressActors) a ! JobDone - } // let them work for a while Thread.sleep(3000) stressActors.foreach { a => diff --git a/actor-tests/src/test/scala/org/apache/pekko/pattern/PatternSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/pattern/PatternSpec.scala index 3e70bc781dc..0184195d716 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/pattern/PatternSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/pattern/PatternSpec.scala @@ -55,7 +55,7 @@ class PatternSpec extends PekkoSpec { val target = system.actorOf(Props[TargetActor]()) val latch = TestLatch() target ! ((latch, remainingOrDefault)) - intercept[AskTimeoutException] { Await.result(gracefulStop(target, 500 millis), remainingOrDefault) } + intercept[AskTimeoutException](Await.result(gracefulStop(target, 500 millis), remainingOrDefault)) latch.open() } } @@ -75,7 +75,7 @@ class PatternSpec extends PekkoSpec { pekko.pattern.after(1 second, using = system.scheduler)(Future.failed(new IllegalStateException("Mexico"))) val r = Future.firstCompletedOf(Seq(Promise[Int]().future, f)) - intercept[IllegalStateException] { Await.result(r, remainingOrDefault) }.getMessage should ===("Mexico") + intercept[IllegalStateException](Await.result(r, remainingOrDefault)).getMessage should ===("Mexico") } } } diff --git a/actor-tests/src/test/scala/org/apache/pekko/pattern/RetrySpec.scala b/actor-tests/src/test/scala/org/apache/pekko/pattern/RetrySpec.scala index 5aa9e093c3e..9ca765a58ab 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/pattern/RetrySpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/pattern/RetrySpec.scala @@ -57,19 +57,18 @@ class RetrySpec extends PekkoSpec with RetrySupport { val retried = retry(() => Future.failed(new IllegalStateException("Mexico")), 5, 100 milliseconds) within(3 second) { - intercept[IllegalStateException] { Await.result(retried, remaining) }.getMessage should ===("Mexico") + intercept[IllegalStateException](Await.result(retried, remaining)).getMessage should ===("Mexico") } } "return a success for a Future that succeeds eventually" in { @volatile var failCount = 0 - def attempt() = { + def attempt() = if (failCount < 5) { failCount += 1 Future.failed(new IllegalStateException(failCount.toString)) } else Future.successful(5) - } val retried = retry(() => attempt(), 10, 100 milliseconds) @@ -81,17 +80,16 @@ class RetrySpec extends PekkoSpec with RetrySupport { "return a failure for a Future that would have succeeded but retires were exhausted" in { @volatile var failCount = 0 - def attempt() = { + def attempt() = if (failCount < 10) { failCount += 1 Future.failed(new IllegalStateException(failCount.toString)) } else Future.successful(5) - } val retried = retry(() => attempt(), 5, 100 milliseconds) within(3 seconds) { - intercept[IllegalStateException] { Await.result(retried, remaining) }.getMessage should ===("6") + intercept[IllegalStateException](Await.result(retried, remaining)).getMessage should ===("6") } } @@ -99,12 +97,11 @@ class RetrySpec extends PekkoSpec with RetrySupport { @volatile var failCount = 0 @volatile var attemptedCount = 0; - def attempt() = { + def attempt() = if (failCount < 10) { failCount += 1 Future.failed(new IllegalStateException(failCount.toString)) } else Future.successful(5) - } val retried = retry(() => attempt(), 5, attempted => { @@ -112,7 +109,7 @@ class RetrySpec extends PekkoSpec with RetrySupport { Some(100.milliseconds * attempted) }) within(30000000 seconds) { - intercept[IllegalStateException] { Await.result(retried, remaining) }.getMessage should ===("6") + intercept[IllegalStateException](Await.result(retried, remaining)).getMessage should ===("6") attemptedCount shouldBe 5 } } @@ -120,12 +117,11 @@ class RetrySpec extends PekkoSpec with RetrySupport { "retry can be attempted without any delay" in { @volatile var failCount = 0 - def attempt() = { + def attempt() = if (failCount < 1000) { failCount += 1 Future.failed(new IllegalStateException(failCount.toString)) } else Future.successful(1) - } val start = System.currentTimeMillis() val retried = retry(() => attempt(), 999) @@ -141,12 +137,11 @@ class RetrySpec extends PekkoSpec with RetrySupport { "handle thrown exceptions in same way as failed Future" in { @volatile var failCount = 0 - def attempt() = { + def attempt() = if (failCount < 5) { failCount += 1 throw new IllegalStateException(failCount.toString) } else Future.successful(5) - } val retried = retry(() => attempt(), 10, 100 milliseconds) @@ -157,9 +152,8 @@ class RetrySpec extends PekkoSpec with RetrySupport { "be able to retry with predicate for value" in { val counter = new AtomicInteger(0) - def attempt(): Future[Int] = { + def attempt(): Future[Int] = Future.successful(counter.incrementAndGet()) - } val retried = retry(() => attempt(), (t: Int, _) => t < 5, 10, 100 milliseconds) diff --git a/actor-tests/src/test/scala/org/apache/pekko/routing/BalancingSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/routing/BalancingSpec.scala index 8049e3d60da..04443e8710b 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/routing/BalancingSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/routing/BalancingSpec.scala @@ -92,18 +92,16 @@ class BalancingSpec extends PekkoSpec(""" val poolSize = 5 // must be less than fork-join parallelism-min, which is 8 in PekkoSpec - override def beforeEach(): Unit = { + override def beforeEach(): Unit = counter.set(1) - } def test(pool: ActorRef, startOthers: Promise[Unit], latch: TestLatch): Unit = { val probe = TestProbe() try { val iterationCount = 100 - for (i <- 1 to iterationCount) { + for (i <- 1 to iterationCount) pool.tell(i, probe.ref) - } // all but one worker are blocked val replies1 = probe.receiveN(iterationCount - poolSize + 1) diff --git a/actor-tests/src/test/scala/org/apache/pekko/routing/ConfiguredLocalRoutingSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/routing/ConfiguredLocalRoutingSpec.scala index 2e33fdbad4d..a3abc6336fa 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/routing/ConfiguredLocalRoutingSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/routing/ConfiguredLocalRoutingSpec.scala @@ -128,14 +128,13 @@ class ConfiguredLocalRoutingSpec case _ => throw new IllegalArgumentException(s"Unexpected actorref $ref") } - def collectRouteePaths(probe: TestProbe, router: ActorRef, n: Int): immutable.Seq[ActorPath] = { + def collectRouteePaths(probe: TestProbe, router: ActorRef, n: Int): immutable.Seq[ActorPath] = for (i <- 1 to n) yield { val msg = i.toString router.tell(msg, probe.ref) probe.expectMsg(msg) probe.lastSender.path } - } "RouterConfig" must { diff --git a/actor-tests/src/test/scala/org/apache/pekko/routing/MetricsBasedResizerSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/routing/MetricsBasedResizerSpec.scala index 0c930e491e6..e41d3a3d225 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/routing/MetricsBasedResizerSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/routing/MetricsBasedResizerSpec.scala @@ -81,10 +81,9 @@ object MetricsBasedResizerSpec { class MetricsBasedResizerSpec extends PekkoSpec(ResizerSpec.config) with DefaultTimeout with ImplicitSender { - override def atStartup(): Unit = { + override def atStartup(): Unit = // when shutting down some Resize messages might hang around system.eventStream.publish(Mute(EventFilter.warning(pattern = ".*Resize"))) - } "MetricsBasedResizer isTimeForResize" must { diff --git a/actor-tests/src/test/scala/org/apache/pekko/routing/RandomSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/routing/RandomSpec.scala index f99cf9b600e..a18d7ae13bf 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/routing/RandomSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/routing/RandomSpec.scala @@ -37,9 +37,8 @@ class RandomSpec extends PekkoSpec with DefaultTimeout with ImplicitSender { case "hello" => sender() ! "world" } - override def postStop(): Unit = { + override def postStop(): Unit = stopLatch.countDown() - } })), "random-shutdown") actor ! "hello" @@ -63,9 +62,8 @@ class RandomSpec extends PekkoSpec with DefaultTimeout with ImplicitSender { val counter = new AtomicInteger var replies = Map.empty[Int, Int] - for (i <- 0 until connectionCount) { + for (i <- 0 until connectionCount) replies = replies + (i -> 0) - } val actor = system.actorOf(RandomPool(connectionCount).props(routeeProps = Props(new Actor { lazy val id = counter.getAndIncrement() @@ -75,19 +73,18 @@ class RandomSpec extends PekkoSpec with DefaultTimeout with ImplicitSender { } })), name = "random") - for (_ <- 0 until iterationCount) { + for (_ <- 0 until iterationCount) for (_ <- 0 until connectionCount) { val id = Await.result((actor ? "hit").mapTo[Int], timeout.duration) replies = replies + (id -> (replies(id) + 1)) } - } counter.get should ===(connectionCount) actor ! pekko.routing.Broadcast("end") Await.ready(doneLatch, 5 seconds) - replies.values.foreach { _ should be > 0 } + replies.values.foreach(_ should be > 0) replies.values.sum should ===(iterationCount * connectionCount) } @@ -100,9 +97,8 @@ class RandomSpec extends PekkoSpec with DefaultTimeout with ImplicitSender { case "hello" => helloLatch.countDown() } - override def postStop(): Unit = { + override def postStop(): Unit = stopLatch.countDown() - } })), "random-broadcast") actor ! pekko.routing.Broadcast("hello") diff --git a/actor-tests/src/test/scala/org/apache/pekko/routing/ResizerSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/routing/ResizerSpec.scala index 7524ab6f233..801042bbb9e 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/routing/ResizerSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/routing/ResizerSpec.scala @@ -51,10 +51,9 @@ class ResizerSpec extends PekkoSpec(ResizerSpec.config) with DefaultTimeout with import pekko.routing.ResizerSpec._ - override def atStartup(): Unit = { + override def atStartup(): Unit = // when shutting down some Resize messages might hang around system.eventStream.publish(Mute(EventFilter.warning(pattern = ".*Resize"))) - } def routeeSize(router: ActorRef): Int = Await.result(router ? GetRoutees, timeout.duration).asInstanceOf[Routees].routees.size diff --git a/actor-tests/src/test/scala/org/apache/pekko/routing/RoundRobinSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/routing/RoundRobinSpec.scala index 1f7b1c5d247..1b1e68266fa 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/routing/RoundRobinSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/routing/RoundRobinSpec.scala @@ -44,9 +44,8 @@ class RoundRobinSpec extends PekkoSpec with DefaultTimeout with ImplicitSender { case "hello" => helloLatch.countDown() } - override def postStop(): Unit = { + override def postStop(): Unit = stopLatch.countDown() - } })), "round-robin-shutdown") actor ! "hello" @@ -86,7 +85,7 @@ class RoundRobinSpec extends PekkoSpec with DefaultTimeout with ImplicitSender { actor ! pekko.routing.Broadcast("end") Await.ready(doneLatch, 5 seconds) - replies.values.foreach { _ should ===(iterationCount) } + replies.values.foreach(_ should ===(iterationCount)) } "deliver a broadcast message using the !" in { @@ -98,9 +97,8 @@ class RoundRobinSpec extends PekkoSpec with DefaultTimeout with ImplicitSender { case "hello" => helloLatch.countDown() } - override def postStop(): Unit = { + override def postStop(): Unit = stopLatch.countDown() - } })), "round-robin-broadcast") actor ! pekko.routing.Broadcast("hello") @@ -158,7 +156,7 @@ class RoundRobinSpec extends PekkoSpec with DefaultTimeout with ImplicitSender { actor ! pekko.routing.Broadcast("end") Await.ready(doneLatch, 5 seconds) - replies.values.foreach { _ should ===(iterationCount) } + replies.values.foreach(_ should ===(iterationCount)) } } @@ -207,7 +205,7 @@ class RoundRobinSpec extends PekkoSpec with DefaultTimeout with ImplicitSender { actor ! pekko.routing.Broadcast("end") expectTerminated(actor) - replies.values.foreach { _ should ===(iterationCount) } + replies.values.foreach(_ should ===(iterationCount)) } } diff --git a/actor-tests/src/test/scala/org/apache/pekko/routing/RouteeCreationSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/routing/RouteeCreationSpec.scala index 3d531f24982..5b1e3b23714 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/routing/RouteeCreationSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/routing/RouteeCreationSpec.scala @@ -32,12 +32,11 @@ class RouteeCreationSpec extends PekkoSpec { system.actorSelection(self.path).tell(Identify(self.path), testActor) def receive = Actor.emptyBehavior }))) - for (i <- 1 to N) { + for (i <- 1 to N) expectMsgType[ActorIdentity] match { case ActorIdentity(_, Some(_)) => // fine case x => fail(s"routee $i was not found $x") } - } } "allow sending to context.parent" in { diff --git a/actor-tests/src/test/scala/org/apache/pekko/routing/RoutingSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/routing/RoutingSpec.scala index 893387ea922..8ce3067d73c 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/routing/RoutingSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/routing/RoutingSpec.scala @@ -105,7 +105,7 @@ class RoutingSpec extends PekkoSpec(RoutingSpec.config) with DefaultTimeout with router ! GetRoutees val routees = expectMsgType[Routees].routees routees.size should ===(2) - routees.foreach { _.send(PoisonPill, testActor) } + routees.foreach(_.send(PoisonPill, testActor)) // expect no Terminated expectNoMessage(2.seconds) } @@ -250,11 +250,10 @@ class RoutingSpec extends PekkoSpec(RoutingSpec.config) with DefaultTimeout with ConfigFactory .parseString("pekko.actor.deployment./routed.router=round-robin-pool") .withFallback(system.settings.config)) - try { + try sys.actorOf(FromConfig.props(routeeProps = Props[TestActor]()), "routed") - } finally { + finally shutdown(sys) - } } } diff --git a/actor-tests/src/test/scala/org/apache/pekko/routing/ScatterGatherFirstCompletedSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/routing/ScatterGatherFirstCompletedSpec.scala index c6210b03e98..bdaa94741fc 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/routing/ScatterGatherFirstCompletedSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/routing/ScatterGatherFirstCompletedSpec.scala @@ -41,15 +41,13 @@ object ScatterGatherFirstCompletedSpec { case Stop(None) => context.stop(self) case Stop(Some(_id)) if _id == id => context.stop(self) case _id: Int if _id == id => - case _ => { + case _ => Thread.sleep(100 * id) sender() ! id - } } - override def postStop() = { + override def postStop() = shudownLatch.foreach(_.countDown()) - } }), "Actor:" + id) } diff --git a/actor-tests/src/test/scala/org/apache/pekko/serialization/AsyncSerializeSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/serialization/AsyncSerializeSpec.scala index 5f503528cd9..509649762d9 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/serialization/AsyncSerializeSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/serialization/AsyncSerializeSpec.scala @@ -48,21 +48,19 @@ object AsyncSerializeSpec { class TestAsyncSerializer(system: ExtendedActorSystem) extends AsyncSerializerWithStringManifest(system) { - override def toBinaryAsync(o: AnyRef): Future[Array[Byte]] = { + override def toBinaryAsync(o: AnyRef): Future[Array[Byte]] = o match { case Message1(msg) => Future.successful(msg.getBytes) case Message2(msg) => Future.successful(msg.getBytes) case _ => throw new IllegalArgumentException(s"Unknown type $o") } - } - override def fromBinaryAsync(bytes: Array[Byte], manifest: String): Future[AnyRef] = { + override def fromBinaryAsync(bytes: Array[Byte], manifest: String): Future[AnyRef] = manifest match { case "1" => Future.successful(Message1(new String(bytes))) case "2" => Future.successful(Message2(new String(bytes))) case _ => throw new IllegalArgumentException(s"Unknown manifest $manifest") } - } override def identifier: Int = 9000 @@ -75,21 +73,19 @@ object AsyncSerializeSpec { class TestAsyncSerializerCS(system: ExtendedActorSystem) extends AsyncSerializerWithStringManifestCS(system) { - override def toBinaryAsyncCS(o: AnyRef): CompletionStage[Array[Byte]] = { + override def toBinaryAsyncCS(o: AnyRef): CompletionStage[Array[Byte]] = o match { case Message3(msg) => CompletableFuture.completedFuture(msg.getBytes) case Message4(msg) => CompletableFuture.completedFuture(msg.getBytes) case _ => throw new IllegalArgumentException(s"Unknown type $o") } - } - override def fromBinaryAsyncCS(bytes: Array[Byte], manifest: String): CompletionStage[AnyRef] = { + override def fromBinaryAsyncCS(bytes: Array[Byte], manifest: String): CompletionStage[AnyRef] = manifest match { case "1" => CompletableFuture.completedFuture(Message3(new String(bytes))) case "2" => CompletableFuture.completedFuture(Message4(new String(bytes))) case _ => throw new IllegalArgumentException(s"Unknown manifest $manifest") } - } override def identifier: Int = 9001 diff --git a/actor-tests/src/test/scala/org/apache/pekko/serialization/SerializeSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/serialization/SerializeSpec.scala index 3a5cc4adef3..b9725d1c307 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/serialization/SerializeSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/serialization/SerializeSpec.scala @@ -389,7 +389,7 @@ class ReferenceSerializationSpec extends PekkoSpec(SerializationTests.mostlyRefe } "not support serialization for other classes" in { - intercept[NotSerializableException] { ser.serializerFor(classOf[Object]) } + intercept[NotSerializableException](ser.serializerFor(classOf[Object])) } "not allow serialize function" in { @@ -432,7 +432,7 @@ class AllowJavaSerializationSpec extends PekkoSpec(SerializationTests.allowJavaS } "not support serialization for other classes" in { - intercept[NotSerializableException] { ser.serializerFor(classOf[Object]) } + intercept[NotSerializableException](ser.serializerFor(classOf[Object])) } "serialize function with JavaSerializer" in { @@ -503,9 +503,8 @@ class AllowJavaSerializationSpec extends PekkoSpec(SerializationTests.allowJavaS val deadLetters = in.readObject().asInstanceOf[DeadLetterActorRef] (deadLetters eq a.deadLetters) should ===(true) } - } finally { + } finally shutdown(a) - } } } @@ -592,9 +591,8 @@ protected[pekko] class NoopSerializer extends Serializer { def identifier = 9999 - def toBinary(o: AnyRef): Array[Byte] = { + def toBinary(o: AnyRef): Array[Byte] = Array.empty[Byte] - } def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]]): AnyRef = null } @@ -604,9 +602,8 @@ protected[pekko] class NoopSerializer2 extends Serializer { def identifier = 10000 - def toBinary(o: AnyRef): Array[Byte] = { + def toBinary(o: AnyRef): Array[Byte] = Array.empty[Byte] - } def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]]): AnyRef = null } diff --git a/actor-tests/src/test/scala/org/apache/pekko/testkit/CallingThreadDispatcherModelSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/testkit/CallingThreadDispatcherModelSpec.scala index 720c84e2675..454e63c5dec 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/testkit/CallingThreadDispatcherModelSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/testkit/CallingThreadDispatcherModelSpec.scala @@ -26,7 +26,7 @@ import pekko.dispatch.MessageDispatcherConfigurator object CallingThreadDispatcherModelSpec { import ActorModelSpec._ - val config = { + val config = """ boss { executor = thread-pool-executor @@ -39,7 +39,6 @@ object CallingThreadDispatcherModelSpec { test-calling-thread-%s { type = "org.apache.pekko.testkit.CallingThreadDispatcherModelSpec$CallingThreadDispatcherInterceptorConfigurator" }""".format(n)).mkString - } class CallingThreadDispatcherInterceptorConfigurator(config: Config, prerequisites: DispatcherPrerequisites) extends MessageDispatcherConfigurator(config, prerequisites) { @@ -60,12 +59,11 @@ class CallingThreadDispatcherModelSpec extends ActorModelSpec(CallingThreadDispa val dispatcherCount = new AtomicInteger() - override def interceptedDispatcher(): MessageDispatcherInterceptor = { + override def interceptedDispatcher(): MessageDispatcherInterceptor = // use new id for each test, since the MessageDispatcherInterceptor holds state system.dispatchers .lookup("test-calling-thread-" + dispatcherCount.incrementAndGet()) .asInstanceOf[MessageDispatcherInterceptor] - } override def dispatcherType = "Calling Thread Dispatcher" } diff --git a/actor-tests/src/test/scala/org/apache/pekko/util/BoundedBlockingQueueSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/util/BoundedBlockingQueueSpec.scala index 1302cae07a7..9cd0df2505c 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/util/BoundedBlockingQueueSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/util/BoundedBlockingQueueSpec.scala @@ -821,7 +821,7 @@ trait QueueSetupHelper { @volatile private var waiting: Option[Manual] = None - def advanceTime(timespan: Span): Unit = { + def advanceTime(timespan: Span): Unit = waiting match { case Some(manual) => val newWaitTime = manual.waitTime - timespan.toNanos @@ -835,14 +835,13 @@ trait QueueSetupHelper { case None => sys.error("Called advance time but hasn't enabled manualTimeControl") } - } def manualTimeControl(@unused on: Boolean): Unit = waiting = Some(Manual()) override def signalAll(): Unit = condition.signalAll() - override def awaitNanos(nanosTimeout: Long): Long = { + override def awaitNanos(nanosTimeout: Long): Long = if (waiting.isEmpty) { events += awaitEvent condition.awaitNanos(nanosTimeout) @@ -851,14 +850,13 @@ trait QueueSetupHelper { val waitingThread = Some(Thread.currentThread()) waiting = Some(Manual(waitTime, waitingThread)) - try { + try this.await() - } catch { + catch { case _: InterruptedException => } waitTime } - } override def awaitUninterruptibly(): Unit = condition.awaitUninterruptibly() diff --git a/actor-tests/src/test/scala/org/apache/pekko/util/ByteStringInputStreamSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/util/ByteStringInputStreamSpec.scala index b49f4de017c..23ee8b23699 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/util/ByteStringInputStreamSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/util/ByteStringInputStreamSpec.scala @@ -62,9 +62,8 @@ class ByteStringInputStreamSpec extends AnyWordSpec with Matchers { try { copy(input, output) output.toByteArray - } finally { + } finally output.close() - } } private def copy(input: InputStream, output: OutputStream): Int = { diff --git a/actor-tests/src/test/scala/org/apache/pekko/util/ByteStringSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/util/ByteStringSpec.scala index d565174609f..5ba5d7dbc41 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/util/ByteStringSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/util/ByteStringSpec.scala @@ -100,9 +100,8 @@ class ByteStringSpec extends AnyWordSpec with Matchers with Checkers { is.readObject } - def testSer(obj: AnyRef) = { + def testSer(obj: AnyRef) = deserialize(serialize(obj)) == obj - } def hexFromSer(obj: AnyRef) = { val os = new ByteArrayOutputStream @@ -819,19 +818,19 @@ class ByteStringSpec extends AnyWordSpec with Matchers with Checkers { "A ByteString" must { "have correct size" when { - "concatenating" in { check((a: ByteString, b: ByteString) => (a ++ b).size == a.size + b.size) } - "dropping" in { check((a: ByteString, b: ByteString) => (a ++ b).drop(b.size).size == a.size) } - "taking" in { check((a: ByteString, b: ByteString) => (a ++ b).take(a.size) == a) } - "takingRight" in { check((a: ByteString, b: ByteString) => (a ++ b).takeRight(b.size) == b) } + "concatenating" in check((a: ByteString, b: ByteString) => (a ++ b).size == a.size + b.size) + "dropping" in check((a: ByteString, b: ByteString) => (a ++ b).drop(b.size).size == a.size) + "taking" in check((a: ByteString, b: ByteString) => (a ++ b).take(a.size) == a) + "takingRight" in check((a: ByteString, b: ByteString) => (a ++ b).takeRight(b.size) == b) "dropping then taking" in { check((a: ByteString, b: ByteString) => (b ++ a ++ b).drop(b.size).take(a.size) == a) } - "droppingRight" in { check((a: ByteString, b: ByteString) => (b ++ a ++ b).drop(b.size).dropRight(b.size) == a) } + "droppingRight" in check((a: ByteString, b: ByteString) => (b ++ a ++ b).drop(b.size).dropRight(b.size) == a) } "be sequential" when { - "taking" in { check((a: ByteString, b: ByteString) => (a ++ b).take(a.size) == a) } - "dropping" in { check((a: ByteString, b: ByteString) => (a ++ b).drop(a.size) == b) } + "taking" in check((a: ByteString, b: ByteString) => (a ++ b).take(a.size) == a) + "dropping" in check((a: ByteString, b: ByteString) => (a ++ b).drop(a.size) == b) } "be equal to the original" when { @@ -937,7 +936,7 @@ class ByteStringSpec extends AnyWordSpec with Matchers with Checkers { "behave like a Vector" when { "concatenating" in { check { (a: ByteString, b: ByteString) => - likeVectors(a, b) { _ ++ _ } + likeVectors(a, b)(_ ++ _) } } @@ -954,84 +953,84 @@ class ByteStringSpec extends AnyWordSpec with Matchers with Checkers { "calling head" in { check { (a: ByteString) => - a.isEmpty || likeVector(a) { _.head } + a.isEmpty || likeVector(a)(_.head) } } "calling tail" in { check { (a: ByteString) => - a.isEmpty || likeVector(a) { _.tail } + a.isEmpty || likeVector(a)(_.tail) } } "calling last" in { check { (a: ByteString) => - a.isEmpty || likeVector(a) { _.last } + a.isEmpty || likeVector(a)(_.last) } } "calling init" in { check { (a: ByteString) => - a.isEmpty || likeVector(a) { _.init } + a.isEmpty || likeVector(a)(_.init) } } "calling length" in { check { (a: ByteString) => - likeVector(a) { _.length } + likeVector(a)(_.length) } } "calling span" in { check { (a: ByteString, b: Byte) => - likeVector(a) { _.span(_ != b) match { case (a, b) => (a, b) } } + likeVector(a)(_.span(_ != b) match { case (a, b) => (a, b) }) } } "calling takeWhile" in { check { (a: ByteString, b: Byte) => - likeVector(a) { _.takeWhile(_ != b) } + likeVector(a)(_.takeWhile(_ != b)) } } "calling dropWhile" in { check { (a: ByteString, b: Byte) => - likeVector(a) { _.dropWhile(_ != b) } + likeVector(a)(_.dropWhile(_ != b)) } } "calling indexWhere" in { check { (a: ByteString, b: Byte) => - likeVector(a) { _.indexWhere(_ == b) } + likeVector(a)(_.indexWhere(_ == b)) } } "calling indexWhere(p, idx)" in { check { (a: ByteString, b: Byte, idx: Int) => - likeVector(a) { _.indexWhere(_ == b, math.max(0, idx)) } + likeVector(a)(_.indexWhere(_ == b, math.max(0, idx))) } } "calling indexOf" in { check { (a: ByteString, b: Byte) => - likeVector(a) { _.indexOf(b) } + likeVector(a)(_.indexOf(b)) } } // this actually behave weird for Vector and negative indexes - SI9936, fixed in Scala 2.12 // so let's just skip negative indexes (doesn't make much sense anyway) "calling indexOf(elem, idx)" in { check { (a: ByteString, b: Byte, idx: Int) => - likeVector(a) { _.indexOf(b, math.max(0, idx)) } + likeVector(a)(_.indexOf(b, math.max(0, idx))) } } "calling foreach" in { check { (a: ByteString) => likeVector(a) { it => - var acc = 0; it.foreach { acc += _ }; acc + var acc = 0; it.foreach(acc += _); acc } } } "calling foldLeft" in { check { (a: ByteString) => - likeVector(a) { _.foldLeft(0) { _ + _ } } + likeVector(a)(_.foldLeft(0)(_ + _)) } } "calling toArray" in { check { (a: ByteString) => - likeVector(a) { _.toArray.toSeq } + likeVector(a)(_.toArray.toSeq) } } @@ -1132,17 +1131,17 @@ class ByteStringSpec extends AnyWordSpec with Matchers with Checkers { "calling head" in { check { (a: ByteString) => - a.isEmpty || likeVecIt(a) { _.head } + a.isEmpty || likeVecIt(a)(_.head) } } "calling next" in { check { (a: ByteString) => - a.isEmpty || likeVecIt(a) { _.next() } + a.isEmpty || likeVecIt(a)(_.next()) } } "calling hasNext" in { check { (a: ByteString) => - likeVecIt(a) { _.hasNext } + likeVecIt(a)(_.hasNext) } } "calling length" in { @@ -1152,7 +1151,7 @@ class ByteStringSpec extends AnyWordSpec with Matchers with Checkers { } "calling duplicate" in { check { (a: ByteString) => - likeVecIt(a)({ _.duplicate match { case (a, b) => (a.toSeq, b.toSeq) } }, strict = false) + likeVecIt(a)(_.duplicate match { case (a, b) => (a.toSeq, b.toSeq) }, strict = false) } } @@ -1161,50 +1160,50 @@ class ByteStringSpec extends AnyWordSpec with Matchers with Checkers { // scala.collection default Iterator (see Scala issue SI-5838). "calling span" in { check { (a: ByteString, b: Byte) => - likeVecIt(a)({ _.span(_ != b) match { case (a, b) => (a.toList, b.toList) } }, strict = false) + likeVecIt(a)(_.span(_ != b) match { case (a, b) => (a.toList, b.toList) }, strict = false) } } "calling takeWhile" in { check { (a: ByteString, b: Byte) => - likeVecIt(a)({ _.takeWhile(_ != b).toSeq }, strict = false) + likeVecIt(a)(_.takeWhile(_ != b).toSeq, strict = false) } } "calling dropWhile" in { check { (a: ByteString, b: Byte) => - likeVecIt(a) { _.dropWhile(_ != b).toSeq } + likeVecIt(a)(_.dropWhile(_ != b).toSeq) } } "calling indexWhere" in { check { (a: ByteString, b: Byte) => - likeVecIt(a) { _.indexWhere(_ == b) } + likeVecIt(a)(_.indexWhere(_ == b)) } } "calling indexOf" in { check { (a: ByteString, b: Byte) => - likeVecIt(a) { _.indexOf(b) } + likeVecIt(a)(_.indexOf(b)) } } "calling toSeq" in { check { (a: ByteString) => - likeVecIt(a) { _.toSeq } + likeVecIt(a)(_.toSeq) } } "calling foreach" in { check { (a: ByteString) => likeVecIt(a) { it => - var acc = 0; it.foreach { acc += _ }; acc + var acc = 0; it.foreach(acc += _); acc } } } "calling foldLeft" in { check { (a: ByteString) => - likeVecIt(a) { _.foldLeft(0) { _ + _ } } + likeVecIt(a)(_.foldLeft(0)(_ + _)) } } "calling toArray" in { check { (a: ByteString) => - likeVecIt(a) { _.toArray.toSeq } + likeVecIt(a)(_.toArray.toSeq) } } @@ -1212,9 +1211,8 @@ class ByteStringSpec extends AnyWordSpec with Matchers with Checkers { check { (slice: ByteStringSlice) => slice match { case (xs, from, until) => - likeVecIt(xs)({ - _.slice(from, until).toSeq - }, strict = false) + likeVecIt(xs)( + _.slice(from, until).toSeq, strict = false) } } } @@ -1223,9 +1221,8 @@ class ByteStringSpec extends AnyWordSpec with Matchers with Checkers { check { (slice: ByteStringSlice) => slice match { case (xs, from, until) => - likeVecIt(xs)({ - _.drop(from).take(until - from).toSeq - }, strict = false) + likeVecIt(xs)( + _.drop(from).take(until - from).toSeq, strict = false) } } } diff --git a/actor-tests/src/test/scala/org/apache/pekko/util/IndexSpec.scala b/actor-tests/src/test/scala/org/apache/pekko/util/IndexSpec.scala index 741782e66b3..c85b36c02f4 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/util/IndexSpec.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/util/IndexSpec.scala @@ -99,10 +99,10 @@ class IndexSpec extends PekkoSpec with Matchers with DefaultTimeout { val index = indexWithValues var valueCount = 0 - index.foreach((key, value) => { + index.foreach { (key, value) => valueCount = valueCount + 1 index.findValue(key)(_ == value) should ===(Some(value)) - }) + } valueCount should ===(6) } "be cleared" in { diff --git a/actor-tests/src/test/scala/org/apache/pekko/util/ZipfianGenerator.scala b/actor-tests/src/test/scala/org/apache/pekko/util/ZipfianGenerator.scala index c45adb17ad6..95779da84e6 100644 --- a/actor-tests/src/test/scala/org/apache/pekko/util/ZipfianGenerator.scala +++ b/actor-tests/src/test/scala/org/apache/pekko/util/ZipfianGenerator.scala @@ -28,9 +28,8 @@ object ZipfianGenerator { private def zeta(n: Int, theta: Double): Double = { var sum = 0.0 - for (i <- 1 to n) { + for (i <- 1 to n) sum += 1 / Math.pow(i, theta) - } sum } } diff --git a/actor-typed-tests/src/test/scala-3/docs/org/apache/pekko/typed/InteractionPatterns3Spec.scala b/actor-typed-tests/src/test/scala-3/docs/org/apache/pekko/typed/InteractionPatterns3Spec.scala index bd7f7203be3..d735360c31b 100644 --- a/actor-typed-tests/src/test/scala-3/docs/org/apache/pekko/typed/InteractionPatterns3Spec.scala +++ b/actor-typed-tests/src/test/scala-3/docs/org/apache/pekko/typed/InteractionPatterns3Spec.scala @@ -141,7 +141,7 @@ class InteractionPatterns3Spec extends ScalaTestWithActorTestKit with AnyWordSpe def apply(backend: ActorRef[Backend.Request]): Behavior[Command] = // (2) Behaviors.setup[CommandAndResponse] { context => - def active(inProgress: Map[Int, ActorRef[URI]], count: Int): Behavior[CommandAndResponse] = { + def active(inProgress: Map[Int, ActorRef[URI]], count: Int): Behavior[CommandAndResponse] = Behaviors.receiveMessage[CommandAndResponse] { case Translate(site, replyTo) => val taskId = count + 1 @@ -159,7 +159,6 @@ class InteractionPatterns3Spec extends ScalaTestWithActorTestKit with AnyWordSpe inProgress(taskId) ! result active(inProgress - taskId, count) } - } active(inProgress = Map.empty, count = 0) }.narrow // (5) @@ -195,9 +194,8 @@ class InteractionPatterns3Spec extends ScalaTestWithActorTestKit with AnyWordSpe private case object Timeout extends Command private case object TimerKey - def apply(target: ActorRef[Batch], after: FiniteDuration, maxSize: Int): Behavior[Command] = { + def apply(target: ActorRef[Batch], after: FiniteDuration, maxSize: Int): Behavior[Command] = Behaviors.withTimers(timers => new Buncher(timers, target, after, maxSize).idle()) - } } class Buncher( @@ -207,14 +205,13 @@ class InteractionPatterns3Spec extends ScalaTestWithActorTestKit with AnyWordSpe maxSize: Int) { import Buncher._ - private def idle(): Behavior[Command] = { + private def idle(): Behavior[Command] = Behaviors.receiveMessage[Command] { message => timers.startSingleTimer(TimerKey, Timeout, after) active(Vector(message)) } - } - def active(buffer: Vector[Command]): Behavior[Command] = { + def active(buffer: Vector[Command]): Behavior[Command] = Behaviors.receiveMessage[Command] { case Timeout => target ! Batch(buffer) @@ -228,7 +225,6 @@ class InteractionPatterns3Spec extends ScalaTestWithActorTestKit with AnyWordSpe } else active(newBuffer) } - } } // #timer @@ -395,7 +391,7 @@ class InteractionPatterns3Spec extends ScalaTestWithActorTestKit with AnyWordSpe case class LeaveHome(who: String, replyTo: ActorRef[ReadyToLeaveHome]) extends Command case class ReadyToLeaveHome(who: String, keys: Keys, wallet: Wallet) - def apply(): Behavior[Command] = { + def apply(): Behavior[Command] = Behaviors.setup[Command] { context => val keyCabinet: ActorRef[KeyCabinet.GetKeys] = context.spawn(KeyCabinet(), "key-cabinet") val drawer: ActorRef[Drawer.GetWallet] = context.spawn(Drawer(), "drawer") @@ -406,14 +402,13 @@ class InteractionPatterns3Spec extends ScalaTestWithActorTestKit with AnyWordSpe Behaviors.same } } - } // per session actor behavior def prepareToLeaveHome( whoIsLeaving: String, replyTo: ActorRef[ReadyToLeaveHome], keyCabinet: ActorRef[KeyCabinet.GetKeys], - drawer: ActorRef[Drawer.GetWallet]): Behavior[NotUsed] = { + drawer: ActorRef[Drawer.GetWallet]): Behavior[NotUsed] = // we don't _really_ care about the actor protocol here as nobody will send us // messages except for responses to our queries, so we just accept any kind of message // but narrow that to more limited types when we interact @@ -449,7 +444,6 @@ class InteractionPatterns3Spec extends ScalaTestWithActorTestKit with AnyWordSpe } } .narrow[NotUsed] // we don't let anyone else know we accept anything - } } // #per-session-child @@ -613,11 +607,10 @@ class InteractionPatterns3Spec extends ScalaTestWithActorTestKit with AnyWordSpe private val MaxOperationsInProgress = 10 - def apply(dataAccess: CustomerDataAccess): Behavior[Command] = { + def apply(dataAccess: CustomerDataAccess): Behavior[Command] = next(dataAccess, operationsInProgress = 0) - } - private def next(dataAccess: CustomerDataAccess, operationsInProgress: Int): Behavior[Command] = { + private def next(dataAccess: CustomerDataAccess, operationsInProgress: Int): Behavior[Command] = Behaviors.receive { (context, command) => command match { case Update(value, replyTo) => @@ -642,7 +635,6 @@ class InteractionPatterns3Spec extends ScalaTestWithActorTestKit with AnyWordSpe next(dataAccess, operationsInProgress - 1) } } - } } // #pipeToSelf diff --git a/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/Aggregator.scala b/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/Aggregator.scala index c3498371258..1ae8a9645d5 100644 --- a/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/Aggregator.scala +++ b/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/Aggregator.scala @@ -34,13 +34,13 @@ object Aggregator { expectedReplies: Int, replyTo: ActorRef[Aggregate], aggregateReplies: immutable.IndexedSeq[Reply] => Aggregate, - timeout: FiniteDuration): Behavior[Command] = { + timeout: FiniteDuration): Behavior[Command] = Behaviors.setup { context => context.setReceiveTimeout(timeout, ReceiveTimeout) val replyAdapter = context.messageAdapter[Reply](WrappedReply(_)) sendRequests(replyAdapter) - def collecting(replies: immutable.IndexedSeq[Reply]): Behavior[Command] = { + def collecting(replies: immutable.IndexedSeq[Reply]): Behavior[Command] = Behaviors.receiveMessage { case WrappedReply(reply) => val newReplies = replies :+ reply.asInstanceOf[Reply] @@ -56,11 +56,9 @@ object Aggregator { replyTo ! aggregate Behaviors.stopped } - } collecting(Vector.empty) } - } } //#behavior diff --git a/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/AggregatorSpec.scala b/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/AggregatorSpec.scala index a6abfac8fc9..83c1db60f96 100644 --- a/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/AggregatorSpec.scala +++ b/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/AggregatorSpec.scala @@ -42,8 +42,7 @@ object AggregatorSpec { final case class Quote(hotel: String, price: BigDecimal) final case class AggregatedQuotes(quotes: List[Quote]) extends Command - def apply(hotel1: ActorRef[Hotel1.RequestQuote], hotel2: ActorRef[Hotel2.RequestPrice]): Behavior[Command] = { - + def apply(hotel1: ActorRef[Hotel1.RequestQuote], hotel2: ActorRef[Hotel2.RequestPrice]): Behavior[Command] = Behaviors.setup[Command] { context => context.spawnAnonymous( Aggregator[Reply, AggregatedQuotes]( @@ -73,7 +72,6 @@ object AggregatorSpec { Behaviors.same } } - } } // #usage } diff --git a/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/GracefulStopDocSpec.scala b/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/GracefulStopDocSpec.scala index 3a35285866b..b5c75a35b4b 100644 --- a/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/GracefulStopDocSpec.scala +++ b/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/GracefulStopDocSpec.scala @@ -39,7 +39,7 @@ object GracefulStopDocSpec { final case class SpawnJob(name: String) extends Command case object GracefulShutdown extends Command - def apply(): Behavior[Command] = { + def apply(): Behavior[Command] = Behaviors .receive[Command] { (context, message) => message match { @@ -59,7 +59,6 @@ object GracefulStopDocSpec { context.log.info("Master Control Program stopped") Behaviors.same } - } } // #master-actor @@ -68,13 +67,12 @@ object GracefulStopDocSpec { object Job { sealed trait Command - def apply(name: String): Behavior[Command] = { + def apply(name: String): Behavior[Command] = Behaviors.receiveSignal[Command] { case (context, PostStop) => context.log.info("Worker {} stopped", name) Behaviors.same } - } } // #worker-actor @@ -85,7 +83,7 @@ object GracefulStopDocSpec { sealed trait Command final case class SpawnJob(name: String) extends Command - def apply(): Behavior[Command] = { + def apply(): Behavior[Command] = Behaviors .receive[Command] { (context, message) => message match { @@ -101,7 +99,6 @@ object GracefulStopDocSpec { context.log.info("Job stopped: {}", ref.path.name) Behaviors.same } - } } // #master-actor-watch } @@ -115,7 +112,7 @@ object GracefulStopDocSpec { final case class JobDone(name: String) private final case class JobTerminated(name: String, replyToWhenDone: ActorRef[JobDone]) extends Command - def apply(): Behavior[Command] = { + def apply(): Behavior[Command] = Behaviors.receive { (context, message) => message match { case SpawnJob(jobName, replyToWhenDone) => @@ -129,7 +126,6 @@ object GracefulStopDocSpec { Behaviors.same } } - } } // #master-actor-watchWith } diff --git a/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/InteractionPatternsSpec.scala b/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/InteractionPatternsSpec.scala index 6e2c5a40ed4..b1a485581e3 100644 --- a/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/InteractionPatternsSpec.scala +++ b/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/InteractionPatternsSpec.scala @@ -137,7 +137,7 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with AnyWordSpec val backendResponseMapper: ActorRef[Backend.Response] = context.messageAdapter(rsp => WrappedBackendResponse(rsp)) - def active(inProgress: Map[Int, ActorRef[URI]], count: Int): Behavior[Command] = { + def active(inProgress: Map[Int, ActorRef[URI]], count: Int): Behavior[Command] = Behaviors.receiveMessage[Command] { case Translate(site, replyTo) => val taskId = count + 1 @@ -158,7 +158,6 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with AnyWordSpec active(inProgress - taskId, count) } } - } active(inProgress = Map.empty, count = 0) } @@ -194,9 +193,8 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with AnyWordSpec private case object Timeout extends Command private case object TimerKey - def apply(target: ActorRef[Batch], after: FiniteDuration, maxSize: Int): Behavior[Command] = { + def apply(target: ActorRef[Batch], after: FiniteDuration, maxSize: Int): Behavior[Command] = Behaviors.withTimers(timers => new Buncher(timers, target, after, maxSize).idle()) - } } class Buncher( @@ -206,14 +204,13 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with AnyWordSpec maxSize: Int) { import Buncher._ - private def idle(): Behavior[Command] = { + private def idle(): Behavior[Command] = Behaviors.receiveMessage[Command] { message => timers.startSingleTimer(TimerKey, Timeout, after) active(Vector(message)) } - } - def active(buffer: Vector[Command]): Behavior[Command] = { + def active(buffer: Vector[Command]): Behavior[Command] = Behaviors.receiveMessage[Command] { case Timeout => target ! Batch(buffer) @@ -227,7 +224,6 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with AnyWordSpec } else active(newBuffer) } - } } // #timer @@ -394,7 +390,7 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with AnyWordSpec case class LeaveHome(who: String, replyTo: ActorRef[ReadyToLeaveHome]) extends Command case class ReadyToLeaveHome(who: String, keys: Keys, wallet: Wallet) - def apply(): Behavior[Command] = { + def apply(): Behavior[Command] = Behaviors.setup[Command] { context => val keyCabinet: ActorRef[KeyCabinet.GetKeys] = context.spawn(KeyCabinet(), "key-cabinet") val drawer: ActorRef[Drawer.GetWallet] = context.spawn(Drawer(), "drawer") @@ -405,14 +401,13 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with AnyWordSpec Behaviors.same } } - } // per session actor behavior def prepareToLeaveHome( whoIsLeaving: String, replyTo: ActorRef[ReadyToLeaveHome], keyCabinet: ActorRef[KeyCabinet.GetKeys], - drawer: ActorRef[Drawer.GetWallet]): Behavior[NotUsed] = { + drawer: ActorRef[Drawer.GetWallet]): Behavior[NotUsed] = // we don't _really_ care about the actor protocol here as nobody will send us // messages except for responses to our queries, so we just accept any kind of message // but narrow that to more limited types when we interact @@ -448,7 +443,6 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with AnyWordSpec } } .narrow[NotUsed] // we don't let anyone else know we accept anything - } } // #per-session-child @@ -612,11 +606,10 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with AnyWordSpec private val MaxOperationsInProgress = 10 - def apply(dataAccess: CustomerDataAccess): Behavior[Command] = { + def apply(dataAccess: CustomerDataAccess): Behavior[Command] = next(dataAccess, operationsInProgress = 0) - } - private def next(dataAccess: CustomerDataAccess, operationsInProgress: Int): Behavior[Command] = { + private def next(dataAccess: CustomerDataAccess, operationsInProgress: Int): Behavior[Command] = Behaviors.receive { (context, command) => command match { case Update(value, replyTo) => @@ -641,7 +634,6 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with AnyWordSpec next(dataAccess, operationsInProgress - 1) } } - } } // #pipeToSelf diff --git a/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/IntroSpec.scala b/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/IntroSpec.scala index 688ef2e1de1..2102ce204bf 100644 --- a/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/IntroSpec.scala +++ b/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/IntroSpec.scala @@ -239,9 +239,8 @@ object IntroSpec { } } - def main(args: Array[String]): Unit = { + def main(args: Array[String]): Unit = ActorSystem(Main(), "ChatRoomDemo") - } } // #chatroom-main diff --git a/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/LoggingDocExamples.scala b/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/LoggingDocExamples.scala index f4e62b32794..bc577bf1331 100644 --- a/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/LoggingDocExamples.scala +++ b/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/LoggingDocExamples.scala @@ -151,7 +151,7 @@ object LoggingDocExamples { // #test-logging-criteria } - def tagsExample(): Unit = { + def tagsExample(): Unit = Behaviors.setup[AnyRef] { context => val myBehavior = Behaviors.empty[AnyRef] // #tags @@ -159,6 +159,5 @@ object LoggingDocExamples { // #tags Behaviors.stopped } - } } diff --git a/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/OOIntroSpec.scala b/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/OOIntroSpec.scala index 4d818d9f4aa..02766ea55d0 100644 --- a/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/OOIntroSpec.scala +++ b/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/OOIntroSpec.scala @@ -61,7 +61,7 @@ object OOIntroSpec { class ChatRoomBehavior(context: ActorContext[RoomCommand]) extends AbstractBehavior[RoomCommand](context) { private var sessions: List[ActorRef[SessionCommand]] = List.empty - override def onMessage(message: RoomCommand): Behavior[RoomCommand] = { + override def onMessage(message: RoomCommand): Behavior[RoomCommand] = message match { case GetSession(screenName, client) => // create a child actor for further interaction with the client @@ -76,7 +76,6 @@ object OOIntroSpec { sessions.foreach(_ ! notification) this } - } } private object SessionBehavior { @@ -147,9 +146,8 @@ object OOIntroSpec { } } - def main(args: Array[String]): Unit = { + def main(args: Array[String]): Unit = ActorSystem(Main(), "ChatRoomDemo") - } } // #chatroom-main diff --git a/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/SpawnProtocolDocSpec.scala b/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/SpawnProtocolDocSpec.scala index bd957879175..4bb149bbf24 100644 --- a/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/SpawnProtocolDocSpec.scala +++ b/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/SpawnProtocolDocSpec.scala @@ -86,9 +86,8 @@ class SpawnProtocolDocSpec extends ScalaTestWithActorTestKit with AnyWordSpecLik val greetedReplyTo: Future[ActorRef[HelloWorld.Greeted]] = system.ask(SpawnProtocol.Spawn(greetedBehavior, name = "", props = Props.empty, _)) - for (greeterRef <- greeter; replyToRef <- greetedReplyTo) { + for (greeterRef <- greeter; replyToRef <- greetedReplyTo) greeterRef ! HelloWorld.Greet("Pekko", replyToRef) - } // #system-spawn diff --git a/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/StashDocSpec.scala b/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/StashDocSpec.scala index 99361787a04..c036cca621b 100644 --- a/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/StashDocSpec.scala +++ b/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/StashDocSpec.scala @@ -45,13 +45,12 @@ object StashDocSpec { private case object SaveSuccess extends Command private final case class DBError(cause: Throwable) extends Command - def apply(id: String, db: DB): Behavior[Command] = { + def apply(id: String, db: DB): Behavior[Command] = Behaviors.withStash(100) { buffer => Behaviors.setup[Command] { context => new DataAccess(context, buffer, id, db).start() } } - } } class DataAccess( @@ -80,7 +79,7 @@ object StashDocSpec { } } - private def active(state: String): Behavior[Command] = { + private def active(state: String): Behavior[Command] = Behaviors.receiveMessagePartial { case Get(replyTo) => replyTo ! state @@ -92,9 +91,8 @@ object StashDocSpec { } saving(value, replyTo) } - } - private def saving(state: String, replyTo: ActorRef[Done]): Behavior[Command] = { + private def saving(state: String, replyTo: ActorRef[Done]): Behavior[Command] = Behaviors.receiveMessage { case SaveSuccess => replyTo ! Done @@ -105,7 +103,6 @@ object StashDocSpec { buffer.stash(other) Behaviors.same } - } } // #stashing diff --git a/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/StyleGuideDocExamples.scala b/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/StyleGuideDocExamples.scala index 5d950775f7d..b75d0b440f7 100644 --- a/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/StyleGuideDocExamples.scala +++ b/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/StyleGuideDocExamples.scala @@ -84,9 +84,8 @@ object StyleGuideDocExamples { final case class GetValue(replyTo: ActorRef[Value]) extends Command final case class Value(n: Int) - def apply(): Behavior[Command] = { + def apply(): Behavior[Command] = Behaviors.setup(context => new Counter(context)) - } } class Counter(context: ActorContext[Counter.Command]) extends AbstractBehavior[Counter.Command](context) { @@ -94,7 +93,7 @@ object StyleGuideDocExamples { private var n = 0 - override def onMessage(msg: Command): Behavior[Counter.Command] = { + override def onMessage(msg: Command): Behavior[Counter.Command] = msg match { case Increment => n += 1 @@ -104,7 +103,6 @@ object StyleGuideDocExamples { replyTo ! Value(n) this } - } } // #oo-style @@ -294,7 +292,7 @@ object StyleGuideDocExamples { private class CountDown(notifyWhenZero: ActorRef[Done]) { import CountDown._ - private def counter(remaining: Int): Behavior[Command] = { + private def counter(remaining: Int): Behavior[Command] = // #exhastivness-check Behaviors.receiveMessage { case Down => @@ -304,8 +302,7 @@ object StyleGuideDocExamples { } else counter(remaining - 1) } - // #exhastivness-check - } + // #exhastivness-check } // #behavior-factory-method @@ -398,7 +395,7 @@ object StyleGuideDocExamples { // Tick is a private command so can't be sent to an ActorRef[Command] case object Tick extends PrivateCommand - def apply(name: String, tickInterval: FiniteDuration): Behavior[Command] = { + def apply(name: String, tickInterval: FiniteDuration): Behavior[Command] = Behaviors .setup[Counter.Message] { context => Behaviors.withTimers { timers => @@ -407,7 +404,6 @@ object StyleGuideDocExamples { } } .narrow // note narrow here - } } class Counter private (name: String, context: ActorContext[Counter.Message]) { @@ -478,7 +474,7 @@ object StyleGuideDocExamples { import CountDown._ // #pattern-match-unhandled - val zero: Behavior[Command] = { + val zero: Behavior[Command] = Behaviors.receiveMessage { case GetValue(replyTo) => replyTo ! Value(0) @@ -486,19 +482,17 @@ object StyleGuideDocExamples { case Down => Behaviors.unhandled } - } // #pattern-match-unhandled @nowarn object partial { // #pattern-match-partial - val zero: Behavior[Command] = { + val zero: Behavior[Command] = Behaviors.receiveMessagePartial { case GetValue(replyTo) => replyTo ! Value(0) Behaviors.same } - } // #pattern-match-partial } diff --git a/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/TailChopping.scala b/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/TailChopping.scala index ad2499ed2ed..134fe111035 100644 --- a/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/TailChopping.scala +++ b/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/TailChopping.scala @@ -34,12 +34,12 @@ object TailChopping { nextRequestAfter: FiniteDuration, replyTo: ActorRef[Reply], finalTimeout: FiniteDuration, - timeoutReply: Reply): Behavior[Command] = { + timeoutReply: Reply): Behavior[Command] = Behaviors.setup { context => Behaviors.withTimers { timers => val replyAdapter = context.messageAdapter[Reply](WrappedReply(_)) - def waiting(requestCount: Int): Behavior[Command] = { + def waiting(requestCount: Int): Behavior[Command] = Behaviors.receiveMessage { case WrappedReply(reply) => replyTo ! reply.asInstanceOf[Reply] @@ -52,7 +52,6 @@ object TailChopping { replyTo ! timeoutReply Behaviors.stopped } - } def sendNextRequest(requestCount: Int): Behavior[Command] = { if (sendRequest(requestCount, replyAdapter)) { @@ -66,7 +65,6 @@ object TailChopping { sendNextRequest(1) } } - } } //#behavior diff --git a/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/fromclassic/TypedSample.scala b/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/fromclassic/TypedSample.scala index f680c2f4292..3a7b7ba5a43 100644 --- a/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/fromclassic/TypedSample.scala +++ b/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/fromclassic/TypedSample.scala @@ -52,7 +52,7 @@ object TypedSample { private case class ChildTerminated(name: String) extends Command def apply(): Behavior[Command] = { - def updated(children: Map[String, ActorRef[Child.Command]]): Behavior[Command] = { + def updated(children: Map[String, ActorRef[Child.Command]]): Behavior[Command] = Behaviors.receive { (context, command) => command match { case DelegateToChild(name, childCommand) => @@ -71,7 +71,6 @@ object TypedSample { updated(children - name) } } - } updated(Map.empty) } diff --git a/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/supervision/SupervisionCompileOnly.scala b/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/supervision/SupervisionCompileOnly.scala index d10be16142e..9cdb3a4ed90 100644 --- a/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/supervision/SupervisionCompileOnly.scala +++ b/actor-typed-tests/src/test/scala/docs/org/apache/pekko/typed/supervision/SupervisionCompileOnly.scala @@ -75,7 +75,7 @@ object SupervisionCompileOnly { def child(size: Long): Behavior[String] = Behaviors.receiveMessage(msg => child(size + msg.length)) - def parent: Behavior[String] = { + def parent: Behavior[String] = Behaviors .supervise[String] { Behaviors.setup { ctx => @@ -92,11 +92,10 @@ object SupervisionCompileOnly { } } .onFailure(SupervisorStrategy.restart) - } // #restart-stop-children // #restart-keep-children - def parent2: Behavior[String] = { + def parent2: Behavior[String] = Behaviors.setup { ctx => val child1 = ctx.spawn(child(0), "child1") val child2 = ctx.spawn(child(0), "child2") @@ -114,7 +113,6 @@ object SupervisionCompileOnly { } .onFailure(SupervisorStrategy.restart.withStopChildren(false)) } - } // #restart-keep-children trait Resource { @@ -125,7 +123,7 @@ object SupervisionCompileOnly { @nowarn("msg=never used") // #restart-PreRestart-signal - def withPreRestart: Behavior[String] = { + def withPreRestart: Behavior[String] = Behaviors .supervise[String] { Behaviors.setup { ctx => @@ -147,7 +145,6 @@ object SupervisionCompileOnly { } } .onFailure[Exception](SupervisorStrategy.restart) - } // #restart-PreRestart-signal } diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/ActorContextSpec.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/ActorContextSpec.scala index d0c232ad533..dd8ee808085 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/ActorContextSpec.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/ActorContextSpec.scala @@ -190,7 +190,7 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit with AnyWordSp } .decorate - val parent: Behavior[Command] = Behaviors.setup[Command](context => { + val parent: Behavior[Command] = Behaviors.setup[Command] { context => val childRef = context.spawnAnonymous(Behaviors.supervise(child).onFailure(SupervisorStrategy.restart)) context.watch(childRef) probe.ref ! ChildMade(childRef) @@ -207,7 +207,7 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit with AnyWordSp Behaviors.stopped } .decorate - }) + } val parentRef = spawn(parent) val childRef = probe.expectMessageType[ChildMade].ref @@ -226,7 +226,7 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit with AnyWordSp val child: Behavior[Command] = Behaviors.empty[Command].decorate val parent: Behavior[Command] = Behaviors - .setup[Command](context => { + .setup[Command] { context => val childRef = context.spawnAnonymous(child) context.watch(childRef) probe.ref ! ChildMade(childRef) @@ -241,7 +241,7 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit with AnyWordSp probe.ref ! ReceivedSignal(signal) Behaviors.stopped } - }) + } .decorate val parentRef = spawn(parent) val childRef = probe.expectMessageType[ChildMade].ref @@ -252,7 +252,7 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit with AnyWordSp "reset behavior upon restart" in { val probe = TestProbe[Int]() val internal = Behaviors - .setup[Command](_ => { + .setup[Command] { _ => var counter = 0 Behaviors.receivePartial[Command] { case (_, Ping) => @@ -262,7 +262,7 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit with AnyWordSp case (_, Fail) => throw new TestException("Boom") } - }) + } .decorate val behavior = Behaviors.supervise(internal).onFailure(SupervisorStrategy.restart) val actor = spawn(behavior) @@ -278,7 +278,7 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit with AnyWordSp "not reset behavior upon resume" in { val probe = TestProbe[Int]() val internal = Behaviors - .setup[Command](_ => { + .setup[Command] { _ => var counter = 0 Behaviors.receivePartial[Command] { case (_, Ping) => @@ -288,7 +288,7 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit with AnyWordSp case (_, Fail) => throw new TestException("Boom") } - }) + } .decorate val behavior = Behaviors.supervise(internal).onFailure(SupervisorStrategy.resume) val actor = spawn(behavior) @@ -379,7 +379,7 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit with AnyWordSp .decorate spawn( Behaviors - .setup[Command](context => { + .setup[Command] { context => val childRef = context.spawn(child, "A") context.watch(childRef) probe.ref ! ChildMade(childRef) @@ -394,7 +394,7 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit with AnyWordSp probe.ref ! ReceivedSignal(signal) Behaviors.same } - }) + } .decorate) val childRef = probe.expectMessageType[ChildMade].ref childRef ! Stop @@ -411,7 +411,7 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit with AnyWordSp .decorate val actor = spawn( Behaviors - .setup[Command](context => { + .setup[Command] { context => val childRef = context.spawn(child, "A") probe.ref ! ChildMade(childRef) Behaviors @@ -426,7 +426,7 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit with AnyWordSp probe.ref ! ReceivedSignal(signal) Behaviors.same } - }) + } .decorate) val childRef = probe.expectMessageType[ChildMade].ref actor ! Watch(childRef) @@ -447,7 +447,7 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit with AnyWordSp .decorate val actor = spawn( Behaviors - .setup[Command](context => { + .setup[Command] { context => val childRef = context.spawn(child, "A") probe.ref ! ChildMade(childRef) Behaviors @@ -466,7 +466,7 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit with AnyWordSp probe.ref ! ReceivedSignal(signal) Behaviors.same } - }) + } .decorate) val childRef = probe.expectMessageType[ChildMade].ref actor ! Watch(childRef) @@ -492,7 +492,7 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit with AnyWordSp .decorate val actor = spawn( Behaviors - .setup[Command](context => { + .setup[Command] { context => val childRef = context.spawn(child, "A") context.watch(childRef) probe.ref ! ChildMade(childRef) @@ -516,7 +516,7 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit with AnyWordSp probe.ref ! ReceivedSignal(signal) Behaviors.same } - }) + } .decorate) val childRef = probe.expectMessageType[ChildMade].ref actor ! Inert @@ -666,7 +666,7 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit with AnyWordSp "not have problems stopping already stopped child" in { val probe = TestProbe[Event]() - val actor = spawn(Behaviors.setup[Command](context => { + val actor = spawn(Behaviors.setup[Command] { context => val child = context.spawnAnonymous(Behaviors.empty[Command]) probe.ref ! ChildMade(child) Behaviors.receivePartial[Command] { @@ -675,7 +675,7 @@ abstract class ActorContextSpec extends ScalaTestWithActorTestKit with AnyWordSp probe.ref ! Pong Behaviors.same } - })) + }) val child = probe.expectMessageType[ChildMade].ref actor ! StopRef(child) probe.expectMessage(Pong) diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/ActorSystemSpec.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/ActorSystemSpec.scala index cfd411d59ba..332fcac2a5a 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/ActorSystemSpec.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/ActorSystemSpec.scala @@ -40,9 +40,8 @@ class ActorSystemSpec extends PekkoSpec { (debugText should not).include(username) (debugText should not).include(userHome) debugText should include("") - } finally { + } finally system.terminate() - } } } } diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/AskSpec.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/AskSpec.scala index 5dc0dd7697e..f32a58a8382 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/AskSpec.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/AskSpec.scala @@ -210,9 +210,8 @@ class AskSpec extends ScalaTestWithActorTestKit(""" implicit val timeout: Timeout = 3.seconds val typedLegacy: ActorRef[AnyRef] = legacyActor typedLegacy.ask(Ping.apply).failed.futureValue should ===(ex) - } finally { + } finally pekko.testkit.TestKit.shutdownActorSystem(classicSystem) - } } "fail asking actor if responder function throws" in { diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/BehaviorSpec.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/BehaviorSpec.scala index 47acbd0cd0b..93b4ec0774e 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/BehaviorSpec.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/BehaviorSpec.scala @@ -140,24 +140,21 @@ object BehaviorSpec { trait Siphon extends Common { override type Aux = TestInbox[Command] - override def checkAux(command: Command, aux: Aux): Unit = { + override def checkAux(command: Command, aux: Aux): Unit = aux.receiveAll() should ===(command :: Nil) - } } trait SignalSiphon extends Common { override type Aux = TestInbox[Either[Signal, Command]] - override def checkAux(command: Command, aux: Aux): Unit = { + override def checkAux(command: Command, aux: Aux): Unit = aux.receiveAll() should ===(Right(command) :: Nil) - } - override def checkAux(signal: Signal, aux: Aux): Unit = { + override def checkAux(signal: Signal, aux: Aux): Unit = aux.receiveAll() should ===(Left(signal) :: Nil) - } } - def mkFull(monitor: ActorRef[Event], state: State = StateA): Behavior[Command] = { + def mkFull(monitor: ActorRef[Event], state: State = StateA): Behavior[Command] = SBehaviors .receive[Command] { case (context, GetSelf) => @@ -186,7 +183,6 @@ object BehaviorSpec { monitor ! ReceivedSignal(signal) SBehaviors.same } - } /* * function converters for Java, to ease the pain on Scala 2.11 */ @@ -346,7 +342,7 @@ class FullBehaviorSpec extends ScalaTestWithActorTestKit with Messages with Beco class ReceiveBehaviorSpec extends Messages with BecomeWithLifecycle with Stoppable { override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = behv(monitor, StateA) -> null - private def behv(monitor: ActorRef[Event], state: State): Behavior[Command] = { + private def behv(monitor: ActorRef[Event], state: State): Behavior[Command] = SBehaviors .receive[Command] { case (context, GetSelf) => @@ -375,12 +371,11 @@ class ReceiveBehaviorSpec extends Messages with BecomeWithLifecycle with Stoppab monitor ! ReceivedSignal(signal) SBehaviors.same } - } } class ReceiveMessageWithSameBehaviorSpec extends Messages { override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = behv(monitor) -> null - private def behv(monitor: ActorRef[Event]): Behavior[Command] = { + private def behv(monitor: ActorRef[Event]): Behavior[Command] = SBehaviors .receiveMessageWithSame[Command] { case Miss => @@ -391,7 +386,6 @@ class ReceiveMessageWithSameBehaviorSpec extends Messages { monitor ! Pong case _ => } - } } class ImmutableWithSignalScalaBehaviorSpec extends Messages with BecomeWithLifecycle with Stoppable { @@ -471,7 +465,7 @@ class MutableScalaBehaviorSpec extends Messages with Become with Stoppable { new SAbstractBehavior[Command](context) { private var state: State = StateA - override def onMessage(message: Command): Behavior[Command] = { + override def onMessage(message: Command): Behavior[Command] = message match { case GetSelf => monitor ! Self(this.context.self) @@ -495,7 +489,6 @@ class MutableScalaBehaviorSpec extends Messages with Become with Stoppable { case Stop => SBehaviors.stopped case _: AuxPing => SBehaviors.unhandled } - } } } } @@ -513,10 +506,10 @@ class DeferredScalaBehaviorSpec extends ImmutableWithSignalScalaBehaviorSpec { override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = { val inbox = TestInbox[Done]("deferredListener") - (SBehaviors.setup(_ => { + (SBehaviors.setup { _ => inbox.ref ! Done super.behavior(monitor)._1 - }), inbox) + }, inbox) } override def checkAux(signal: Signal, aux: Aux): Unit = @@ -550,9 +543,8 @@ class InterceptScalaBehaviorSpec extends ImmutableWithSignalScalaBehaviorSpec wi } class RestarterScalaBehaviorSpec extends ImmutableWithSignalScalaBehaviorSpec with Reuse { - override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = { + override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = SBehaviors.supervise(super.behavior(monitor)._1).onFailure(SupervisorStrategy.restart) -> null - } } class ImmutableWithSignalJavaBehaviorSpec extends Messages with BecomeWithLifecycle with Stoppable { @@ -622,10 +614,10 @@ class TransformMessagesJavaBehaviorSpec extends ImmutableWithSignalJavaBehaviorS val inbox = TestInbox[Command]("transformMessagesListener") JBehaviors.transformMessages(classOf[Command], super.behavior(monitor)._1, pf(_.`match`(classOf[Command], - fi(x => { + fi { x => inbox.ref ! x x - })))) -> inbox + }))) -> inbox } } @@ -634,10 +626,10 @@ class DeferredJavaBehaviorSpec extends ImmutableWithSignalJavaBehaviorSpec { override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = { val inbox = TestInbox[Done]("deferredListener") - (JBehaviors.setup(_ => { + (JBehaviors.setup { _ => inbox.ref ! Done super.behavior(monitor)._1 - }), inbox) + }, inbox) } override def checkAux(signal: Signal, aux: Aux): Unit = @@ -671,7 +663,6 @@ class TapJavaBehaviorSpec extends ImmutableWithSignalJavaBehaviorSpec with Reuse } class RestarterJavaBehaviorSpec extends ImmutableWithSignalJavaBehaviorSpec with Reuse { - override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = { + override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = JBehaviors.supervise(super.behavior(monitor)._1).onFailure(classOf[Exception], SupervisorStrategy.restart) -> null - } } diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/ExtensionsSpec.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/ExtensionsSpec.scala index 17bfa5d4ce2..6d5e3b8a973 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/ExtensionsSpec.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/ExtensionsSpec.scala @@ -49,9 +49,8 @@ object SlowExtension extends ExtensionId[SlowExtension] { class FailingToLoadExtension extends Extension object FailingToLoadExtension extends ExtensionId[FailingToLoadExtension] { - def createExtension(system: ActorSystem[_]) = { + def createExtension(system: ActorSystem[_]) = throw new RuntimeException("I cannot be trusted!") - } } class MultiExtension(val n: Int) extends Extension @@ -134,14 +133,13 @@ class ExtensionsSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with } "handle extensions that fail to initialize" in { - def create(): Unit = { + def create(): Unit = ActorSystem[Any]( Behaviors.empty[Any], "ExtensionsSpec04", ConfigFactory.parseString(""" pekko.actor.typed.extensions = ["org.apache.pekko.actor.typed.FailingToLoadExtension$"] """)) - } intercept[RuntimeException] { create() @@ -214,9 +212,8 @@ class ExtensionsSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with // as a typed library-extension in the config before shouldEqual beforeCreation + 1 after shouldEqual before - } finally { + } finally classicSystem.terminate().futureValue - } } "not create an extension multiple times when using the ActorSystemAdapter" in { @@ -228,9 +225,8 @@ class ExtensionsSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with (ext1 should be).theSameInstanceAs(ext2) - } finally { + } finally classicSystem.terminate().futureValue - } } "override extensions via ActorSystemSetup" in diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/InterceptSpec.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/InterceptSpec.scala index 3f786e36b81..ac1307b96f5 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/InterceptSpec.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/InterceptSpec.scala @@ -38,9 +38,8 @@ object InterceptSpec { override def aroundReceive( context: TypedActorContext[String], message: String, - target: ReceiveTarget[String]): Behavior[String] = { + target: ReceiveTarget[String]): Behavior[String] = target(context, message) - } override def isSame(other: BehaviorInterceptor[Any, Any]): Boolean = other.isInstanceOf[SameTypeInterceptor] @@ -72,7 +71,7 @@ object InterceptSpec { } - def apply(probe: ActorRef[String]): Behavior[Command] = { + def apply(probe: ActorRef[String]): Behavior[Command] = Behaviors .intercept(() => new ProtocolTransformer)(Behaviors.receiveMessagePartial[InternalProtocol] { case InternalProtocol.WrappedCommand(cmd) => @@ -83,7 +82,6 @@ object InterceptSpec { Behaviors.same }) .narrow - } } } @@ -211,9 +209,8 @@ class InterceptSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with override def aroundStart( context: TypedActorContext[String], - target: PreStartTarget[String]): Behavior[String] = { + target: PreStartTarget[String]): Behavior[String] = Behaviors.stopped - } def aroundReceive( context: TypedActorContext[String], @@ -261,7 +258,7 @@ class InterceptSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with val probe = TestProbe[String]() val interceptor = snitchingInterceptor(probe.ref) - def next(count1: Int): Behavior[String] = { + def next(count1: Int): Behavior[String] = Behaviors.intercept(() => interceptor)(Behaviors.setup { _ => var count2 = 0 Behaviors.receiveMessage[String] { m => @@ -270,7 +267,6 @@ class InterceptSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with next(count1 + 1) } }) - } val ref: ActorRef[String] = spawn(next(1)) @@ -427,7 +423,7 @@ class InterceptSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with } "not grow stack when nesting same interceptor" in { - def next(n: Int, p: ActorRef[Array[StackTraceElement]]): Behavior[String] = { + def next(n: Int, p: ActorRef[Array[StackTraceElement]]): Behavior[String] = Behaviors.intercept(() => new SameTypeInterceptor) { Behaviors.receiveMessage { _ => @@ -441,7 +437,6 @@ class InterceptSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with } } } - } val probe = TestProbe[Array[StackTraceElement]]() val ref = spawn(next(0, probe.ref)) @@ -464,9 +459,8 @@ class InterceptSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with override def aroundReceive( ctx: TypedActorContext[Command], msg: Command, - target: BehaviorInterceptor.ReceiveTarget[Command]): Behavior[Command] = { + target: BehaviorInterceptor.ReceiveTarget[Command]): Behavior[Command] = target(ctx, Command(msg.s.toUpperCase())) - } } diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/LocalActorRefProviderLogMessagesSpec.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/LocalActorRefProviderLogMessagesSpec.scala index dd8b9dc05c1..a7387b0deef 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/LocalActorRefProviderLogMessagesSpec.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/LocalActorRefProviderLogMessagesSpec.scala @@ -66,16 +66,15 @@ class LocalActorRefProviderLogMessagesSpec val invalidPath = otherSystem.provider.rootPath / "user" / "foo" val provider = system.asInstanceOf[ActorSystemAdapter[_]].provider - try { + try LoggingTestKit .debug("Resolve (deserialization) of foreign path [pekko://otherSystem/user/foo]") .withLoggerName("org.apache.pekko.actor.LocalActorRefProvider.Deserialization") .expect { provider.resolveActorRef(invalidPath) } - } finally { + finally ActorTestKit.shutdown(otherSystem) - } } } } diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/OrElseSpec.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/OrElseSpec.scala index 91b803ec732..ad2e2afe3fb 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/OrElseSpec.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/OrElseSpec.scala @@ -68,7 +68,7 @@ object OrElseSpec { val pingHandlers: List[Ping => Behavior[Ping]] = ping1 :: ping2 :: ping3 :: Nil // this could be provided as a general purpose utility - @tailrec def handle(command: Ping, handlers: List[Ping => Behavior[Ping]]): Behavior[Ping] = { + @tailrec def handle(command: Ping, handlers: List[Ping => Behavior[Ping]]): Behavior[Ping] = handlers match { case Nil => Behaviors.unhandled case head :: tail => @@ -76,7 +76,6 @@ object OrElseSpec { if (Behavior.isUnhandled(next)) handle(command, tail) else next } - } Behaviors.receiveMessage(command => handle(command, pingHandlers)) } @@ -110,12 +109,11 @@ object OrElseSpec { val pingHandlers: List[PartialFunction[Ping, Behavior[Ping]]] = ping1 :: ping2 :: ping3 :: Nil // this could be provided as a general purpose utility - def handle(command: Ping, handlers: List[PartialFunction[Ping, Behavior[Ping]]]): Behavior[Ping] = { + def handle(command: Ping, handlers: List[PartialFunction[Ping, Behavior[Ping]]]): Behavior[Ping] = handlers match { case Nil => Behaviors.unhandled case head :: tail => head.applyOrElse(command, handle(_, tail)) } - } Behaviors.receiveMessage(command => handle(command, pingHandlers)) } @@ -133,7 +131,7 @@ object OrElseSpec { msg: Ping, target: BehaviorInterceptor.ReceiveTarget[Ping]): Behavior[Ping] = { - @tailrec def handle(i: Int): Behavior[Ping] = { + @tailrec def handle(i: Int): Behavior[Ping] = if (i == handlers.size) target(ctx, msg) else { @@ -147,17 +145,15 @@ object OrElseSpec { Behaviors.same } } - } handle(0) } // could do same for signals - override def isSame(other: BehaviorInterceptor[Any, Any]): Boolean = { + override def isSame(other: BehaviorInterceptor[Any, Any]): Boolean = other.isInstanceOf[OrElseInterceptor] - } } def ping1(count: Int): Behavior[Ping] = Behaviors.receiveMessagePartial { diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/SpawnProtocolSpec.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/SpawnProtocolSpec.scala index 8732279f451..bb378d7033e 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/SpawnProtocolSpec.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/SpawnProtocolSpec.scala @@ -78,9 +78,8 @@ class SpawnProtocolSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike w sys ! SpawnProtocol.Spawn(target, "child2", Props.empty, guardianReply.ref) val child2 = guardianReply.receiveMessage() child2.path.elements.mkString("/", "/", "") should ===("/user/child2") - } finally { + } finally ActorTestKit.shutdown(sys) - } } "spawn with unique name when given name is taken" in { diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/SupervisionSpec.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/SupervisionSpec.scala index 2da89af9ee9..c7a818e1a4c 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/SupervisionSpec.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/SupervisionSpec.scala @@ -320,7 +320,7 @@ class SupervisionSpec extends ScalaTestWithActorTestKit(""" throw TestException("simulated exc from constructor") } - override def onMessage(message: Command): Behavior[Command] = { + override def onMessage(message: Command): Behavior[Command] = message match { case Ping(i) => monitor ! Pong(i) @@ -328,7 +328,6 @@ class SupervisionSpec extends ScalaTestWithActorTestKit(""" // ignore others. case _ => Behaviors.same } - } } def testMessageRetentionWhenStartException(strategy: SupervisorStrategy): Unit = { @@ -407,10 +406,10 @@ class SupervisionSpec extends ScalaTestWithActorTestKit(""" "stop when strategy is stop - exception in setup" in { val probe = TestProbe[Event]("evt") - val failedSetup = Behaviors.setup[Command](_ => { + val failedSetup = Behaviors.setup[Command] { _ => throw new Exc3() targetBehavior(probe.ref) - }) + } val behv = supervise(failedSetup).onFailure[Throwable](SupervisorStrategy.stop) LoggingTestKit.error[Exc3].expect { spawn(behv) diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/TransformMessagesSpec.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/TransformMessagesSpec.scala index 290ba148c40..654d91a63b5 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/TransformMessagesSpec.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/TransformMessagesSpec.scala @@ -49,7 +49,7 @@ class TransformMessagesSpec extends ScalaTestWithActorTestKit with AnyWordSpecLi implicit val classicSystem: actor.ActorSystem = system.toClassic - def intToString(probe: ActorRef[String]): Behavior[Int] = { + def intToString(probe: ActorRef[String]): Behavior[Int] = Behaviors .receiveMessage[String] { message => probe ! message @@ -58,7 +58,6 @@ class TransformMessagesSpec extends ScalaTestWithActorTestKit with AnyWordSpecLi .transformMessages[Int] { case n if n != 13 => n.toString } - } "transformMessages" should { diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/WatchSpec.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/WatchSpec.scala index 5bddfc6da73..a8685b8d9cb 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/WatchSpec.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/WatchSpec.scala @@ -133,9 +133,9 @@ class WatchSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with LogC val behavior = Behaviors.setup[Any] { context => val child = context.spawn( Behaviors - .supervise(Behaviors.receive[Any]((_, _) => { + .supervise(Behaviors.receive[Any] { (_, _) => throw ex - })) + }) .onFailure[Throwable](SupervisorStrategy.stop), "child") context.watch(child) diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/coexistence/ClassicSupervisingTypedSpec.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/coexistence/ClassicSupervisingTypedSpec.scala index 3014042166d..cdd8bb669c3 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/coexistence/ClassicSupervisingTypedSpec.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/coexistence/ClassicSupervisingTypedSpec.scala @@ -27,7 +27,7 @@ import pekko.actor.typed.scaladsl.adapter._ import pekko.testkit.TestProbe object ProbedBehavior { - def behavior(probe: u.ActorRef): Behavior[String] = { + def behavior(probe: u.ActorRef): Behavior[String] = Behaviors .receiveMessagePartial[String] { case "throw" => throw TestException("oh dear") @@ -37,7 +37,6 @@ object ProbedBehavior { probe ! s Behaviors.same } - } } object ClassicSupervisingTypedSpec { diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/coexistence/TypedSupervisingClassicSpec.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/coexistence/TypedSupervisingClassicSpec.scala index 4989bd0d7ef..51932dd3600 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/coexistence/TypedSupervisingClassicSpec.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/coexistence/TypedSupervisingClassicSpec.scala @@ -41,13 +41,11 @@ object TypedSupervisingClassicSpec { case "throw" => throw TestException("oh dear") } - override def postStop(): Unit = { + override def postStop(): Unit = lifecycleProbe ! "postStop" - } - override def preStart(): Unit = { + override def preStart(): Unit = lifecycleProbe ! "preStart" - } } } diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/delivery/DurableWorkPullingSpec.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/delivery/DurableWorkPullingSpec.scala index 617e27c9f1e..680e7baee24 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/delivery/DurableWorkPullingSpec.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/delivery/DurableWorkPullingSpec.scala @@ -63,11 +63,10 @@ class DurableWorkPullingSpec s: DurableProducerQueue.State[TestConsumer.Job], expected: DurableProducerQueue.State[TestConsumer.Job]): Unit = { - def cleanup(a: DurableProducerQueue.State[TestConsumer.Job]): DurableProducerQueue.State[TestConsumer.Job] = { + def cleanup(a: DurableProducerQueue.State[TestConsumer.Job]): DurableProducerQueue.State[TestConsumer.Job] = a.copy( confirmedSeqNr = Map.empty, unconfirmed = s.unconfirmed.map(m => m.withConfirmationQualifier(DurableProducerQueue.NoQualifier))) - } cleanup(s) should ===(cleanup(expected)) } diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/delivery/ReliableDeliveryRandomSpec.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/delivery/ReliableDeliveryRandomSpec.scala index 99ec8e49c93..a5f7e978ebf 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/delivery/ReliableDeliveryRandomSpec.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/delivery/ReliableDeliveryRandomSpec.scala @@ -50,14 +50,13 @@ object ReliableDeliveryRandomSpec { override def aroundReceive( ctx: TypedActorContext[Any], msg: Any, - target: BehaviorInterceptor.ReceiveTarget[Any]): Behavior[Any] = { + target: BehaviorInterceptor.ReceiveTarget[Any]): Behavior[Any] = if (rnd.nextDouble() < dropProbability(msg)) { ctx.asScala.log.info("dropped {}", msg) Behaviors.same } else { target(ctx, msg) } - } } } diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/delivery/TestConsumer.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/delivery/TestConsumer.scala index d7681948ab1..bbb42b783fe 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/delivery/TestConsumer.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/delivery/TestConsumer.scala @@ -55,10 +55,9 @@ object TestConsumer { producerId: String, n: Long, producerController: ActorRef[ProducerController.Command[TestConsumer.Job]], - ack: Boolean = false): SequencedMessage[TestConsumer.Job] = { + ack: Boolean = false): SequencedMessage[TestConsumer.Job] = ConsumerController.SequencedMessage(producerId, n, TestConsumer.Job(s"msg-$n"), first = n == 1, ack)( producerController.unsafeUpcast[ProducerControllerImpl.InternalCommand]) - } def consumerEndCondition(seqNr: Long): TestConsumer.SomeAsyncJob => Boolean = { case TestConsumer.SomeAsyncJob(_, _, _, nr) => nr >= seqNr @@ -97,7 +96,7 @@ class TestConsumer( controller ! ConsumerController.Start(deliverTo) - private def active(processed: Set[(String, Long)], messageCount: Int): Behavior[Command] = { + private def active(processed: Set[(String, Long)], messageCount: Int): Behavior[Command] = Behaviors.receive { (ctx, m) => m match { case JobDelivery(msg, confirmTo, producerId, seqNr) => @@ -129,7 +128,6 @@ class TestConsumer( active(cleanProcessed + (producerId -> seqNr), messageCount + 1) } } - } } diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/delivery/TestDurableProducerQueue.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/delivery/TestDurableProducerQueue.scala index d471512141f..27dd28af251 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/delivery/TestDurableProducerQueue.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/delivery/TestDurableProducerQueue.scala @@ -46,9 +46,8 @@ object TestDurableProducerQueue { .onFailure(SupervisorStrategy.restartWithBackoff(delay, delay, 0.0)) } - def apply[A](delay: FiniteDuration, state: State[A]): Behavior[Command[A]] = { + def apply[A](delay: FiniteDuration, state: State[A]): Behavior[Command[A]] = apply(delay, new AtomicReference(state), _ => false) - } // using a fixed timestamp to simplify tests, not using the timestamps in the commands val TestTimestamp: DurableProducerQueue.TimestampMillis = Long.MaxValue @@ -103,9 +102,8 @@ class TestDurableProducerQueue[A]( } } - private def maybeFail(cmd: Command[A]): Unit = { + private def maybeFail(cmd: Command[A]): Unit = if (failWhen(cmd)) throw TestException(s"TestDurableProducerQueue failed at [$cmd]") - } } diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/delivery/TestProducer.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/delivery/TestProducer.scala index de6fd1dac8f..eb01c5e4409 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/delivery/TestProducer.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/delivery/TestProducer.scala @@ -33,7 +33,7 @@ object TestProducer { def apply( delay: FiniteDuration, - producerController: ActorRef[ProducerController.Start[TestConsumer.Job]]): Behavior[Command] = { + producerController: ActorRef[ProducerController.Start[TestConsumer.Job]]): Behavior[Command] = Behaviors.setup { context => context.setLoggerName("TestProducer") val requestNextAdapter: ActorRef[ProducerController.RequestNext[TestConsumer.Job]] = @@ -49,16 +49,14 @@ object TestProducer { } } } - } - private def idle(n: Int): Behavior[Command] = { + private def idle(n: Int): Behavior[Command] = Behaviors.receiveMessage { case Tick => Behaviors.same case RequestNext(sendTo) => active(n + 1, sendTo) } - } - private def active(n: Int, sendTo: ActorRef[TestConsumer.Job]): Behavior[Command] = { + private def active(n: Int, sendTo: ActorRef[TestConsumer.Job]): Behavior[Command] = Behaviors.receive { (ctx, msg) => msg match { case Tick => @@ -69,15 +67,13 @@ object TestProducer { throw new IllegalStateException("Unexpected RequestNext, already got one.") } } - } - private def activeNoDelay(n: Int): Behavior[Command] = { + private def activeNoDelay(n: Int): Behavior[Command] = Behaviors.receivePartial { case (ctx, RequestNext(sendTo)) => sendMessage(n, sendTo, ctx) activeNoDelay(n + 1) } - } private def sendMessage(n: Int, sendTo: ActorRef[TestConsumer.Job], ctx: ActorContext[Command]): Unit = { val msg = s"msg-$n" diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/delivery/TestProducerWithAsk.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/delivery/TestProducerWithAsk.scala index 79855cdc518..da69d11d1cc 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/delivery/TestProducerWithAsk.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/delivery/TestProducerWithAsk.scala @@ -38,7 +38,7 @@ object TestProducerWithAsk { def apply( delay: FiniteDuration, replyProbe: ActorRef[Long], - producerController: ActorRef[ProducerController.Start[TestConsumer.Job]]): Behavior[Command] = { + producerController: ActorRef[ProducerController.Start[TestConsumer.Job]]): Behavior[Command] = Behaviors.setup { context => context.setLoggerName("TestProducerWithConfirmation") val requestNextAdapter: ActorRef[ProducerController.RequestNext[TestConsumer.Job]] = @@ -50,9 +50,8 @@ object TestProducerWithAsk { idle(0, replyProbe) } } - } - private def idle(n: Int, replyProbe: ActorRef[Long]): Behavior[Command] = { + private def idle(n: Int, replyProbe: ActorRef[Long]): Behavior[Command] = Behaviors.receivePartial { case (_, Tick) => Behaviors.same case (_, RequestNext(sendTo)) => active(n + 1, replyProbe, sendTo) @@ -63,12 +62,11 @@ object TestProducerWithAsk { ctx.log.warn("Timeout") Behaviors.same } - } private def active( n: Int, replyProbe: ActorRef[Long], - sendTo: ActorRef[ProducerController.MessageWithConfirmation[TestConsumer.Job]]): Behavior[Command] = { + sendTo: ActorRef[ProducerController.MessageWithConfirmation[TestConsumer.Job]]): Behavior[Command] = Behaviors.receivePartial { case (ctx, Tick) => val msg = s"msg-$n" @@ -95,6 +93,4 @@ object TestProducerWithAsk { Behaviors.same } - } - } diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/delivery/TestProducerWorkPulling.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/delivery/TestProducerWorkPulling.scala index 384f7c4a956..11913a086d3 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/delivery/TestProducerWorkPulling.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/delivery/TestProducerWorkPulling.scala @@ -28,7 +28,7 @@ object TestProducerWorkPulling { def apply( delay: FiniteDuration, - producerController: ActorRef[WorkPullingProducerController.Start[TestConsumer.Job]]): Behavior[Command] = { + producerController: ActorRef[WorkPullingProducerController.Start[TestConsumer.Job]]): Behavior[Command] = Behaviors.setup { context => context.setLoggerName("TestProducerWorkPulling") val requestNextAdapter: ActorRef[WorkPullingProducerController.RequestNext[TestConsumer.Job]] = @@ -40,16 +40,14 @@ object TestProducerWorkPulling { idle(0) } } - } - private def idle(n: Int): Behavior[Command] = { + private def idle(n: Int): Behavior[Command] = Behaviors.receiveMessagePartial { case Tick => Behaviors.same case RequestNext(sendTo) => active(n + 1, sendTo) } - } - private def active(n: Int, sendTo: ActorRef[TestConsumer.Job]): Behavior[Command] = { + private def active(n: Int, sendTo: ActorRef[TestConsumer.Job]): Behavior[Command] = Behaviors.receivePartial { case (ctx, Tick) => val msg = s"msg-$n" @@ -60,6 +58,5 @@ object TestProducerWorkPulling { case (_, RequestNext(_)) => throw new IllegalStateException("Unexpected RequestNext, already got one.") } - } } diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/eventstream/EventStreamDocSpec.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/eventstream/EventStreamDocSpec.scala index b47c81769f4..ca0ec18c2a1 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/eventstream/EventStreamDocSpec.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/eventstream/EventStreamDocSpec.scala @@ -34,7 +34,7 @@ object EventStreamDocSpec { sealed trait Command final case class DeadLetterWrapper(deadLetter: DeadLetter) extends Command - def apply(): Behavior[Command] = { + def apply(): Behavior[Command] = Behaviors.setup[Command] { context => val adapter = context.messageAdapter[DeadLetter](DeadLetterWrapper.apply) @@ -47,7 +47,6 @@ object EventStreamDocSpec { Behaviors.same } } - } } // #listen-to-dead-letters @@ -56,7 +55,7 @@ object EventStreamDocSpec { sealed trait Command final case class AllDeadLettersWrapper(allDeadLetters: AllDeadLetters) extends Command - def apply(): Behavior[Command] = { + def apply(): Behavior[Command] = Behaviors.setup[Command] { context => val adapter = context.messageAdapter[AllDeadLetters](AllDeadLettersWrapper.apply) @@ -85,7 +84,6 @@ object EventStreamDocSpec { Behaviors.same } } - } } // #listen-to-super-class } diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/internal/receptionist/LocalReceptionistSpec.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/internal/receptionist/LocalReceptionistSpec.scala index d463f23c44c..e2fecf9a0b9 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/internal/receptionist/LocalReceptionistSpec.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/internal/receptionist/LocalReceptionistSpec.scala @@ -208,9 +208,8 @@ class LocalReceptionistSpec extends ScalaTestWithActorTestKit with AnyWordSpecLi class LocalReceptionistBehaviorSpec extends AnyWordSpec with Matchers with LogCapturing { import LocalReceptionistSpec._ - def assertEmpty(inboxes: TestInbox[_]*): Unit = { + def assertEmpty(inboxes: TestInbox[_]*): Unit = inboxes.foreach(i => withClue(s"inbox $i had messages")(i.hasMessages should be(false))) - } "A local receptionist behavior" must { diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/internal/routing/RoutingLogicSpec.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/internal/routing/RoutingLogicSpec.scala index 2cc5111b54b..855f708fbe1 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/internal/routing/RoutingLogicSpec.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/internal/routing/RoutingLogicSpec.scala @@ -224,11 +224,10 @@ class RoutingLogicSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike wi verifyConsistentHashing(logic) } - def verifyConsistentHashing(logic: ConsistentHashingLogic[Int]): Boolean = { + def verifyConsistentHashing(logic: ConsistentHashingLogic[Int]): Boolean = messages.view.map(_._2.map(logic.selectRoutee)).forall { refs => refs.headOption.forall(head => refs.forall(_ == head)) } - } } } diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/pubsub/LocalPubSubSpec.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/pubsub/LocalPubSubSpec.scala index 08198f23dca..926955a0dda 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/pubsub/LocalPubSubSpec.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/pubsub/LocalPubSubSpec.scala @@ -51,9 +51,8 @@ class LocalPubSubSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike wit probe2.expectMessage("banana") probe3.expectMessage("banana") - } finally { + } finally testKit.stop(fruitTopic) - } } "publish to all subscriber actors across several instances of the same topic" in { @@ -120,9 +119,8 @@ class LocalPubSubSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike wit veggieTopic ! Topic.Publish("carrot") probe1.expectNoMessage(200.millis) - } finally { + } finally testKit.stop(fruitTopic) - } } "doesn't publish after unsubscribe" in { @@ -148,9 +146,8 @@ class LocalPubSubSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike wit fruitTopic ! Topic.Publish("orange") probe1.expectNoMessage(200.millis) - } finally { + } finally testKit.stop(fruitTopic) - } } } diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/ActorLoggingSpec.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/ActorLoggingSpec.scala index 7924d56f0a0..7360355a27c 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/ActorLoggingSpec.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/ActorLoggingSpec.scala @@ -57,9 +57,8 @@ object BehaviorWhereTheLoggerIsUsed { } class BehaviorWhereTheLoggerIsUsed(context: ActorContext[String]) extends AbstractBehavior[String](context) { context.log.info("Starting up") - override def onMessage(msg: String): Behavior[String] = { + override def onMessage(msg: String): Behavior[String] = Behaviors.same - } } class ActorLoggingSpec extends ScalaTestWithActorTestKit(""" @@ -314,9 +313,8 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit(""" classicSys.settings.Loggers should ===(List(classOf[Slf4jLogger].getName)) classicSys.settings.LoggingFilter should ===(classOf[Slf4jLoggingFilter].getName) - } finally { + } finally ActorTestKit.shutdown(classicSys.toTyped) - } } "not be amended when use-slf4j=off" in { @@ -495,7 +493,7 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit(""" } } - def assertExpectedMdc(event: LoggingEvent) = { + def assertExpectedMdc(event: LoggingEvent) = try { event.mdc should contain allElementsOf ( Map( @@ -509,7 +507,6 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit(""" ex.printStackTrace() false } - } // log from setup // can't use LoggingEventFilter.withMdc here because the actorPathStr isn't know yet diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/ActorThreadSpec.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/ActorThreadSpec.scala index f13ddd45f1b..46ca8e184cf 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/ActorThreadSpec.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/ActorThreadSpec.scala @@ -72,9 +72,9 @@ class ActorThreadSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike wit val ref = spawn(Behaviors.receive[CountDownLatch] { case (context, latch) => Future { - try { + try context.children - } catch { + catch { case e: UnsupportedOperationException => probe.ref ! e } @@ -87,9 +87,8 @@ class ActorThreadSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike wit try { ref ! l probe.receiveMessage().getMessage should include("Unsupported access to ActorContext") - } finally { + } finally l.countDown() - } } "detect illegal access to ActorContext from other thread after processing message" in { @@ -114,9 +113,8 @@ class ActorThreadSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike wit try { ref ! l probe.expectTerminated(ref) - } finally { + } finally l.countDown() - } probe.receiveMessage().getMessage should include("Unsupported access to ActorContext") } @@ -127,9 +125,9 @@ class ActorThreadSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike wit case (context, _) => // really bad idea to define a child actor like this context.spawnAnonymous(Behaviors.setup[String] { _ => - try { + try context.children - } catch { + catch { case e: UnsupportedOperationException => probe.ref ! e } @@ -222,16 +220,15 @@ class ActorThreadSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike wit Behaviors.setup[String](_ => // wrongly using parent's context new AbstractBehavior[String](context) { - try { + try this.context.children - } catch { + catch { case e: UnsupportedOperationException => probe.ref ! e } - override def onMessage(msg: String): Behavior[String] = { + override def onMessage(msg: String): Behavior[String] = Behaviors.same - } })) Behaviors.empty @@ -271,9 +268,8 @@ class ActorThreadSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike wit .expect { ref2 ! new CountDownLatch(0) } - } finally { + } finally latch1.countDown() - } } } diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/DispatcherSelectorSpec.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/DispatcherSelectorSpec.scala index 62dcd12c5e4..4829de75973 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/DispatcherSelectorSpec.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/DispatcherSelectorSpec.scala @@ -131,9 +131,8 @@ class DispatcherSelectorSpec(config: Config) val response = probe.receiveMessage() response.threadName should startWith("DispatcherSelectorSpec2-pekko.actor.default-dispatcher") - } finally { + } finally ActorTestKit.shutdown(sys) - } } } diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/MailboxSelectorSpec.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/MailboxSelectorSpec.scala index 0f9b6a42c7b..b114adc5d76 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/MailboxSelectorSpec.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/MailboxSelectorSpec.scala @@ -73,7 +73,7 @@ class MailboxSelectorSpec(config: Config) case class WhatsYourMailbox(replyTo: ActorRef[MessageQueue]) extends Command case class WhatsYourDispatcher(replyTo: ActorRef[String]) extends Command - private def extract[R](context: ActorContext[_], f: ActorCell => R): R = { + private def extract[R](context: ActorContext[_], f: ActorCell => R): R = context match { case adapter: ActorContextAdapter[_] => adapter.classicActorContext match { @@ -82,7 +82,6 @@ class MailboxSelectorSpec(config: Config) } case unexpected => throw new RuntimeException(s"Unexpected: $unexpected") } - } private def behavior: Behavior[Command] = Behaviors.setup { context => diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/MessageAdapterSpec.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/MessageAdapterSpec.scala index a45a03e875f..96a4acf9cb5 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/MessageAdapterSpec.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/MessageAdapterSpec.scala @@ -52,7 +52,7 @@ class MessageAdapterSpec private val log = LoggerFactory.getLogger(getClass) - private def assertDeadLetter(deadLetterProbe: TestProbe[DeadLetter], expectedMessage: Any): Unit = { + private def assertDeadLetter(deadLetterProbe: TestProbe[DeadLetter], expectedMessage: Any): Unit = deadLetterProbe.fishForMessage(deadLetterProbe.remainingOrDefault, s"looking for DeadLetter $expectedMessage") { deadLetter => deadLetter.message match { @@ -68,7 +68,6 @@ class MessageAdapterSpec FishingOutcomes.continueAndIgnore } } - } "Message adapters" must { diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/OnSignalSpec.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/OnSignalSpec.scala index 570c77491b2..fa9e1c5d00e 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/OnSignalSpec.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/OnSignalSpec.scala @@ -75,9 +75,8 @@ final class OnSignalSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike try { system ! "stop" probe.expectMessage(Done) - } finally { + } finally ActorTestKit.shutdown(system) - } } } } diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/StashSpec.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/StashSpec.scala index c339c5851c7..1e636b88a61 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/StashSpec.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/StashSpec.scala @@ -145,7 +145,7 @@ object AbstractStashSpec { private var stashing = false private var processed = Vector.empty[String] - override def onMessage(cmd: Command): Behavior[Command] = { + override def onMessage(cmd: Command): Behavior[Command] = cmd match { case message: Msg => if (stashing) @@ -189,7 +189,6 @@ object AbstractStashSpec { case _: Unstashed => Behaviors.unhandled } - } } @@ -276,7 +275,7 @@ class UnstashingSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with private def stashingBehavior( probe: ActorRef[String], - withSlowStoppingChild: Option[CountDownLatch] = None): Behavior[String] = { + withSlowStoppingChild: Option[CountDownLatch] = None): Behavior[String] = Behaviors.setup[String] { ctx => withSlowStoppingChild.foreach(latch => ctx.spawnAnonymous(slowStoppingChild(latch))) @@ -324,7 +323,6 @@ class UnstashingSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with } } } - } "Unstashing" must { diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/StopSpec.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/StopSpec.scala index ef73035499c..b64e4eaa598 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/StopSpec.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/StopSpec.scala @@ -81,9 +81,8 @@ class StopSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with LogCa override def aroundReceive( context: typed.TypedActorContext[AnyRef], message: AnyRef, - target: ReceiveTarget[AnyRef]): Behavior[AnyRef] = { + target: ReceiveTarget[AnyRef]): Behavior[AnyRef] = target(context, message) - } })(Behaviors.stopped { () => probe.ref ! Done }) diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/adapter/AdapterSpec.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/adapter/AdapterSpec.scala index 5526af02a59..76f92cf6d55 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/adapter/AdapterSpec.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/adapter/AdapterSpec.scala @@ -210,18 +210,18 @@ class AdapterSpec extends AnyWordSpec with Matchers with BeforeAndAfterAll with "not crash if guardian is stopped" in { for { _ <- 0 to 10 } { var systemN: pekko.actor.typed.ActorSystem[NotUsed] = null - try { + try systemN = ActorSystem.create( Behaviors.setup[NotUsed](_ => Behaviors.stopped[NotUsed]), "AdapterSpec-stopping-guardian") - } finally if (system != null) TestKit.shutdownActorSystem(systemN.toClassic) + finally if (system != null) TestKit.shutdownActorSystem(systemN.toClassic) } } "not crash if guardian is stopped very quickly" in { for { _ <- 0 to 10 } { var systemN: pekko.actor.typed.ActorSystem[Done] = null - try { + try systemN = ActorSystem.create(Behaviors.receive[Done] { (context, message) => context.self ! Done message match { @@ -230,7 +230,7 @@ class AdapterSpec extends AnyWordSpec with Matchers with BeforeAndAfterAll with }, "AdapterSpec-stopping-guardian-2") - } finally if (system != null) TestKit.shutdownActorSystem(systemN.toClassic) + finally if (system != null) TestKit.shutdownActorSystem(systemN.toClassic) } } diff --git a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/adapter/GuardianStartupSpec.scala b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/adapter/GuardianStartupSpec.scala index a2a14118ede..fe49f5d0b99 100644 --- a/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/adapter/GuardianStartupSpec.scala +++ b/actor-typed-tests/src/test/scala/org/apache/pekko/actor/typed/scaladsl/adapter/GuardianStartupSpec.scala @@ -44,10 +44,9 @@ class GuardianStartupSpec extends AnyWordSpec with Matchers with ScalaFutures wi sawMsg.await(3, TimeUnit.SECONDS) should ===(true) - } finally { + } finally if (system ne null) ActorTestKit.shutdown(system) - } } "not start before classic system initialization is complete" in { @@ -64,10 +63,9 @@ class GuardianStartupSpec extends AnyWordSpec with Matchers with ScalaFutures wi initialized.await(3, TimeUnit.SECONDS) should ===(true) - } finally { + } finally if (system ne null) ActorTestKit.shutdown(system) - } } "have its shutdown hook run on immediate shutdown (after start)" in { @@ -82,10 +80,9 @@ class GuardianStartupSpec extends AnyWordSpec with Matchers with ScalaFutures wi system.whenTerminated.futureValue stopHookExecuted.await(3, TimeUnit.SECONDS) should ===(true) - } finally { + } finally if (system ne null) ActorTestKit.shutdown(system) - } } } diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/ActorRef.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/ActorRef.scala index b25f0560186..67197a1f615 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/ActorRef.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/ActorRef.scala @@ -82,9 +82,8 @@ object ActorRef { * INTERNAL API */ private[pekko] object SerializedActorRef { - def apply[T](actorRef: ActorRef[T]): SerializedActorRef[T] = { + def apply[T](actorRef: ActorRef[T]): SerializedActorRef[T] = new SerializedActorRef(actorRef) - } def toAddress[T](actorRef: ActorRef[T]) = { import pekko.actor.typed.scaladsl.adapter._ diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/ActorSystem.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/ActorSystem.scala index d60d91077ee..85f925a7bb1 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/ActorSystem.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/ActorSystem.scala @@ -226,9 +226,8 @@ object ActorSystem { guardianBehavior: Behavior[T], name: String, setup: ActorSystemSetup, - guardianProps: Props = Props.empty): ActorSystem[T] = { + guardianProps: Props = Props.empty): ActorSystem[T] = createInternal(name, guardianBehavior, guardianProps, setup) - } /** * Scala API: Shortcut for creating an actor system with custom bootstrap settings. diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/Behavior.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/Behavior.scala index b7899957009..10912884cc4 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/Behavior.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/Behavior.scala @@ -195,7 +195,7 @@ object Behavior { * Starts deferred behavior and nested deferred behaviors until all deferred behaviors in the stack are started * and then the resulting behavior is returned. */ - def start[T](behavior: Behavior[T], ctx: TypedActorContext[T]): Behavior[T] = { + def start[T](behavior: Behavior[T], ctx: TypedActorContext[T]): Behavior[T] = // note that this can't be @tailrec, but normal stack of interceptors and similar shouldn't be // that deep, and if they are it's most likely a bug which will be seen as StackOverflowError behavior match { @@ -208,7 +208,6 @@ object Behavior { case supervise: SuperviseBehavior[T] => start(supervise.unwrap, ctx) case _ => behavior } - } /** * Go through the behavior stack and apply a predicate to see if any nested behavior diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/BehaviorInterceptor.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/BehaviorInterceptor.scala index b25a24a50aa..648f456106d 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/BehaviorInterceptor.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/BehaviorInterceptor.scala @@ -163,10 +163,9 @@ abstract class BehaviorSignalInterceptor[Inner] extends BehaviorInterceptor[Inne final override def aroundReceive( ctx: TypedActorContext[Inner], msg: Inner, - target: ReceiveTarget[Inner]): Behavior[Inner] = { + target: ReceiveTarget[Inner]): Behavior[Inner] = // by using `null` as interceptMessageClass of `BehaviorInterceptor` no messages will pass here throw new IllegalStateException(s"Unexpected message in ${getClass.getName}, it should only intercept signals.") - } /** * Intercept a signal sent to the running actor. Pass the signal on to the next behavior diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/Props.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/Props.scala index 3c8a8d23f3c..0c70161016f 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/Props.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/Props.scala @@ -102,13 +102,12 @@ abstract class Props private[pekko] () extends Product with Serializable { */ @InternalApi private[pekko] def firstOrElse[T <: Props: ClassTag](default: T): T = { - @tailrec def rec(d: Props): T = { + @tailrec def rec(d: Props): T = d match { case EmptyProps => default case t: T => t case _ => rec(d.next) } - } rec(this) } diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/ConsumerController.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/ConsumerController.scala index 3ff6e20801b..4ce66a89bd0 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/ConsumerController.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/ConsumerController.scala @@ -182,20 +182,18 @@ object ConsumerController { copy(first = true)(producerController) /** INTERNAL API */ - @InternalApi private[pekko] def isFirstChunk: Boolean = { + @InternalApi private[pekko] def isFirstChunk: Boolean = message match { case c: ChunkedMessage => c.firstChunk case _ => true } - } /** INTERNAL API */ - @InternalApi private[pekko] def isLastChunk: Boolean = { + @InternalApi private[pekko] def isLastChunk: Boolean = message match { case c: ChunkedMessage => c.lastChunk case _ => true } - } } object Settings { @@ -211,13 +209,12 @@ object ConsumerController { * Scala API: Factory method from Config corresponding to * `pekko.reliable-delivery.consumer-controller`. */ - def apply(config: Config): Settings = { + def apply(config: Config): Settings = new Settings( flowControlWindow = config.getInt("flow-control-window"), resendIntervalMin = config.getDuration("resend-interval-min").asScala, resendIntervalMax = config.getDuration("resend-interval-max").asScala, onlyFlowControl = config.getBoolean("only-flow-control")) - } /** * Java API: Factory method from config `pekko.reliable-delivery.producer-controller` @@ -316,9 +313,8 @@ object ConsumerController { */ @InternalApi private[pekko] def apply[A]( serviceKey: Option[ServiceKey[Command[A]]], - settings: Settings): Behavior[Command[A]] = { + settings: Settings): Behavior[Command[A]] = ConsumerControllerImpl(serviceKey, settings) - } /** * Java API diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/DurableProducerQueue.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/DurableProducerQueue.scala index cd69940cd81..bba0946b2c3 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/DurableProducerQueue.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/DurableProducerQueue.scala @@ -80,9 +80,8 @@ object DurableProducerQueue { unconfirmed: immutable.IndexedSeq[MessageSent[A]]) extends DeliverySerializable { - def addMessageSent(sent: MessageSent[A]): State[A] = { + def addMessageSent(sent: MessageSent[A]): State[A] = copy(currentSeqNr = sent.seqNr + 1, unconfirmed = unconfirmed :+ sent) - } def confirmed( seqNr: SeqNr, @@ -97,14 +96,13 @@ object DurableProducerQueue { unconfirmed = newUnconfirmed) } - def cleanup(confirmationQualifiers: Set[String]): State[A] = { + def cleanup(confirmationQualifiers: Set[String]): State[A] = copy(confirmedSeqNr = confirmedSeqNr -- confirmationQualifiers) - } /** * If not all chunked messages were stored before crash those partial chunked messages should not be resent. */ - def cleanupPartialChunkedMessages(): State[A] = { + def cleanupPartialChunkedMessages(): State[A] = if (unconfirmed.isEmpty || unconfirmed.forall(u => u.isFirstChunk && u.isLastChunk)) { this } else { @@ -130,7 +128,6 @@ object DurableProducerQueue { } copy(currentSeqNr = newCurrentSeqNr, unconfirmed = newUnconfirmed.result()) } - } } /** @@ -150,20 +147,18 @@ object DurableProducerQueue { extends Event { /** INTERNAL API */ - @InternalApi private[pekko] def isFirstChunk: Boolean = { + @InternalApi private[pekko] def isFirstChunk: Boolean = message match { case c: ChunkedMessage => c.firstChunk case _ => true } - } /** INTERNAL API */ - @InternalApi private[pekko] def isLastChunk: Boolean = { + @InternalApi private[pekko] def isLastChunk: Boolean = message match { case c: ChunkedMessage => c.lastChunk case _ => true } - } def withConfirmationQualifier(qualifier: ConfirmationQualifier): MessageSent[A] = new MessageSent(seqNr, message, ack, qualifier, timestampMillis) @@ -171,14 +166,13 @@ object DurableProducerQueue { def withTimestampMillis(timestamp: TimestampMillis): MessageSent[A] = new MessageSent(seqNr, message, ack, confirmationQualifier, timestamp) - override def equals(obj: Any): Boolean = { + override def equals(obj: Any): Boolean = obj match { case other: MessageSent[_] => seqNr == other.seqNr && message == other.message && ack == other.ack && confirmationQualifier == other .confirmationQualifier && timestampMillis == other.timestampMillis case _ => false } - } override def hashCode(): Int = seqNr.hashCode() diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/ProducerController.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/ProducerController.scala index 252f06fa077..4078f27813b 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/ProducerController.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/ProducerController.scala @@ -254,18 +254,16 @@ object ProducerController { def apply[A: ClassTag]( producerId: String, - durableQueueBehavior: Option[Behavior[DurableProducerQueue.Command[A]]]): Behavior[Command[A]] = { + durableQueueBehavior: Option[Behavior[DurableProducerQueue.Command[A]]]): Behavior[Command[A]] = Behaviors.setup { context => ProducerControllerImpl(producerId, durableQueueBehavior, ProducerController.Settings(context.system)) } - } def apply[A: ClassTag]( producerId: String, durableQueueBehavior: Option[Behavior[DurableProducerQueue.Command[A]]], - settings: Settings): Behavior[Command[A]] = { + settings: Settings): Behavior[Command[A]] = ProducerControllerImpl(producerId, durableQueueBehavior, settings) - } /** * INTERNAL API @@ -283,9 +281,8 @@ object ProducerController { producerId: String, durableQueueBehavior: Option[Behavior[DurableProducerQueue.Command[A]]], settings: Settings, - send: ConsumerController.SequencedMessage[A] => Unit): Behavior[Command[A]] = { + send: ConsumerController.SequencedMessage[A] => Unit): Behavior[Command[A]] = ProducerControllerImpl(producerId, durableQueueBehavior, settings, send) - } /** * Java API @@ -293,9 +290,8 @@ object ProducerController { def create[A]( messageClass: Class[A], producerId: String, - durableQueueBehavior: Optional[Behavior[DurableProducerQueue.Command[A]]]): Behavior[Command[A]] = { + durableQueueBehavior: Optional[Behavior[DurableProducerQueue.Command[A]]]): Behavior[Command[A]] = apply(producerId, durableQueueBehavior.toScala)(ClassTag(messageClass)) - } /** * Java API @@ -304,8 +300,7 @@ object ProducerController { messageClass: Class[A], producerId: String, durableQueueBehavior: Optional[Behavior[DurableProducerQueue.Command[A]]], - settings: Settings): Behavior[Command[A]] = { + settings: Settings): Behavior[Command[A]] = apply(producerId, durableQueueBehavior.toScala, settings)(ClassTag(messageClass)) - } } diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/WorkPullingProducerController.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/WorkPullingProducerController.scala index bbe094f3c21..664a44731b9 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/WorkPullingProducerController.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/WorkPullingProducerController.scala @@ -161,12 +161,11 @@ object WorkPullingProducerController { * Scala API: Factory method from Config corresponding to * `pekko.reliable-delivery.work-pulling.producer-controller`. */ - def apply(config: Config): Settings = { + def apply(config: Config): Settings = new Settings( bufferSize = config.getInt("buffer-size"), config.getDuration("internal-ask-timeout").asScala, ProducerController.Settings(config)) - } /** * Java API: Factory method from config `pekko.reliable-delivery.work-pulling.producer-controller` @@ -219,19 +218,17 @@ object WorkPullingProducerController { def apply[A: ClassTag]( producerId: String, workerServiceKey: ServiceKey[ConsumerController.Command[A]], - durableQueueBehavior: Option[Behavior[DurableProducerQueue.Command[A]]]): Behavior[Command[A]] = { + durableQueueBehavior: Option[Behavior[DurableProducerQueue.Command[A]]]): Behavior[Command[A]] = Behaviors.setup { context => WorkPullingProducerControllerImpl(producerId, workerServiceKey, durableQueueBehavior, Settings(context.system)) } - } def apply[A: ClassTag]( producerId: String, workerServiceKey: ServiceKey[ConsumerController.Command[A]], durableQueueBehavior: Option[Behavior[DurableProducerQueue.Command[A]]], - settings: Settings): Behavior[Command[A]] = { + settings: Settings): Behavior[Command[A]] = WorkPullingProducerControllerImpl(producerId, workerServiceKey, durableQueueBehavior, settings) - } /** * Java API @@ -240,9 +237,8 @@ object WorkPullingProducerController { messageClass: Class[A], producerId: String, workerServiceKey: ServiceKey[ConsumerController.Command[A]], - durableQueueBehavior: Optional[Behavior[DurableProducerQueue.Command[A]]]): Behavior[Command[A]] = { + durableQueueBehavior: Optional[Behavior[DurableProducerQueue.Command[A]]]): Behavior[Command[A]] = apply(producerId, workerServiceKey, durableQueueBehavior.toScala)(ClassTag(messageClass)) - } /** * Java API @@ -252,7 +248,6 @@ object WorkPullingProducerController { producerId: String, workerServiceKey: ServiceKey[ConsumerController.Command[A]], durableQueueBehavior: Optional[Behavior[DurableProducerQueue.Command[A]]], - settings: Settings): Behavior[Command[A]] = { + settings: Settings): Behavior[Command[A]] = apply(producerId, workerServiceKey, durableQueueBehavior.toScala, settings)(ClassTag(messageClass)) - } } diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/internal/ConsumerControllerImpl.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/internal/ConsumerControllerImpl.scala index 0467cb1aab0..446bb3ce342 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/internal/ConsumerControllerImpl.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/internal/ConsumerControllerImpl.scala @@ -108,22 +108,20 @@ import pekko.util.ConstantFun.scalaIdentityFunction def isProducerChanged(seqMsg: SequencedMessage[A]): Boolean = seqMsg.producerController != producerController || receivedSeqNr == 0 - def updatedRegistering(seqMsg: SequencedMessage[A]): Option[ActorRef[ProducerController.Command[A]]] = { + def updatedRegistering(seqMsg: SequencedMessage[A]): Option[ActorRef[ProducerController.Command[A]]] = registering match { case None => None case s @ Some(reg) => if (seqMsg.producerController == reg) None else s } - } - def clearCollectedChunks(): State[A] = { + def clearCollectedChunks(): State[A] = if (collectedChunks == Nil) this else copy(collectedChunks = Nil) - } } def apply[A]( serviceKey: Option[ServiceKey[Command[A]]], - settings: ConsumerController.Settings): Behavior[Command[A]] = { + settings: ConsumerController.Settings): Behavior[Command[A]] = Behaviors .withStash[InternalCommand](settings.flowControlWindow) { stashBuffer => Behaviors.setup { context => @@ -137,7 +135,7 @@ import pekko.util.ConstantFun.scalaIdentityFunction Behaviors.withTimers { timers => // wait for the `Start` message from the consumer, SequencedMessage will be stashed def waitForStart(registering: Option[ActorRef[ProducerController.Command[A]]], stopping: Boolean) - : Behavior[InternalCommand] = { + : Behavior[InternalCommand] = Behaviors.receiveMessagePartial { case reg: RegisterToProducerController[A] @unchecked => reg.producerController ! ProducerController.RegisterConsumer(context.self) @@ -190,8 +188,6 @@ import pekko.util.ConstantFun.scalaIdentityFunction } - } - timers.startTimerWithFixedDelay(Retry, Retry, settings.resendIntervalMin) waitForStart(None, stopping = false) } @@ -199,20 +195,18 @@ import pekko.util.ConstantFun.scalaIdentityFunction } } .narrow // expose Command, but not InternalCommand - } - private def mdcForMessage(msg: InternalCommand): Map[String, String] = { + private def mdcForMessage(msg: InternalCommand): Map[String, String] = msg match { case seqMsg: SequencedMessage[_] => Map("producerId" -> seqMsg.producerId) case _ => Map.empty } - } private def initialState[A]( context: ActorContext[InternalCommand], start: Start[A], registering: Option[ActorRef[ProducerController.Command[A]]], - stopping: Boolean): State[A] = { + stopping: Boolean): State[A] = State( producerController = context.system.deadLetters, "n/a", @@ -223,12 +217,10 @@ import pekko.util.ConstantFun.scalaIdentityFunction collectedChunks = Nil, registering, stopping) - } - def enforceLocalConsumer(ref: ActorRef[_]): Unit = { + def enforceLocalConsumer(ref: ActorRef[_]): Unit = if (ref.path.address.hasGlobalScope) throw new IllegalArgumentException(s"Consumer [$ref] should be local.") - } private class RetryTimer( timers: TimerScheduler[ConsumerControllerImpl.InternalCommand], @@ -259,10 +251,9 @@ import pekko.util.ConstantFun.scalaIdentityFunction } } - def reset(): Unit = { + def reset(): Unit = if (_interval ne minBackoff) start() - } } } @@ -296,7 +287,7 @@ private class ConsumerControllerImpl[A] private ( // Expecting a SequencedMessage from ProducerController, that will be delivered to the consumer if // the seqNr is right. - private def active(s: State[A]): Behavior[InternalCommand] = { + private def active(s: State[A]): Behavior[InternalCommand] = Behaviors .receiveMessage[InternalCommand] { case seqMsg: SequencedMessage[A @unchecked] => @@ -368,7 +359,6 @@ private class ConsumerControllerImpl[A] private ( .receiveSignal { case (_, PostStop) => postStop(s) } - } private def receiveChangedProducer(s: State[A], seqMsg: SequencedMessage[A]): Behavior[InternalCommand] = { val seqNr = seqMsg.seqNr @@ -412,7 +402,7 @@ private class ConsumerControllerImpl[A] private ( } - private def logChangedProducer(s: State[A], seqMsg: SequencedMessage[A]): Unit = { + private def logChangedProducer(s: State[A], seqMsg: SequencedMessage[A]): Unit = if (s.producerController == context.system.deadLetters) { context.log.debugN( "Associated with new ProducerController [{}], seqNr [{}].", @@ -426,7 +416,6 @@ private class ConsumerControllerImpl[A] private ( seqMsg.producerController, seqMsg.seqNr) } - } // It has detected a missing seqNr and requested a Resend. Expecting a SequencedMessage from the // ProducerController with the missing seqNr. Other SequencedMessage with different seqNr will be @@ -550,7 +539,7 @@ private class ConsumerControllerImpl[A] private ( // The message has been delivered to the consumer and it is now waiting for Confirmed from // the consumer. New SequencedMessage from the ProducerController will be stashed. - private def waitingForConfirmation(s: State[A], seqMsg: SequencedMessage[A]): Behavior[InternalCommand] = { + private def waitingForConfirmation(s: State[A], seqMsg: SequencedMessage[A]): Behavior[InternalCommand] = Behaviors .receiveMessage[InternalCommand] { case Confirmed => @@ -651,7 +640,6 @@ private class ConsumerControllerImpl[A] private ( .receiveSignal { case (_, PostStop) => postStop(s) } - } private def receiveRetry(s: State[A], nextBehavior: () => Behavior[InternalCommand]): Behavior[InternalCommand] = { retryTimer.scheduleNext() @@ -683,7 +671,7 @@ private class ConsumerControllerImpl[A] private ( private def receiveRegisterToProducerController( s: State[A], reg: RegisterToProducerController[A], - nextBehavior: State[A] => Behavior[InternalCommand]): Behavior[InternalCommand] = { + nextBehavior: State[A] => Behavior[InternalCommand]): Behavior[InternalCommand] = if (reg.producerController != s.producerController) { context.log.debug2( "Register to new ProducerController [{}], previous was [{}].", @@ -695,18 +683,16 @@ private class ConsumerControllerImpl[A] private ( } else { Behaviors.same } - } private def receiveDeliverThenStop( s: State[A], - nextBehavior: State[A] => Behavior[InternalCommand]): Behavior[InternalCommand] = { + nextBehavior: State[A] => Behavior[InternalCommand]): Behavior[InternalCommand] = if (stashBuffer.isEmpty && s.receivedSeqNr == s.confirmedSeqNr) { context.log.debug("Stopped at seqNr [{}], no buffered messages.", s.confirmedSeqNr) Behaviors.stopped } else { nextBehavior(s.copy(stopping = true)) } - } private def receiveConsumerTerminated(c: ActorRef[_]): Behavior[InternalCommand] = { context.log.debug("Consumer [{}] terminated.", c) @@ -719,7 +705,7 @@ private class ConsumerControllerImpl[A] private ( } // in case the Request or the SequencedMessage triggering the Request is lost - private def retryRequest(s: State[A]): State[A] = { + private def retryRequest(s: State[A]): State[A] = if (s.producerController == context.system.deadLetters) { s } else { @@ -732,7 +718,6 @@ private class ConsumerControllerImpl[A] private ( s.producerController ! Request(s.confirmedSeqNr, newRequestedSeqNr, resendLost, viaTimeout = true) s.copy(requestedSeqNr = newRequestedSeqNr) } - } private def postStop(s: State[A]): Behavior[InternalCommand] = { // best effort to Ack latest confirmed when stopping diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/internal/ProducerControllerImpl.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/internal/ProducerControllerImpl.scala index aab18c1e1aa..0f04b305b68 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/internal/ProducerControllerImpl.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/internal/ProducerControllerImpl.scala @@ -143,7 +143,7 @@ object ProducerControllerImpl { def apply[A: ClassTag]( producerId: String, durableQueueBehavior: Option[Behavior[DurableProducerQueue.Command[A]]], - settings: ProducerController.Settings): Behavior[Command[A]] = { + settings: ProducerController.Settings): Behavior[Command[A]] = Behaviors .setup[InternalCommand] { context => ActorFlightRecorder(context.system).delivery.producerCreated(producerId, context.self.path) @@ -167,7 +167,6 @@ object ProducerControllerImpl { } } .narrow - } /** * For custom `send` function. For example used with Sharding where the message must be wrapped in @@ -177,7 +176,7 @@ object ProducerControllerImpl { producerId: String, durableQueueBehavior: Option[Behavior[DurableProducerQueue.Command[A]]], settings: ProducerController.Settings, - send: ConsumerController.SequencedMessage[A] => Unit): Behavior[Command[A]] = { + send: ConsumerController.SequencedMessage[A] => Unit): Behavior[Command[A]] = Behaviors .setup[InternalCommand] { context => ActorFlightRecorder(context.system).delivery.producerCreated(producerId, context.self.path) @@ -201,20 +200,17 @@ object ProducerControllerImpl { } } .narrow - } private def askLoadState[A]( context: ActorContext[InternalCommand], durableQueueBehavior: Option[Behavior[DurableProducerQueue.Command[A]]], - settings: ProducerController.Settings): Option[ActorRef[DurableProducerQueue.Command[A]]] = { - + settings: ProducerController.Settings): Option[ActorRef[DurableProducerQueue.Command[A]]] = durableQueueBehavior.map { b => val ref = context.spawn(b, "durable", DispatcherSelector.sameAsParent()) context.watchWith(ref, DurableQueueTerminated) askLoadState(context, Some(ref), settings, attempt = 1) ref } - } private def askLoadState[A]( context: ActorContext[InternalCommand], @@ -232,9 +228,8 @@ object ProducerControllerImpl { } } - private def createInitialState[A](hasDurableQueue: Boolean) = { + private def createInitialState[A](hasDurableQueue: Boolean) = if (hasDurableQueue) None else Some(DurableProducerQueue.State.empty[A]) - } private def createState[A]( self: ActorRef[InternalCommand], @@ -269,7 +264,7 @@ object ProducerControllerImpl { initialState: Option[DurableProducerQueue.State[A]])( thenBecomeActive: ( ActorRef[RequestNext[A]], ActorRef[ConsumerController.Command[A]], - DurableProducerQueue.State[A]) => Behavior[InternalCommand]): Behavior[InternalCommand] = { + DurableProducerQueue.State[A]) => Behavior[InternalCommand]): Behavior[InternalCommand] = Behaviors.receiveMessagePartial[InternalCommand] { case RegisterConsumer(c: ActorRef[ConsumerController.Command[A]] @unchecked) => (producer, initialState) match { @@ -313,14 +308,12 @@ object ProducerControllerImpl { case DurableQueueTerminated => throw new IllegalStateException("DurableQueue was unexpectedly terminated.") } - } private def becomeActive[A: ClassTag]( producerId: String, durableQueue: Option[ActorRef[DurableProducerQueue.Command[A]]], settings: ProducerController.Settings, - state: State[A]): Behavior[InternalCommand] = { - + state: State[A]): Behavior[InternalCommand] = Behaviors.setup { context => val flightRecorder = ActorFlightRecorder(context.system).delivery flightRecorder.producerStarted(producerId, context.self.path) @@ -340,12 +333,10 @@ object ProducerControllerImpl { .active(state.copy(requested = requested)) } } - } - def enforceLocalProducer(ref: ActorRef[_]): Unit = { + def enforceLocalProducer(ref: ActorRef[_]): Unit = if (ref.path.address.hasGlobalScope) throw new IllegalArgumentException(s"Consumer [$ref] should be local.") - } def createChunks[A](m: A, chunkSize: Int, serialization: Serialization): immutable.Seq[ChunkedMessage] = { val mAnyRef = m.asInstanceOf[AnyRef] @@ -445,19 +436,17 @@ private class ProducerControllerImpl[A: ClassTag]( storeMessageSentInProgress = 0)) } - def checkOnMsgRequestedState(): Unit = { + def checkOnMsgRequestedState(): Unit = if (!s.requested || s.currentSeqNr > s.requestedSeqNr) { throw new IllegalStateException( s"Unexpected Msg when no demand, requested ${s.requested}, " + s"requestedSeqNr ${s.requestedSeqNr}, currentSeqNr ${s.currentSeqNr}") } - } - def checkReceiveMessageRemainingChunksState(): Unit = { + def checkReceiveMessageRemainingChunksState(): Unit = if (s.remainingChunks.nonEmpty) throw new IllegalStateException( s"Received unexpected message before sending remaining [${s.remainingChunks.size}] chunks.") - } def receiveRequest( newConfirmedSeqNr: SeqNr, @@ -558,7 +547,7 @@ private class ProducerControllerImpl[A: ClassTag]( s.copy(confirmedSeqNr = newMaxConfirmedSeqNr, replyAfterStore = newReplyAfterStore, unconfirmed = newUnconfirmed) } - def receiveStoreMessageSentCompleted(seqNr: SeqNr): Behavior[InternalCommand] = { + def receiveStoreMessageSentCompleted(seqNr: SeqNr): Behavior[InternalCommand] = if (seqNr == s.storeMessageSentInProgress) { if (seqNr != s.currentSeqNr) throw new IllegalStateException(s"currentSeqNr [${s.currentSeqNr}] not matching stored seqNr [$seqNr]") @@ -582,9 +571,8 @@ private class ProducerControllerImpl[A: ClassTag]( s.storeMessageSentInProgress) Behaviors.same } - } - def receiveStoreMessageSentFailed(f: StoreMessageSentFailed[A]): Behavior[InternalCommand] = { + def receiveStoreMessageSentFailed(f: StoreMessageSentFailed[A]): Behavior[InternalCommand] = if (f.messageSent.seqNr == s.storeMessageSentInProgress) { if (f.attempt >= settings.durableQueueRetryAttempts) { val errorMessage = @@ -639,7 +627,6 @@ private class ProducerControllerImpl[A: ClassTag]( } else { Behaviors.same } - } def receiveResend(fromSeqNr: SeqNr): Behavior[InternalCommand] = { flightRecorder.producerReceivedResend(producerId, fromSeqNr) @@ -651,7 +638,7 @@ private class ProducerControllerImpl[A: ClassTag]( Behaviors.same } - def resendUnconfirmed(newUnconfirmed: Vector[SequencedMessage[A]]): Unit = { + def resendUnconfirmed(newUnconfirmed: Vector[SequencedMessage[A]]): Unit = if (newUnconfirmed.nonEmpty) { val fromSeqNr = newUnconfirmed.head.seqNr val toSeqNr = newUnconfirmed.last.seqNr @@ -659,7 +646,6 @@ private class ProducerControllerImpl[A: ClassTag]( context.log.debug("Resending [{} - {}].", fromSeqNr, toSeqNr) newUnconfirmed.foreach(s.send) } - } def receiveResendFirstUnconfirmed(): Behavior[InternalCommand] = { if (s.unconfirmed.nonEmpty) { @@ -710,7 +696,7 @@ private class ProducerControllerImpl[A: ClassTag]( active(s.copy(firstSeqNr = newFirstSeqNr, send = newSend)) } - def receiveSendChunk(): Behavior[InternalCommand] = { + def receiveSendChunk(): Behavior[InternalCommand] = if (s.remainingChunks.nonEmpty && s.remainingChunks.head.seqNr <= s.requestedSeqNr && s .storeMessageSentInProgress == 0) { if (traceEnabled) @@ -728,7 +714,6 @@ private class ProducerControllerImpl[A: ClassTag]( } else { Behaviors.same } - } def chunk(m: A, ack: Boolean): immutable.Seq[SequencedMessage[A]] = { val chunkSize = settings.chunkLargeMessagesBytes @@ -842,12 +827,11 @@ private class ProducerControllerImpl[A: ClassTag]( } } - private def storeMessageSent(messageSent: MessageSent[A], attempt: Int): Unit = { + private def storeMessageSent(messageSent: MessageSent[A], attempt: Int): Unit = context.ask[StoreMessageSent[A], StoreMessageSentAck]( durableQueue.get, askReplyTo => StoreMessageSent(messageSent, askReplyTo)) { case Success(_) => StoreMessageSentCompleted(messageSent) case Failure(_) => StoreMessageSentFailed(messageSent, attempt) // timeout } - } } diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/internal/WorkPullingProducerControllerImpl.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/internal/WorkPullingProducerControllerImpl.scala index 9b2c05034bd..cb3a7f73ef3 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/internal/WorkPullingProducerControllerImpl.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/delivery/internal/WorkPullingProducerControllerImpl.scala @@ -124,7 +124,7 @@ import pekko.util.Timeout producerId: String, workerServiceKey: ServiceKey[ConsumerController.Command[A]], durableQueueBehavior: Option[Behavior[DurableProducerQueue.Command[A]]], - settings: WorkPullingProducerController.Settings): Behavior[Command[A]] = { + settings: WorkPullingProducerController.Settings): Behavior[Command[A]] = Behaviors .withStash[InternalCommand](settings.bufferSize) { stashBuffer => Behaviors.setup[InternalCommand] { context => @@ -148,11 +148,9 @@ import pekko.util.Timeout } } .narrow - } - private def createInitialState[A](hasDurableQueue: Boolean) = { + private def createInitialState[A](hasDurableQueue: Boolean) = if (hasDurableQueue) None else Some(DurableProducerQueue.State.empty[A]) - } private def waitingForStart[A: ClassTag]( producerId: String, @@ -231,23 +229,20 @@ import pekko.util.Timeout } } - private def checkStashFull[A](stashBuffer: StashBuffer[InternalCommand]): Unit = { + private def checkStashFull[A](stashBuffer: StashBuffer[InternalCommand]): Unit = if (stashBuffer.isFull) throw new IllegalArgumentException(s"Buffer is full, size [${stashBuffer.size}].") - } private def askLoadState[A]( context: ActorContext[InternalCommand], durableQueueBehavior: Option[Behavior[DurableProducerQueue.Command[A]]], - settings: WorkPullingProducerController.Settings): Option[ActorRef[DurableProducerQueue.Command[A]]] = { - + settings: WorkPullingProducerController.Settings): Option[ActorRef[DurableProducerQueue.Command[A]]] = durableQueueBehavior.map { b => val ref = context.spawn(b, "durable", DispatcherSelector.sameAsParent()) context.watchWith(ref, DurableQueueTerminated) askLoadState(context, Some(ref), settings, attempt = 1) ref } - } private def askLoadState[A]( context: ActorContext[InternalCommand], @@ -409,7 +404,7 @@ private class WorkPullingProducerControllerImpl[A: ClassTag]( } } - def onMessageBeforeDurableQueue(msg: A, replyTo: Option[ActorRef[Done]]): Behavior[InternalCommand] = { + def onMessageBeforeDurableQueue(msg: A, replyTo: Option[ActorRef[Done]]): Behavior[InternalCommand] = selectWorker() match { case Some((outKey, out)) => storeMessageSent( @@ -438,7 +433,6 @@ private class WorkPullingProducerControllerImpl[A: ClassTag]( stashBuffer.stash(Msg(msg, wasStashed = false, replyTo)) active(s) } - } def onResendDurableMsg(resend: ResendDurableMsg[A]): Behavior[InternalCommand] = { require(durableQueue.isDefined, "Unexpected ResendDurableMsg when DurableQueue not defined.") @@ -487,7 +481,7 @@ private class WorkPullingProducerControllerImpl[A: ClassTag]( active(newState.copy(replyAfterStore = newState.replyAfterStore - seqNr, handOver = newState.handOver - seqNr)) } - def receiveAck(ack: Ack): Behavior[InternalCommand] = { + def receiveAck(ack: Ack): Behavior[InternalCommand] = s.out.get(ack.outKey) match { case Some(outState) => val newUnconfirmed = onAck(outState, ack.confirmedSeqNr) @@ -496,7 +490,6 @@ private class WorkPullingProducerControllerImpl[A: ClassTag]( // obsolete Next, ConsumerController already deregistered Behaviors.unhandled } - } def onAck(outState: OutState[A], confirmedSeqNr: OutSeqNr): Vector[Unconfirmed[A]] = { val (confirmed, newUnconfirmed) = outState.unconfirmed.partition { @@ -675,7 +668,7 @@ private class WorkPullingProducerControllerImpl[A: ClassTag]( } } - private def receiveStoreMessageSentFailed(f: StoreMessageSentFailed[A]): Behavior[InternalCommand] = { + private def receiveStoreMessageSentFailed(f: StoreMessageSentFailed[A]): Behavior[InternalCommand] = if (f.attempt >= producerControllerSettings.durableQueueRetryAttempts) { val errorMessage = s"StoreMessageSentFailed seqNr [${f.messageSent.seqNr}] failed after [${f.attempt}] attempts, giving up." @@ -687,7 +680,6 @@ private class WorkPullingProducerControllerImpl[A: ClassTag]( storeMessageSent(f.messageSent, attempt = f.attempt + 1) Behaviors.same } - } private def storeMessageSent(messageSent: MessageSent[A], attempt: Int): Unit = { implicit val askTimout: Timeout = durableQueueAskTimeout diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/ActorContextImpl.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/ActorContextImpl.scala index 6d6864246a4..152efeea4f2 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/ActorContextImpl.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/ActorContextImpl.scala @@ -125,10 +125,9 @@ import scala.util.Success override private[pekko] def hasTimer: Boolean = _timer.isDefined - override private[pekko] def cancelAllTimers(): Unit = { + override private[pekko] def cancelAllTimers(): Unit = if (hasTimer) timer.cancelAll() - } override def asJava: javadsl.ActorContext[T] = this @@ -157,7 +156,7 @@ import scala.util.Success override def getSystem: pekko.actor.typed.ActorSystem[Void] = system.asInstanceOf[ActorSystem[Void]] - private def loggingContext(): LoggingContext = { + private def loggingContext(): LoggingContext = // lazy init of logging setup _logging match { case OptionVal.Some(l) => l @@ -168,7 +167,6 @@ import scala.util.Success _logging = OptionVal.Some(l) l } - } override def log: Logger = { checkCurrentActorThread() @@ -190,7 +188,7 @@ import scala.util.Success def hasCustomLoggerName: Boolean = loggingContext().hasCustomName // MDC is cleared (if used) from aroundReceive in ActorAdapter after processing each message - override private[pekko] def clearMdc(): Unit = { + override private[pekko] def clearMdc(): Unit = // avoid access to MDC ThreadLocal if not needed, see details in LoggingContext _logging match { case OptionVal.Some(ctx) if ctx.mdcUsed => @@ -198,7 +196,6 @@ import scala.util.Success ctx.mdcUsed = false case _ => } - } override def setReceiveTimeout(duration: java.time.Duration, msg: T): Unit = setReceiveTimeout(duration.asScala, msg) @@ -276,20 +273,18 @@ import scala.util.Success } // Scala API impl - def pipeToSelf[Value](future: Future[Value])(mapResult: Try[Value] => T): Unit = { + def pipeToSelf[Value](future: Future[Value])(mapResult: Try[Value] => T): Unit = future.onComplete(value => self.unsafeUpcast ! AdaptMessage(value, mapResult))(ExecutionContexts.parasitic) - } // Java API impl def pipeToSelf[Value]( future: CompletionStage[Value], - applyToResult: pekko.japi.function.Function2[Value, Throwable, T]): Unit = { + applyToResult: pekko.japi.function.Function2[Value, Throwable, T]): Unit = future.handle[Unit] { (value, ex) => if (ex != null) self.unsafeUpcast ! AdaptMessage(ex, applyToResult.apply(null.asInstanceOf[Value], _: Throwable)) else self.unsafeUpcast ! AdaptMessage(value, applyToResult.apply(_: Value, null)) } - } private[pekko] override def spawnMessageAdapter[U](f: U => T, name: String): ActorRef[U] = internalSpawnMessageAdapter(f, name) @@ -338,7 +333,7 @@ import scala.util.Success /** * INTERNAL API */ - @InternalApi private[pekko] def setCurrentActorThread(): Unit = { + @InternalApi private[pekko] def setCurrentActorThread(): Unit = _currentActorThread match { case OptionVal.Some(t) => throw new IllegalStateException( @@ -347,14 +342,12 @@ import scala.util.Success case _ => _currentActorThread = OptionVal.Some(Thread.currentThread()) } - } /** * INTERNAL API */ - @InternalApi private[pekko] def clearCurrentActorThread(): Unit = { + @InternalApi private[pekko] def clearCurrentActorThread(): Unit = _currentActorThread = OptionVal.None - } /** * INTERNAL API diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/BehaviorImpl.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/BehaviorImpl.scala index 20485d885f2..6122bc5b144 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/BehaviorImpl.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/BehaviorImpl.scala @@ -105,12 +105,11 @@ private[pekko] object BehaviorTags { private[pekko] final class StoppedBehavior[T](val postStop: OptionVal[TypedActorContext[T] => Unit]) extends Behavior[T](BehaviorTags.StoppedBehavior) { - def onPostStop(ctx: TypedActorContext[T]): Unit = { + def onPostStop(ctx: TypedActorContext[T]): Unit = postStop match { case OptionVal.Some(callback) => callback(ctx) case _ => } - } override def toString = "Stopped" + { postStop match { @@ -138,11 +137,10 @@ private[pekko] object BehaviorTags { BehaviorImpl.unhandledSignal.asInstanceOf[PartialFunction[(SAC[T], Signal), Behavior[T]]]) extends ExtensibleBehavior[T] { - override def receiveSignal(ctx: AC[T], msg: Signal): Behavior[T] = { + override def receiveSignal(ctx: AC[T], msg: Signal): Behavior[T] = onSignal.applyOrElse( (ctx.asScala, msg), BehaviorImpl.unhandledSignal.asInstanceOf[PartialFunction[(SAC[T], Signal), Behavior[T]]]) - } override def receive(ctx: AC[T], msg: T) = onMessage(ctx.asScala, msg) @@ -162,11 +160,10 @@ private[pekko] object BehaviorTags { override def receive(ctx: AC[T], msg: T) = onMessage(msg) - override def receiveSignal(ctx: AC[T], msg: Signal): Behavior[T] = { + override def receiveSignal(ctx: AC[T], msg: Signal): Behavior[T] = onSignal.applyOrElse( (ctx.asScala, msg), BehaviorImpl.unhandledSignal.asInstanceOf[PartialFunction[(SAC[T], Signal), Behavior[T]]]) - } override def toString = s"ReceiveMessage(${LineNumbers(onMessage)})" } diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/ExtensionsImpl.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/ExtensionsImpl.scala index 0c0d5d5cdfc..8024279f6c9 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/ExtensionsImpl.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/ExtensionsImpl.scala @@ -45,8 +45,7 @@ private[pekko] trait ExtensionsImpl extends Extensions { self: ActorSystem[_] wi /* * @param throwOnLoadFail Throw exception when an extension fails to load (needed for backwards compatibility) */ - private def loadExtensionsFor(key: String, throwOnLoadFail: Boolean): Unit = { - + private def loadExtensionsFor(key: String, throwOnLoadFail: Boolean): Unit = settings.config.getStringList(key).asScala.foreach { extensionIdFQCN => // it is either a Scala object or it is a Java class with a static singleton accessor val idTry = dynamicAccess.getObjectFor[AnyRef](extensionIdFQCN).recoverWith { @@ -64,7 +63,6 @@ private[pekko] trait ExtensionsImpl extends Extensions { self: ActorSystem[_] wi else throw new RuntimeException(s"While trying to load extension [$extensionIdFQCN]", problem) } } - } private def idFromJavaSingletonAccessor(extensionIdFQCN: String): Try[ExtensionId[Extension]] = dynamicAccess.getClassFor[ExtensionId[Extension]](extensionIdFQCN).flatMap[ExtensionId[Extension]] { @@ -112,10 +110,9 @@ private[pekko] trait ExtensionsImpl extends Extensions { self: ActorSystem[_] wi // In case shit hits the fan, remove the inProcess signal and escalate to caller extensions.replace(ext, inProcessOfRegistration, t) throw t - } finally { + } finally // Always notify listeners of the inProcess signal inProcessOfRegistration.countDown() - } case _ => // Someone else is in process of registering an extension for this Extension, retry registerExtension(ext) diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/InterceptorImpl.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/InterceptorImpl.scala index 0763b224873..0d673c07a6b 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/InterceptorImpl.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/InterceptorImpl.scala @@ -34,12 +34,11 @@ import pekko.util.LineNumbers @InternalApi private[pekko] object InterceptorImpl { - def apply[O, I](interceptor: () => BehaviorInterceptor[O, I], nestedBehavior: Behavior[I]): Behavior[O] = { + def apply[O, I](interceptor: () => BehaviorInterceptor[O, I], nestedBehavior: Behavior[I]): Behavior[O] = BehaviorImpl.DeferredBehavior[O] { ctx => val interceptorBehavior = new InterceptorImpl[O, I](interceptor(), nestedBehavior) interceptorBehavior.preStart(ctx) } - } } /** @@ -56,9 +55,8 @@ private[pekko] final class InterceptorImpl[O, I]( import BehaviorInterceptor._ private val preStartTarget: PreStartTarget[I] = new PreStartTarget[I] { - override def start(ctx: TypedActorContext[_]): Behavior[I] = { + override def start(ctx: TypedActorContext[_]): Behavior[I] = Behavior.start[I](nestedBehavior, ctx.asInstanceOf[TypedActorContext[I]]) - } override def toString: String = s"PreStartTarget($nestedBehavior)" } @@ -152,9 +150,8 @@ private[pekko] final case class MonitorInterceptor[T: ClassTag](actorRef: ActorR * INTERNAL API */ @InternalApi private[pekko] object LogMessagesInterceptor { - def apply[T](opts: LogOptions): BehaviorInterceptor[T, T] = { + def apply[T](opts: LogOptions): BehaviorInterceptor[T, T] = new LogMessagesInterceptor(opts).asInstanceOf[BehaviorInterceptor[T, T]] - } private val LogMessageTemplate = "actor [{}] received message: {}" private val LogSignalTemplate = "actor [{}] received signal: {}" @@ -183,7 +180,7 @@ private[pekko] final class LogMessagesInterceptor(val opts: LogOptions) extends target(ctx, signal) } - private def log(template: String, messageOrSignal: Any, context: TypedActorContext[Any]): Unit = { + private def log(template: String, messageOrSignal: Any, context: TypedActorContext[Any]): Unit = if (opts.enabled) { val selfPath = context.asScala.self.path opts.level match { @@ -194,7 +191,6 @@ private[pekko] final class LogMessagesInterceptor(val opts: LogOptions) extends case Level.TRACE => logger.trace(template, selfPath, messageOrSignal) } } - } // only once in the same behavior stack override def isSame(other: BehaviorInterceptor[Any, Any]): Boolean = other match { @@ -235,12 +231,11 @@ private[pekko] final case class TransformMessagesInterceptor[O: ClassTag, I](mat case _ => false } - def aroundReceive(ctx: TypedActorContext[O], msg: O, target: ReceiveTarget[I]): Behavior[I] = { + def aroundReceive(ctx: TypedActorContext[O], msg: O, target: ReceiveTarget[I]): Behavior[I] = matcher.applyOrElse(msg, any2NotMatchIndicator) match { case result if _notMatchIndicator == result => Behaviors.unhandled case transformed => target(ctx, transformed) } - } override def toString: String = s"TransformMessages(${LineNumbers(matcher)})" } diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/LoggerClass.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/LoggerClass.scala index 6fd02e35604..cc945e34a2e 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/LoggerClass.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/LoggerClass.scala @@ -35,7 +35,7 @@ private[pekko] object LoggerClass { /** * Try to extract a logger class from the call stack, if not possible the provided default is used */ - def detectLoggerClassFromStack(default: Class[_], additionalPrefixesToSkip: List[String] = Nil): Class[_] = { + def detectLoggerClassFromStack(default: Class[_], additionalPrefixesToSkip: List[String] = Nil): Class[_] = // TODO use stack walker API when we no longer need to support Java 8 try { def skip(name: String): Boolean = { @@ -62,6 +62,5 @@ private[pekko] object LoggerClass { } catch { case NonFatal(_) => default } - } } diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/PoisonPill.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/PoisonPill.scala index 66a74f76add..4fec8492e04 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/PoisonPill.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/PoisonPill.scala @@ -49,7 +49,7 @@ import pekko.annotation.InternalApi override def aroundSignal( ctx: TypedActorContext[M], signal: Signal, - target: BehaviorInterceptor.SignalTarget[M]): Behavior[M] = { + target: BehaviorInterceptor.SignalTarget[M]): Behavior[M] = signal match { case p: PoisonPill => val next = target(ctx, p) @@ -57,7 +57,6 @@ import pekko.annotation.InternalApi else next case _ => target(ctx, signal) } - } override def isSame(other: BehaviorInterceptor[Any, Any]): Boolean = // only one interceptor per behavior stack is needed diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/StashBufferImpl.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/StashBufferImpl.scala index 2b3ff8b9e2d..5fdb3f84f5c 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/StashBufferImpl.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/StashBufferImpl.scala @@ -96,9 +96,8 @@ import java.util.function.Predicate } @InternalStableApi - private def createNode(message: T, @unused ctx: scaladsl.ActorContext[T]): Node[T] = { + private def createNode(message: T, @unused ctx: scaladsl.ActorContext[T]): Node[T] = new Node(null, message) - } @InternalStableApi private def dropHeadForUnstash(): Node[T] = { @@ -116,9 +115,8 @@ import java.util.function.Predicate behavior: Behavior[T], ctx: TypedActorContext[T], wrappedMessage: T, - @unused node: Node[T]): Behavior[T] = { + @unused node: Node[T]): Behavior[T] = Behavior.interpretMessage(behavior, ctx, wrappedMessage) - } private def rawHead: Node[T] = if (nonEmpty) _first @@ -159,7 +157,7 @@ import java.util.function.Predicate behav } - override def unstash(behavior: Behavior[T], numberOfMessages: Int, wrap: T => T): Behavior[T] = { + override def unstash(behavior: Behavior[T], numberOfMessages: Int, wrap: T => T): Behavior[T] = if (isEmpty) behavior // optimization else { @@ -177,12 +175,10 @@ import java.util.function.Predicate } }.take(math.min(numberOfMessages, size)) interpretUnstashedMessages(behavior, ctx, iter, wrap) - } finally { + } finally if (!unstashAlreadyInProgress) currentBehaviorWhenUnstashInProgress = OptionVal.None - } } - } private def interpretUnstashedMessages( behavior: Behavior[T], @@ -197,12 +193,12 @@ import java.util.function.Predicate val node = messages.next() val message = wrap(node.message) val interpretResult = - try { + try message match { case sig: Signal => Behavior.interpretSignal(b2, ctx, sig) case msg => interpretUnstashedMessage(b2, ctx, msg, node) } - } catch { + catch { case NonFatal(e) => throw UnstashException(e, b2) } diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/Supervision.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/Supervision.scala index bbc4366cb26..31dc72bcebc 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/Supervision.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/Supervision.scala @@ -75,29 +75,26 @@ private abstract class AbstractSupervisor[I, Thr <: Throwable](strategy: Supervi protected def isInstanceOfTheThrowableClass(t: Throwable): Boolean = throwableClass.isAssignableFrom(UnstashException.unwrap(t).getClass) - override def isSame(other: BehaviorInterceptor[Any, Any]): Boolean = { + override def isSame(other: BehaviorInterceptor[Any, Any]): Boolean = other match { case as: AbstractSupervisor[_, _] if throwableClass == as.throwableClass => true case _ => false } - } - override def aroundStart(ctx: TypedActorContext[Any], target: PreStartTarget[I]): Behavior[I] = { - try { + override def aroundStart(ctx: TypedActorContext[Any], target: PreStartTarget[I]): Behavior[I] = + try target.start(ctx) - } catch handleExceptionOnStart(ctx, target) - } + catch handleExceptionOnStart(ctx, target) - override def aroundSignal(ctx: TypedActorContext[Any], signal: Signal, target: SignalTarget[I]): Behavior[I] = { - try { + override def aroundSignal(ctx: TypedActorContext[Any], signal: Signal, target: SignalTarget[I]): Behavior[I] = + try target(ctx, signal) - } catch handleSignalException(ctx, target) - } + catch handleSignalException(ctx, target) def log(ctx: TypedActorContext[_], t: Throwable): Unit = log(ctx, t, errorCount = -1) - def log(ctx: TypedActorContext[_], t: Throwable, errorCount: Int): Unit = { + def log(ctx: TypedActorContext[_], t: Throwable, errorCount: Int): Unit = if (strategy.loggingEnabled) { val unwrapped = UnstashException.unwrap(t) val errorCountStr = if (errorCount >= 0) s" [$errorCount]" else "" @@ -115,7 +112,6 @@ private abstract class AbstractSupervisor[I, Thr <: Throwable](strategy: Supervi case Level.TRACE => logger.trace(logMessage, unwrapped) } } - } def dropped(ctx: TypedActorContext[_], signalOrMessage: Any): Unit = { import pekko.actor.typed.scaladsl.adapter._ @@ -136,11 +132,10 @@ private abstract class AbstractSupervisor[I, Thr <: Throwable](strategy: Supervi private abstract class SimpleSupervisor[T, Thr <: Throwable: ClassTag](ss: SupervisorStrategy) extends AbstractSupervisor[T, Thr](ss) { - override def aroundReceive(ctx: TypedActorContext[Any], msg: Any, target: ReceiveTarget[T]): Behavior[T] = { - try { + override def aroundReceive(ctx: TypedActorContext[Any], msg: Any, target: ReceiveTarget[T]): Behavior[T] = + try target(ctx, msg.asInstanceOf[T]) - } catch handleReceiveException(ctx, target) - } + catch handleReceiveException(ctx, target) protected def handleException(@unused ctx: TypedActorContext[Any]): Catcher[Behavior[T]] = { case NonFatal(t) if isInstanceOfTheThrowableClass(t) => @@ -217,7 +212,7 @@ private class RestartSupervisor[T, Thr <: Throwable: ClassTag](initial: Behavior case _ => true } - override def aroundSignal(ctx: TypedActorContext[Any], signal: Signal, target: SignalTarget[T]): Behavior[T] = { + override def aroundSignal(ctx: TypedActorContext[Any], signal: Signal, target: SignalTarget[T]): Behavior[T] = signal match { case ScheduledRestart(owner) => if (owner eq this) { @@ -273,7 +268,6 @@ private class RestartSupervisor[T, Thr <: Throwable: ClassTag](initial: Behavior super.aroundSignal(ctx, signal, target) } } - } override def aroundReceive(ctx: TypedActorContext[Any], msg: Any, target: ReceiveTarget[T]): Behavior[T] = { val m = msg.asInstanceOf[T] @@ -285,9 +279,9 @@ private class RestartSupervisor[T, Thr <: Throwable: ClassTag](initial: Behavior stashBuffer.stash(m) Behaviors.same case _ => - try { + try target(ctx, m) - } catch handleReceiveException(ctx, target) + catch handleReceiveException(ctx, target) } } @@ -312,22 +306,20 @@ private class RestartSupervisor[T, Thr <: Throwable: ClassTag](initial: Behavior override protected def handleSignalException( ctx: TypedActorContext[Any], - target: SignalTarget[T]): Catcher[Behavior[T]] = { + target: SignalTarget[T]): Catcher[Behavior[T]] = handleException(ctx, signalRestart = { case e: UnstashException[Any] @unchecked => Behavior.interpretSignal(e.behavior, ctx, PreRestart) case _ => target(ctx, PreRestart) }) - } override protected def handleReceiveException( ctx: TypedActorContext[Any], - target: ReceiveTarget[T]): Catcher[Behavior[T]] = { + target: ReceiveTarget[T]): Catcher[Behavior[T]] = handleException(ctx, signalRestart = { case e: UnstashException[Any] @unchecked => Behavior.interpretSignal(e.behavior, ctx, PreRestart) case _ => target.signalRestart(ctx) }) - } private def handleException(ctx: TypedActorContext[Any], signalRestart: Throwable => Unit): Catcher[Behavior[T]] = { case NonFatal(t) if isInstanceOfTheThrowableClass(t) => @@ -418,16 +410,15 @@ private class RestartSupervisor[T, Thr <: Throwable: ClassTag](initial: Behavior }) } - private def stopChildren(ctx: TypedActorContext[_], children: Set[ActorRef[Nothing]]): Unit = { + private def stopChildren(ctx: TypedActorContext[_], children: Set[ActorRef[Nothing]]): Unit = children.foreach { child => // Unwatch in case the actor being restarted used watchWith to watch the child. ctx.asScala.unwatch(child) ctx.asScala.watch(child) ctx.asScala.stop(child) } - } - private def updateRestartCount(): Unit = { + private def updateRestartCount(): Unit = strategy match { case restart: Restart => val timeLeft = deadlineHasTimeLeft @@ -438,6 +429,5 @@ private class RestartSupervisor[T, Thr <: Throwable: ClassTag](initial: Behavior case _: Backoff => restartCount += 1 } - } } diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/SystemMessage.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/SystemMessage.scala index 6fe01639bf1..149ed7ba0dc 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/SystemMessage.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/SystemMessage.scala @@ -31,14 +31,13 @@ private[typed] object SystemMessageList { if (head eq null) acc else sizeInner(head.next, acc + 1) @tailrec - private[internal] def reverseInner(head: SystemMessage, acc: SystemMessage): SystemMessage = { + private[internal] def reverseInner(head: SystemMessage, acc: SystemMessage): SystemMessage = if (head eq null) acc else { val next = head.next head.next = acc reverseInner(next, head) } - } } /** diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/TimerSchedulerImpl.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/TimerSchedulerImpl.scala index dc25fdfdec4..7ffc812c9f7 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/TimerSchedulerImpl.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/TimerSchedulerImpl.scala @@ -35,9 +35,8 @@ import scala.concurrent.duration.FiniteDuration override def toString = s"TimerMsg(key=$key, generation=$generation, owner=$owner)" } - def withTimers[T](factory: TimerSchedulerCrossDslSupport[T] => Behavior[T]): Behavior[T] = { + def withTimers[T](factory: TimerSchedulerCrossDslSupport[T] => Behavior[T]): Behavior[T] = scaladsl.Behaviors.setup[T](wrapWithTimers(factory)) - } def wrapWithTimers[T](factory: TimerSchedulerCrossDslSupport[T] => Behavior[T])(ctx: ActorContext[T]): Behavior[T] = ctx match { @@ -78,10 +77,9 @@ import scala.concurrent.duration.FiniteDuration override final def startTimerAtFixedRate(key: Any, msg: T, initialDelay: Duration, interval: Duration): Unit = startTimerAtFixedRate(key, msg, initialDelay.asScala, interval.asScala) - override final def startPeriodicTimer(key: Any, msg: T, interval: Duration): Unit = { + override final def startPeriodicTimer(key: Any, msg: T, interval: Duration): Unit = // this follows the deprecation note in the super class startTimerWithFixedDelay(key, msg, interval.asScala) - } override final def startSingleTimer(key: Any, msg: T, delay: Duration): Unit = startSingleTimer(key, msg, delay.asScala) @@ -147,12 +145,11 @@ import scala.concurrent.duration.FiniteDuration override def isTimerActive(key: Any): Boolean = timers.contains(key) - override def cancel(key: Any): Unit = { + override def cancel(key: Any): Unit = timers.get(key) match { case None => // already removed/canceled case Some(t) => cancelTimer(t) } - } private def cancelTimer(timer: Timer[T]): Unit = { timer.task.cancel() @@ -166,7 +163,7 @@ import scala.concurrent.duration.FiniteDuration timers = Map.empty } - def interceptTimerMsg(log: Logger, timerMsg: TimerMsg): OptionVal[T] = { + def interceptTimerMsg(log: Logger, timerMsg: TimerMsg): OptionVal[T] = timers.get(timerMsg.key) match { case None => // it was from canceled timer that was already enqueued in mailbox @@ -193,5 +190,4 @@ import scala.concurrent.duration.FiniteDuration OptionVal.none // message should be ignored } } - } } diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/WithMdcBehaviorInterceptor.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/WithMdcBehaviorInterceptor.scala index cf7b371e243..83d030067d8 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/WithMdcBehaviorInterceptor.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/WithMdcBehaviorInterceptor.scala @@ -30,9 +30,8 @@ import pekko.annotation.InternalApi def apply[T: ClassTag]( staticMdc: Map[String, String], mdcForMessage: T => Map[String, String], - behavior: Behavior[T]): Behavior[T] = { + behavior: Behavior[T]): Behavior[T] = BehaviorImpl.intercept(() => new WithMdcBehaviorInterceptor[T](staticMdc, mdcForMessage))(behavior) - } } @@ -57,7 +56,7 @@ import pekko.annotation.InternalApi // val withMdc2 = withMdc(Map("second" -> true)) // we'd expect the second one to be used // so we need to look through the stack and eliminate any MCD already existing - def loop(next: Behavior[T]): Behavior[T] = { + def loop(next: Behavior[T]): Behavior[T] = next match { case i: InterceptorImpl[_, T @unchecked] if i.interceptor.isSame(this.asInstanceOf[BehaviorInterceptor[Any, Any]]) => @@ -72,13 +71,11 @@ import pekko.annotation.InternalApi case b => b } - } try { setMdcValues(Map.empty) loop(target.start(ctx)) - } finally { + } finally MDC.clear() - } } // in the normal case, a new withMDC replaces the previous one @@ -87,23 +84,19 @@ import pekko.annotation.InternalApi case _ => false } - override def aroundReceive(ctx: TypedActorContext[T], msg: T, target: ReceiveTarget[T]): Behavior[T] = { + override def aroundReceive(ctx: TypedActorContext[T], msg: T, target: ReceiveTarget[T]): Behavior[T] = try { setMdcValues(mdcForMessage(msg)) target(ctx, msg) - } finally { + } finally MDC.clear() - } - } - override def aroundSignal(ctx: TypedActorContext[T], signal: Signal, target: SignalTarget[T]): Behavior[T] = { + override def aroundSignal(ctx: TypedActorContext[T], signal: Signal, target: SignalTarget[T]): Behavior[T] = try { setMdcValues(Map.empty) target(ctx, signal) - } finally { + } finally MDC.clear() - } - } private def setMdcValues(dynamicMdc: Map[String, String]): Unit = { if (staticMdc.nonEmpty) staticMdc.foreach { diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/adapter/ActorAdapter.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/adapter/ActorAdapter.scala index 9638149134c..883fd5aeb19 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/adapter/ActorAdapter.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/adapter/ActorAdapter.scala @@ -86,7 +86,7 @@ import pekko.util.OptionVal override protected[pekko] def aroundReceive(receive: Receive, msg: Any): Unit = { ctx.setCurrentActorThread() - try { + try // as we know we never become in "normal" typed actors, it is just the current behavior that // changes, we can avoid some overhead with the partial function/behavior stack of untyped entirely // we also know that the receive is total, so we can avoid the orElse part as well. @@ -116,13 +116,13 @@ import pekko.util.OptionVal val t = msg.asInstanceOf[T] handleMessage(t) } - } finally { + finally { ctx.clearCurrentActorThread() ctx.clearMdc() } } - private def handleMessage(msg: T): Unit = { + private def handleMessage(msg: T): Unit = try { val c = ctx if (c.hasTimer) { @@ -141,13 +141,11 @@ import pekko.util.OptionVal next(Behavior.interpretMessage(behavior, c, msg), msg) } } catch handleUnstashException - } - private def handleSignal(sig: Signal): Unit = { - try { + private def handleSignal(sig: Signal): Unit = + try next(Behavior.interpretSignal(behavior, ctx, sig), sig) - } catch handleUnstashException - } + catch handleUnstashException private def handleUnstashException: Catcher[Unit] = { case e: UnstashException[T] @unchecked => @@ -161,7 +159,7 @@ import pekko.util.OptionVal throw ActorInitializationException(actor, message, e.cause) } - private def next(b: Behavior[T], msg: Any): Unit = { + private def next(b: Behavior[T], msg: Any): Unit = (b._tag: @switch) match { case BehaviorTags.UnhandledBehavior => unhandled(msg) @@ -177,10 +175,9 @@ import pekko.util.OptionVal case _ => behavior = Behavior.canonicalize(b, behavior, ctx) } - } private def adaptAndHandle(msg: Any): Unit = { - @tailrec def handle(adapters: List[(Class[_], Any => T)]): Unit = { + @tailrec def handle(adapters: List[(Class[_], Any => T)]): Unit = adapters match { case Nil => // no adapter function registered for message class @@ -191,16 +188,15 @@ import pekko.util.OptionVal } else handle(tail) // recursive } - } handle(ctx.messageAdapters) } private def withSafelyAdapted[U, V](adapt: () => U)(body: U => V): Unit = { var failed = false val adapted: U = - try { + try adapt() - } catch { + catch { case NonFatal(ex) => // pass it on through the signal handler chain giving supervision a chance to deal with it handleSignal(MessageAdaptionFailure(ex)) @@ -260,9 +256,8 @@ import pekko.util.OptionVal else ActorAdapter.classicSupervisorDecider(ex) } - finally { + finally ctx.clearCurrentActorThread() - } } private def recordChildFailure(ex: Throwable): Unit = { @@ -296,7 +291,7 @@ import pekko.util.OptionVal finally ctx.clearCurrentActorThread() } - override def preStart(): Unit = { + override def preStart(): Unit = try { if (Behavior.isAlive(behavior)) { behavior = Behavior.validateAsInitial(Behavior.start(behavior, ctx)) @@ -304,25 +299,22 @@ import pekko.util.OptionVal // either was stopped initially or became stopped on start if (!Behavior.isAlive(behavior)) context.stop(self) } finally ctx.clearMdc() - } - override def preRestart(reason: Throwable, message: Option[Any]): Unit = { + override def preRestart(reason: Throwable, message: Option[Any]): Unit = try { ctx.cancelAllTimers() Behavior.interpretSignal(behavior, ctx, PreRestart) behavior = BehaviorImpl.stopped } finally ctx.clearMdc() - } - override def postRestart(reason: Throwable): Unit = { + override def postRestart(reason: Throwable): Unit = try { ctx.cancelAllTimers() behavior = Behavior.validateAsInitial(Behavior.start(behavior, ctx)) if (!Behavior.isAlive(behavior)) context.stop(self) } finally ctx.clearMdc() - } - override def postStop(): Unit = { + override def postStop(): Unit = try { ctx.cancelAllTimers() behavior match { @@ -332,7 +324,6 @@ import pekko.util.OptionVal } behavior = BehaviorImpl.stopped } finally ctx.clearMdc() - } } diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/adapter/ActorRefFactoryAdapter.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/adapter/ActorRefFactoryAdapter.scala index 1d47ef10f8c..b3aa489b8a6 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/adapter/ActorRefFactoryAdapter.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/adapter/ActorRefFactoryAdapter.scala @@ -29,29 +29,27 @@ import pekko.util.ErrorMessages context: pekko.actor.ActorRefFactory, behavior: Behavior[T], props: Props, - rethrowTypedFailure: Boolean): ActorRef[T] = { - try { + rethrowTypedFailure: Boolean): ActorRef[T] = + try ActorRefAdapter(context.actorOf(internal.adapter.PropsAdapter(() => behavior, props, rethrowTypedFailure))) - } catch { + catch { case ex: ConfigurationException if ex.getMessage.startsWith(ErrorMessages.RemoteDeploymentConfigErrorPrefix) => throw new ConfigurationException(remoteDeploymentNotAllowed, ex) } - } def spawn[T]( actorRefFactory: pekko.actor.ActorRefFactory, behavior: Behavior[T], name: String, props: Props, - rethrowTypedFailure: Boolean): ActorRef[T] = { - try { + rethrowTypedFailure: Boolean): ActorRef[T] = + try ActorRefAdapter( actorRefFactory.actorOf( internal.adapter.PropsAdapter(() => Behavior.validateAsInitial(behavior), props, rethrowTypedFailure), name)) - } catch { + catch { case ex: ConfigurationException if ex.getMessage.startsWith(ErrorMessages.RemoteDeploymentConfigErrorPrefix) => throw new ConfigurationException(remoteDeploymentNotAllowed, ex) } - } } diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/adapter/GuardianStartupBehavior.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/adapter/GuardianStartupBehavior.scala index d719a372326..4b0c1b186eb 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/adapter/GuardianStartupBehavior.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/adapter/GuardianStartupBehavior.scala @@ -37,7 +37,7 @@ private[pekko] object GuardianStartupBehavior { def apply[T](guardianBehavior: Behavior[T]): Behavior[Any] = waitingForStart(guardianBehavior, Vector.empty) - private def waitingForStart[T](guardianBehavior: Behavior[T], tempStash: Vector[Any]): Behavior[Any] = { + private def waitingForStart[T](guardianBehavior: Behavior[T], tempStash: Vector[Any]): Behavior[Any] = Behaviors.receiveMessage { case Start => // ctx is not available initially so we cannot use it until here @@ -51,7 +51,6 @@ private[pekko] object GuardianStartupBehavior { } waitingForStart(guardianBehavior, tempStash :+ other) } - } } /** @@ -78,7 +77,7 @@ private[pekko] object GuardianStartupBehavior { interceptStopped(ctx, next) } - private def interceptStopped(ctx: TypedActorContext[Any], next: Behavior[Any]): Behavior[Any] = { + private def interceptStopped(ctx: TypedActorContext[Any], next: Behavior[Any]): Behavior[Any] = if (Behavior.isAlive(next)) next else { @@ -86,5 +85,4 @@ private[pekko] object GuardianStartupBehavior { // return next so that the adapter can call post stop on the previous behavior next } - } } diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/routing/GroupRouterImpl.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/routing/GroupRouterImpl.scala index a7c35b348bd..f6c6876e311 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/routing/GroupRouterImpl.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/routing/GroupRouterImpl.scala @@ -56,11 +56,10 @@ private[pekko] final case class GroupRouterBuilder[T] private[pekko] ( mapping: function.Function[T, String]): GroupRouterBuilder[T] = withConsistentHashingRouting(virtualNodesFactor, mapping.apply(_)) - def withConsistentHashingRouting(virtualNodesFactor: Int, mapping: T => String): GroupRouterBuilder[T] = { + def withConsistentHashingRouting(virtualNodesFactor: Int, mapping: T => String): GroupRouterBuilder[T] = copy( preferLocalRoutees = false, logicFactory = system => new RoutingLogics.ConsistentHashingLogic[T](virtualNodesFactor, mapping, system.address)) - } } /** @@ -109,12 +108,11 @@ private final class InitialGroupRouterImpl[T]( */ @InternalApi private[routing] object GroupRouterHelper { - def routeesToUpdate[T](allRoutees: Set[ActorRef[T]], preferLocalRoutees: Boolean): Set[ActorRef[T]] = { + def routeesToUpdate[T](allRoutees: Set[ActorRef[T]], preferLocalRoutees: Boolean): Set[ActorRef[T]] = if (preferLocalRoutees) { val localRoutees = allRoutees.filter(_.path.address.hasLocalScope) if (localRoutees.nonEmpty) localRoutees else allRoutees } else allRoutees - } } /** diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/routing/PoolRouterImpl.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/routing/PoolRouterImpl.scala index 8789052ad62..622953f0459 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/routing/PoolRouterImpl.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/routing/PoolRouterImpl.scala @@ -54,10 +54,9 @@ private[pekko] final case class PoolRouterBuilder[T]( def withConsistentHashingRouting(virtualNodesFactor: Int, mapping: function.Function[T, String]): PoolRouter[T] = withConsistentHashingRouting(virtualNodesFactor, mapping.apply(_)) - def withConsistentHashingRouting(virtualNodesFactor: Int, mapping: T => String): PoolRouterBuilder[T] = { + def withConsistentHashingRouting(virtualNodesFactor: Int, mapping: T => String): PoolRouterBuilder[T] = copy( logicFactory = system => new RoutingLogics.ConsistentHashingLogic[T](virtualNodesFactor, mapping, system.address)) - } def withPoolSize(poolSize: Int): PoolRouterBuilder[T] = copy(poolSize = poolSize) diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/routing/RoutingLogic.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/routing/RoutingLogic.scala index e06b1e598ec..6e70f90959c 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/routing/RoutingLogic.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/internal/routing/RoutingLogic.scala @@ -73,9 +73,8 @@ private[pekko] object RoutingLogics { var idx = 0 while (idx < currentRoutees.length && idx < sortedNewRoutees.length && - currentRoutees(idx) == sortedNewRoutees(idx)) { + currentRoutees(idx) == sortedNewRoutees(idx)) idx += 1 - } idx } if (nextIdx > firstDiffIndex) nextIdx -= 1 @@ -93,9 +92,8 @@ private[pekko] object RoutingLogics { currentRoutees(selectedIdx) } - override def routeesUpdated(newRoutees: Set[ActorRef[T]]): Unit = { + override def routeesUpdated(newRoutees: Set[ActorRef[T]]): Unit = currentRoutees = newRoutees.toArray - } } final class ConsistentHashingLogic[T](virtualNodesFactor: Int, mapping: T => String, baseAddress: Address) diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/javadsl/AbstractBehavior.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/javadsl/AbstractBehavior.scala index 5ddfa89491d..887c80ecc73 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/javadsl/AbstractBehavior.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/javadsl/AbstractBehavior.scala @@ -60,13 +60,12 @@ abstract class AbstractBehavior[T](context: ActorContext[T]) extends ExtensibleB protected def getContext: ActorContext[T] = context - private def checkRightContext(ctx: TypedActorContext[T]): Unit = { + private def checkRightContext(ctx: TypedActorContext[T]): Unit = if (ctx.asJava ne context) throw new IllegalStateException( s"Actor [${ctx.asJava.getSelf}] of AbstractBehavior class " + s"[${getClass.getName}] was created with wrong ActorContext [${context.asJava.getSelf}]. " + "Wrap in Behaviors.setup and pass the context to the constructor of AbstractBehavior.") - } @throws(classOf[Exception]) override final def receive(ctx: TypedActorContext[T], msg: T): Behavior[T] = { diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/javadsl/BehaviorBuilder.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/javadsl/BehaviorBuilder.scala index 96b40477428..c746469bf06 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/javadsl/BehaviorBuilder.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/javadsl/BehaviorBuilder.scala @@ -44,9 +44,8 @@ final class BehaviorBuilder[T] private (messageHandlers: List[Case[T, T]], signa /** * Build a Behavior from the current state of the builder */ - def build(): Behavior[T] = { + def build(): Behavior[T] = new BuiltBehavior[T](messageHandlers.reverse.toArray, signalHandlers.reverse.toArray) - } /** * Add a new case to the message handling. @@ -157,11 +156,10 @@ final class BehaviorBuilder[T] private (messageHandlers: List[Case[T, T]], signa private def withSignal[M <: Signal]( `type`: Class[M], test: OptionVal[Signal => Boolean], - handler: JFunction[Signal, Behavior[T]]): BehaviorBuilder[T] = { + handler: JFunction[Signal, Behavior[T]]): BehaviorBuilder[T] = new BehaviorBuilder[T]( messageHandlers, Case(OptionVal.Some(`type`), test, handler).asInstanceOf[Case[T, Signal]] +: signalHandlers) - } } object BehaviorBuilder { @@ -198,7 +196,7 @@ private final class BuiltBehavior[T](messageHandlers: Array[Case[T, T]], signalH override def receiveSignal(ctx: TypedActorContext[T], msg: Signal): Behavior[T] = receive(msg, signalHandlers, 0) @tailrec - private def receive[M](msg: M, handlers: Array[Case[T, M]], idx: Int): Behavior[T] = { + private def receive[M](msg: M, handlers: Array[Case[T, M]], idx: Int): Behavior[T] = if (handlers.length == 0) { Behaviors.unhandled[T] } else { @@ -210,5 +208,4 @@ private final class BuiltBehavior[T](messageHandlers: Array[Case[T, T]], signalH else receive(msg, handlers, idx + 1) } - } } diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/javadsl/Behaviors.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/javadsl/Behaviors.scala index c9d4facd350..d6697e27270 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/javadsl/Behaviors.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/javadsl/Behaviors.scala @@ -54,9 +54,9 @@ object Behaviors { * Support for stashing messages to unstash at a later time. */ def withStash[T](capacity: Int, factory: java.util.function.Function[StashBuffer[T], Behavior[T]]): Behavior[T] = - setup(ctx => { + setup { ctx => factory(StashBufferImpl[T](ctx.asScala, capacity)) - }) + } /** * Return this behavior from message processing in order to advise the @@ -180,12 +180,11 @@ object Behaviors { */ def receive[T]( onMessage: JapiFunction2[ActorContext[T], T, Behavior[T]], - onSignal: JapiFunction2[ActorContext[T], Signal, Behavior[T]]): Behavior[T] = { + onSignal: JapiFunction2[ActorContext[T], Signal, Behavior[T]]): Behavior[T] = new BehaviorImpl.ReceiveBehavior((ctx, msg) => onMessage.apply(ctx.asJava, msg), { case (ctx, sig) => onSignal.apply(ctx.asJava, sig) }) - } /** * Constructs an actor behavior builder that can build a behavior that can react to both @@ -204,9 +203,8 @@ object Behaviors { /** * Construct an actor behavior that can react to lifecycle signals only. */ - def receiveSignal[T](handler: JapiFunction2[ActorContext[T], Signal, Behavior[T]]): Behavior[T] = { + def receiveSignal[T](handler: JapiFunction2[ActorContext[T], Signal, Behavior[T]]): Behavior[T] = receive(two2same, handler) - } /** * Intercept messages and signals for a `behavior` by first passing them to a [[pekko.actor.typed.BehaviorInterceptor]] @@ -402,10 +400,9 @@ object Behaviors { mdcForMessage: pekko.japi.function.Function[T, java.util.Map[String, String]], behavior: Behavior[T]): Behavior[T] = { - def asScalaMap(m: java.util.Map[String, String]): Map[String, String] = { + def asScalaMap(m: java.util.Map[String, String]): Map[String, String] = if (m == null || m.isEmpty) Map.empty[String, String] else m.asScala.toMap - } val mdcForMessageFun: T => Map[String, String] = if (mdcForMessage == null) _ => Map.empty diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/javadsl/ReceiveBuilder.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/javadsl/ReceiveBuilder.scala index ec60a85f74d..e83c18ff6d5 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/javadsl/ReceiveBuilder.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/javadsl/ReceiveBuilder.scala @@ -216,7 +216,7 @@ private final class BuiltReceive[T]( override def receiveSignal(msg: Signal): Behavior[T] = receive[Signal](msg, signalHandlers, 0) @tailrec - private def receive[M](msg: M, handlers: Array[Case[T, M]], idx: Int): Behavior[T] = { + private def receive[M](msg: M, handlers: Array[Case[T, M]], idx: Int): Behavior[T] = if (handlers.length == 0) { Behaviors.unhandled[T] } else { @@ -228,5 +228,4 @@ private final class BuiltReceive[T]( else receive(msg, handlers, idx + 1) } - } } diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/scaladsl/AbstractBehavior.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/scaladsl/AbstractBehavior.scala index 490c04078df..ee1bf85826d 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/scaladsl/AbstractBehavior.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/scaladsl/AbstractBehavior.scala @@ -79,13 +79,12 @@ abstract class AbstractBehavior[T](protected val context: ActorContext[T]) exten @throws(classOf[Exception]) def onSignal: PartialFunction[Signal, Behavior[T]] = PartialFunction.empty - private def checkRightContext(ctx: TypedActorContext[T]): Unit = { + private def checkRightContext(ctx: TypedActorContext[T]): Unit = if (ctx.asJava ne context) throw new IllegalStateException( s"Actor [${ctx.asJava.getSelf}] of AbstractBehavior class " + s"[${getClass.getName}] was created with wrong ActorContext [${context.asJava.getSelf}]. " + "Wrap in Behaviors.setup and pass the context to the constructor of AbstractBehavior.") - } @throws(classOf[Exception]) override final def receive(ctx: TypedActorContext[T], msg: T): Behavior[T] = { diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/scaladsl/AskPattern.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/scaladsl/AskPattern.scala index 66892700cb6..571c06830d9 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/scaladsl/AskPattern.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/scaladsl/AskPattern.scala @@ -81,9 +81,8 @@ object AskPattern { * * @tparam Res The response protocol, what the other actor sends back */ - def ?[Res](replyTo: ActorRef[Res] => Req)(implicit timeout: Timeout, scheduler: Scheduler): Future[Res] = { + def ?[Res](replyTo: ActorRef[Res] => Req)(implicit timeout: Timeout, scheduler: Scheduler): Future[Res] = ask(replyTo)(timeout, scheduler) - } /** * The ask-pattern implements the initiator side of a request–reply protocol. @@ -114,7 +113,7 @@ object AskPattern { * @tparam Res The response protocol, what the other actor sends back */ @nowarn("msg=never used") - def ask[Res](replyTo: ActorRef[Res] => Req)(implicit timeout: Timeout, scheduler: Scheduler): Future[Res] = { + def ask[Res](replyTo: ActorRef[Res] => Req)(implicit timeout: Timeout, scheduler: Scheduler): Future[Res] = // We do not currently use the implicit scheduler, but want to require it // because it might be needed when we move to a 'native' typed runtime, see #24219 ref match { @@ -124,7 +123,6 @@ object AskPattern { "Only expect references to be RecipientRef, ActorRefAdapter or ActorSystemAdapter until " + "native system is implemented: " + a.getClass) } - } /** * The same as [[ask]] but only for requests that result in a response of type [[pekko.pattern.StatusReply]]. diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/scaladsl/Behaviors.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/scaladsl/Behaviors.scala index 93c71616c78..378bf80c555 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/scaladsl/Behaviors.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/scaladsl/Behaviors.scala @@ -43,10 +43,10 @@ object Behaviors { * Support for stashing messages to unstash at a later time. */ def withStash[T](capacity: Int)(factory: StashBuffer[T] => Behavior[T]): Behavior[T] = - setup(ctx => { + setup { ctx => val stash = StashBuffer[T](ctx, capacity) factory(stash) - }) + } /** * Return this behavior from message processing in order to advise the @@ -150,9 +150,8 @@ object Behaviors { * * @since 1.1.0 */ - def receiveMessageWithSame[T](onMessage: T => Unit): Receive[T] = { + def receiveMessageWithSame[T](onMessage: T => Unit): Receive[T] = new ReceiveMessageImpl(onMessage.andThen(_ => same)) - } /** * Construct an actor `Behavior` from a partial message handler which treats undefined messages as unhandled. @@ -254,9 +253,8 @@ object Behaviors { /** Specify the [[SupervisorStrategy]] to be invoked when the wrapped behavior throws. */ def onFailure[Thr <: Throwable](strategy: SupervisorStrategy)( - implicit tag: ClassTag[Thr] = ThrowableClassTag): SuperviseBehavior[T] = { + implicit tag: ClassTag[Thr] = ThrowableClassTag): SuperviseBehavior[T] = new SuperviseBehavior[T](wrapped).onFailure(strategy)(tag) - } } /** diff --git a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/scaladsl/adapter/package.scala b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/scaladsl/adapter/package.scala index 18e6583eead..48aa2c43db7 100644 --- a/actor-typed/src/main/scala/org/apache/pekko/actor/typed/scaladsl/adapter/package.scala +++ b/actor-typed/src/main/scala/org/apache/pekko/actor/typed/scaladsl/adapter/package.scala @@ -54,13 +54,12 @@ package object adapter { * Typed actors default supervision strategy is to stop. Can be overridden with * `Behaviors.supervise`. */ - def spawnAnonymous[T](behavior: Behavior[T], props: Props = Props.empty): ActorRef[T] = { + def spawnAnonymous[T](behavior: Behavior[T], props: Props = Props.empty): ActorRef[T] = ActorRefFactoryAdapter.spawnAnonymous( sys, Behaviors.supervise(behavior).onFailure(SupervisorStrategy.stop), props, rethrowTypedFailure = false) - } /** * Spawn the given behavior as a child of the user actor in a classic ActorSystem. @@ -68,14 +67,13 @@ package object adapter { * Typed actors default supervision strategy is to stop. Can be overridden with * `Behaviors.supervise`. */ - def spawn[T](behavior: Behavior[T], name: String, props: Props = Props.empty): ActorRef[T] = { + def spawn[T](behavior: Behavior[T], name: String, props: Props = Props.empty): ActorRef[T] = ActorRefFactoryAdapter.spawn( sys, Behaviors.supervise(behavior).onFailure(SupervisorStrategy.stop), name, props, rethrowTypedFailure = false) - } def toTyped: ActorSystem[Nothing] = AdapterExtension(sys).adapter } @@ -92,9 +90,8 @@ package object adapter { @InternalApi private[pekko] def internalSystemActorOf[U]( behavior: Behavior[U], name: String, - props: Props): ActorRef[U] = { + props: Props): ActorRef[U] = toClassic.asInstanceOf[ExtendedActorSystem].systemActorOf(PropsAdapter(behavior, props), name) - } } /** diff --git a/actor/src/main/scala-2.12/org/apache/pekko/util/ByteIterator.scala b/actor/src/main/scala-2.12/org/apache/pekko/util/ByteIterator.scala index 03c536d5559..a30153d3bcb 100644 --- a/actor/src/main/scala-2.12/org/apache/pekko/util/ByteIterator.scala +++ b/actor/src/main/scala-2.12/org/apache/pekko/util/ByteIterator.scala @@ -44,12 +44,11 @@ object ByteIterator { final def head: Byte = array(from) - final def next(): Byte = { + final def next(): Byte = if (!hasNext) EmptyImmutableSeq.iterator.next() else { val i = from; from = from + 1; array(i) } - } def clear(): Unit = { this.array = Array.emptyByteArray; from = 0; until = from } @@ -79,12 +78,12 @@ object ByteIterator { final override def clone: ByteArrayIterator = new ByteArrayIterator(array, from, until) final override def take(n: Int): this.type = { - if (n < len) until = { if (n > 0) from + n else from } + if (n < len) until = if (n > 0) from + n else from this } final override def drop(n: Int): this.type = { - if (n > 0) from = { if (n < len) from + n else until } + if (n > 0) from = if (n < len) from + n else until this } @@ -97,13 +96,12 @@ object ByteIterator { final override def dropWhile(p: Byte => Boolean): this.type = { var stop = false - while (!stop && hasNext) { + while (!stop && hasNext) if (p(array(from))) { from = from + 1 } else { stop = true } - } this } @@ -121,12 +119,11 @@ object ByteIterator { result } - def getBytes(xs: Array[Byte], offset: Int, n: Int): this.type = { + def getBytes(xs: Array[Byte], offset: Int, n: Int): this.type = if (n <= this.len) { System.arraycopy(this.array, this.from, xs, offset, n) this.drop(n) } else EmptyImmutableSeq.iterator.next() - } private def wrappedByteBuffer: ByteBuffer = ByteBuffer.wrap(array, from, len).asReadOnlyBuffer @@ -196,19 +193,18 @@ object ByteIterator { // * iterators.isEmpty == false // * (!iterator.head.isEmpty || iterators.tail.isEmpty) == true private def normalize(): this.type = { - @tailrec def norm(xs: LinearSeq[ByteArrayIterator]): LinearSeq[ByteArrayIterator] = { + @tailrec def norm(xs: LinearSeq[ByteArrayIterator]): LinearSeq[ByteArrayIterator] = if (xs.isEmpty) MultiByteArrayIterator.clearedList else if (xs.head.isEmpty) norm(xs.tail) else xs - } iterators = norm(iterators) this } normalize() private def current: ByteArrayIterator = iterators.head - private def dropCurrent(): Unit = { iterators = iterators.tail } - final def clear(): Unit = { iterators = MultiByteArrayIterator.empty.iterators } + private def dropCurrent(): Unit = iterators = iterators.tail + final def clear(): Unit = iterators = MultiByteArrayIterator.empty.iterators final def hasNext: Boolean = current.hasNext @@ -220,7 +216,7 @@ object ByteIterator { result } - final override def len: Int = iterators.foldLeft(0) { _ + _.len } + final override def len: Int = iterators.foldLeft(0)(_ + _.len) final override def length: Int = { val result = len @@ -322,18 +318,17 @@ object ByteIterator { } override def foreach[@specialized U](f: Byte => U): Unit = { - iterators.foreach { _.foreach(f) } + iterators.foreach(_.foreach(f)) clear() } - final override def toByteString: ByteString = { + final override def toByteString: ByteString = if (iterators.tail.isEmpty) iterators.head.toByteString else { - val result = iterators.foldLeft(ByteString.empty) { _ ++ _.toByteString } + val result = iterators.foldLeft(ByteString.empty)(_ ++ _.toByteString) clear() result } - } @tailrec protected final def getToArray[A](xs: Array[A], offset: Int, n: Int, elemSize: Int)(getSingle: => A)( getMult: (Array[A], Int, Int) => Unit): this.type = @@ -353,27 +348,27 @@ object ByteIterator { } def getBytes(xs: Array[Byte], offset: Int, n: Int): this.type = - getToArray(xs, offset, n, 1) { getByte } { current.getBytes(_, _, _) } + getToArray(xs, offset, n, 1)(getByte)(current.getBytes(_, _, _)) def getShorts(xs: Array[Short], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type = - getToArray(xs, offset, n, 2) { getShort(byteOrder) } { current.getShorts(_, _, _)(byteOrder) } + getToArray(xs, offset, n, 2)(getShort(byteOrder))(current.getShorts(_, _, _)(byteOrder)) def getInts(xs: Array[Int], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type = - getToArray(xs, offset, n, 4) { getInt(byteOrder) } { current.getInts(_, _, _)(byteOrder) } + getToArray(xs, offset, n, 4)(getInt(byteOrder))(current.getInts(_, _, _)(byteOrder)) def getLongs(xs: Array[Long], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type = - getToArray(xs, offset, n, 8) { getLong(byteOrder) } { current.getLongs(_, _, _)(byteOrder) } + getToArray(xs, offset, n, 8)(getLong(byteOrder))(current.getLongs(_, _, _)(byteOrder)) def getFloats(xs: Array[Float], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type = - getToArray(xs, offset, n, 8) { getFloat(byteOrder) } { current.getFloats(_, _, _)(byteOrder) } + getToArray(xs, offset, n, 8)(getFloat(byteOrder))(current.getFloats(_, _, _)(byteOrder)) def getDoubles(xs: Array[Double], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type = - getToArray(xs, offset, n, 8) { getDouble(byteOrder) } { current.getDoubles(_, _, _)(byteOrder) } + getToArray(xs, offset, n, 8)(getDouble(byteOrder))(current.getDoubles(_, _, _)(byteOrder)) /** For performance sensitive code, call copyToBuffer() directly on ByteString (it's optimised there) */ override def copyToBuffer(buffer: ByteBuffer): Int = { // the fold here is better than indexing into the LinearSeq - val n = iterators.foldLeft(0) { _ + _.copyToBuffer(buffer) } + val n = iterators.foldLeft(0)(_ + _.copyToBuffer(buffer)) normalize() n } @@ -443,10 +438,9 @@ abstract class ByteIterator extends BufferedIterator[Byte] { override def drop(n: Int): this.type = throw new UnsupportedOperationException("Method drop is not implemented in ByteIterator") - override def slice(from: Int, until: Int): this.type = { + override def slice(from: Int, until: Int): this.type = if (from > 0) drop(from).take(until - from) else take(until) - } // *must* be overridden by derived classes. This construction is necessary // to specialize the return type, as the method is already implemented in @@ -518,18 +512,17 @@ abstract class ByteIterator extends BufferedIterator[Byte] { /** * Get a single Short from this iterator. */ - def getShort(implicit byteOrder: ByteOrder): Short = { + def getShort(implicit byteOrder: ByteOrder): Short = if (byteOrder == ByteOrder.BIG_ENDIAN) ((next() & 0xFF) << 8 | (next() & 0xFF) << 0).toShort else if (byteOrder == ByteOrder.LITTLE_ENDIAN) ((next() & 0xFF) << 0 | (next() & 0xFF) << 8).toShort else throw new IllegalArgumentException("Unknown byte order " + byteOrder) - } /** * Get a single Int from this iterator. */ - def getInt(implicit byteOrder: ByteOrder): Int = { + def getInt(implicit byteOrder: ByteOrder): Int = if (byteOrder == ByteOrder.BIG_ENDIAN) ((next() & 0xFF) << 24 | (next() & 0xFF) << 16 @@ -541,12 +534,11 @@ abstract class ByteIterator extends BufferedIterator[Byte] { | (next() & 0xFF) << 16 | (next() & 0xFF) << 24) else throw new IllegalArgumentException("Unknown byte order " + byteOrder) - } /** * Get a single Long from this iterator. */ - def getLong(implicit byteOrder: ByteOrder): Long = { + def getLong(implicit byteOrder: ByteOrder): Long = if (byteOrder == ByteOrder.BIG_ENDIAN) ((next().toLong & 0xFF) << 56 | (next().toLong & 0xFF) << 48 @@ -566,13 +558,12 @@ abstract class ByteIterator extends BufferedIterator[Byte] { | (next().toLong & 0xFF) << 48 | (next().toLong & 0xFF) << 56) else throw new IllegalArgumentException("Unknown byte order " + byteOrder) - } /** * Get a Long from this iterator where only the least significant `n` * bytes were encoded. */ - def getLongPart(n: Int)(implicit byteOrder: ByteOrder): Long = { + def getLongPart(n: Int)(implicit byteOrder: ByteOrder): Long = if (byteOrder == ByteOrder.BIG_ENDIAN) { var x = 0L (1 to n).foreach(_ => x = (x << 8) | (next() & 0xFF)) @@ -582,7 +573,6 @@ abstract class ByteIterator extends BufferedIterator[Byte] { (0 until n).foreach(i => x |= (next() & 0xFF) << 8 * i) x } else throw new IllegalArgumentException("Unknown byte order " + byteOrder) - } def getFloat(implicit byteOrder: ByteOrder): Float = java.lang.Float.intBitsToFloat(getInt(byteOrder)) diff --git a/actor/src/main/scala-2.12/org/apache/pekko/util/ByteString.scala b/actor/src/main/scala-2.12/org/apache/pekko/util/ByteString.scala index 46865255312..eaa5216822b 100644 --- a/actor/src/main/scala-2.12/org/apache/pekko/util/ByteString.scala +++ b/actor/src/main/scala-2.12/org/apache/pekko/util/ByteString.scala @@ -213,11 +213,10 @@ object ByteString { override def encodeBase64: ByteString = if (isEmpty) this else ByteString1C(Base64.getEncoder.encode(bytes)) - override def ++(that: ByteString): ByteString = { + override def ++(that: ByteString): ByteString = if (that.isEmpty) this else if (this.isEmpty) that else toByteString1 ++ that - } override def take(n: Int): ByteString = if (n <= 0) ByteString.empty @@ -233,7 +232,7 @@ object ByteString { else toByteString1.drop(n) override def indexOf[B >: Byte](elem: B): Int = indexOf(elem, 0) - override def indexOf[B >: Byte](elem: B, from: Int): Int = { + override def indexOf[B >: Byte](elem: B, from: Int): Int = if (from >= length) -1 else { var found = -1 @@ -244,10 +243,9 @@ object ByteString { } found } - } override def indexOf(elem: Byte): Int = indexOf(elem, 0) - override def indexOf(elem: Byte, from: Int): Int = { + override def indexOf(elem: Byte, from: Int): Int = if (from >= length) -1 else { var found = -1 @@ -258,7 +256,6 @@ object ByteString { } found } - } override def slice(from: Int, until: Int): ByteString = if (from <= 0 && until >= length) this @@ -281,9 +278,8 @@ object ByteString { } /** INTERNAL API: Specialized for internal use, appending ByteString1C to a ByteStringBuilder. */ - private[pekko] def appendToBuilder(buffer: ByteStringBuilder) = { + private[pekko] def appendToBuilder(buffer: ByteStringBuilder) = buffer.putByteArrayUnsafe(bytes) - } override def toArrayUnsafe(): Array[Byte] = bytes @@ -321,12 +317,11 @@ object ByteString { override def iterator: ByteIterator.ByteArrayIterator = ByteIterator.ByteArrayIterator(bytes, startIndex, startIndex + length) - private def checkRangeConvert(index: Int): Int = { + private def checkRangeConvert(index: Int): Int = if (0 <= index && length > index) index + startIndex else throw new IndexOutOfBoundsException(index.toString) - } private[pekko] def writeToOutputStream(os: ObjectOutputStream): Unit = { os.writeInt(length) @@ -419,7 +414,7 @@ object ByteString { } else CompactByteString(dst) } - def ++(that: ByteString): ByteString = { + def ++(that: ByteString): ByteString = if (that.isEmpty) this else if (this.isEmpty) that else @@ -431,10 +426,9 @@ object ByteString { else ByteStrings(this, b) case bs: ByteStrings => ByteStrings(this, bs) } - } override def indexOf[B >: Byte](elem: B): Int = indexOf(elem, 0) - override def indexOf[B >: Byte](elem: B, from: Int): Int = { + override def indexOf[B >: Byte](elem: B, from: Int): Int = if (from >= length) -1 else { var found = -1 @@ -445,10 +439,9 @@ object ByteString { } found } - } override def indexOf(elem: Byte): Int = indexOf(elem, 0) - override def indexOf(elem: Byte, from: Int): Int = { + override def indexOf(elem: Byte, from: Int): Int = if (from >= length) -1 else { var found = -1 @@ -459,14 +452,12 @@ object ByteString { } found } - } protected def writeReplace(): AnyRef = new SerializationProxy(this) - override def toArrayUnsafe(): Array[Byte] = { + override def toArrayUnsafe(): Array[Byte] = if (startIndex == 0 && length == bytes.length) bytes else toArray - } override def asInputStream: InputStream = new ByteArrayInputStream(bytes, startIndex, length) @@ -542,7 +533,7 @@ object ByteString { if (bytestrings.isEmpty) throw new IllegalArgumentException("bytestrings must not be empty") if (bytestrings.head.isEmpty) throw new IllegalArgumentException("bytestrings.head must not be empty") - def apply(idx: Int): Byte = { + def apply(idx: Int): Byte = if (0 <= idx && idx < length) { var pos = 0 var seen = 0 @@ -554,13 +545,12 @@ object ByteString { } frag(idx - seen) } else throw new IndexOutOfBoundsException(idx.toString) - } /** Avoid `iterator` in performance sensitive code, call ops directly on ByteString instead */ override def iterator: ByteIterator.MultiByteArrayIterator = - ByteIterator.MultiByteArrayIterator(bytestrings.toStream.map { _.iterator }) + ByteIterator.MultiByteArrayIterator(bytestrings.toStream.map(_.iterator)) - def ++(that: ByteString): ByteString = { + def ++(that: ByteString): ByteString = if (that.isEmpty) this else if (this.isEmpty) that else @@ -569,7 +559,6 @@ object ByteString { case b: ByteString1 => ByteStrings(this, b) case bs: ByteStrings => ByteStrings(this, bs) } - } private[pekko] def byteStringCompanion = ByteStrings @@ -583,7 +572,7 @@ object ByteString { copyItToTheBuffer(buffer, 0, 0) } - def compact: CompactByteString = { + def compact: CompactByteString = if (isCompact) bytestrings.head.compact else { val ar = new Array[Byte](length) @@ -594,11 +583,10 @@ object ByteString { } ByteString1C(ar) } - } def asByteBuffer: ByteBuffer = compact.asByteBuffer - def asByteBuffers: scala.collection.immutable.Iterable[ByteBuffer] = bytestrings.map { _.asByteBuffer } + def asByteBuffers: scala.collection.immutable.Iterable[ByteBuffer] = bytestrings.map(_.asByteBuffer) override def asInputStream: InputStream = new SequenceInputStream(bytestrings.iterator.map(_.asInputStream).asJavaEnumeration) @@ -694,13 +682,13 @@ object ByteString { } override def indexOf[B >: Byte](elem: B): Int = indexOf(elem, 0) - override def indexOf[B >: Byte](elem: B, from: Int): Int = { + override def indexOf[B >: Byte](elem: B, from: Int): Int = if (from >= length) -1 else { val byteStringsSize = bytestrings.size @tailrec - def find(bsIdx: Int, relativeIndex: Int, bytesPassed: Int): Int = { + def find(bsIdx: Int, relativeIndex: Int, bytesPassed: Int): Int = if (bsIdx >= byteStringsSize) -1 else { val bs = bytestrings(bsIdx) @@ -714,20 +702,18 @@ object ByteString { } else subIndexOf + bytesPassed } } - } find(0, math.max(from, 0), 0) } - } override def indexOf(elem: Byte): Int = indexOf(elem, 0) - override def indexOf(elem: Byte, from: Int): Int = { + override def indexOf(elem: Byte, from: Int): Int = if (from >= length) -1 else { val byteStringsSize = bytestrings.size @tailrec - def find(bsIdx: Int, relativeIndex: Int, bytesPassed: Int): Int = { + def find(bsIdx: Int, relativeIndex: Int, bytesPassed: Int): Int = if (bsIdx >= byteStringsSize) -1 else { val bs = bytestrings(bsIdx) @@ -741,11 +727,9 @@ object ByteString { } else subIndexOf + bytesPassed } } - } find(0, math.max(from, 0), 0) } - } protected def writeReplace(): AnyRef = new SerializationProxy(this) } @@ -983,9 +967,8 @@ sealed abstract class ByteString extends IndexedSeq[Byte] with IndexedSeqOptimiz * Java API: Returns an Iterable of read-only ByteBuffers that directly wraps this ByteStrings * all fragments. Will always have at least one entry. */ - def getByteBuffers(): JIterable[ByteBuffer] = { + def getByteBuffers(): JIterable[ByteBuffer] = asByteBuffers.asJava - } /** * Creates a new ByteBuffer with a copy of all bytes contained in this @@ -1038,42 +1021,38 @@ object CompactByteString { /** * Creates a new CompactByteString by copying bytes. */ - def apply(bytes: Byte*): CompactByteString = { + def apply(bytes: Byte*): CompactByteString = if (bytes.isEmpty) empty else { val ar = new Array[Byte](bytes.size) bytes.copyToArray(ar) ByteString.ByteString1C(ar) } - } /** * Creates a new CompactByteString by traversing bytes. */ - def apply(bytes: Iterator[Byte]): CompactByteString = { + def apply(bytes: Iterator[Byte]): CompactByteString = if (bytes.isEmpty) empty else ByteString.ByteString1C(bytes.toArray) - } /** * Creates a new CompactByteString by converting from integral numbers to bytes. */ - def apply[T](bytes: T*)(implicit num: Integral[T]): CompactByteString = { + def apply[T](bytes: T*)(implicit num: Integral[T]): CompactByteString = if (bytes.isEmpty) empty else ByteString.ByteString1C(bytes.map(x => num.toInt(x).toByte)(collection.breakOut)) - } /** * Creates a new CompactByteString by copying bytes from a ByteBuffer. */ - def apply(bytes: ByteBuffer): CompactByteString = { + def apply(bytes: ByteBuffer): CompactByteString = if (bytes.remaining < 1) empty else { val ar = new Array[Byte](bytes.remaining) bytes.get(ar) ByteString.ByteString1C(ar) } - } /** * Creates a new CompactByteString by encoding a String as UTF-8. @@ -1144,29 +1123,26 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { this } - protected final def fillByteBuffer(len: Int, byteOrder: ByteOrder)(fill: ByteBuffer => Unit): this.type = { + protected final def fillByteBuffer(len: Int, byteOrder: ByteOrder)(fill: ByteBuffer => Unit): this.type = fillArray(len) { case (array, start) => val buffer = ByteBuffer.wrap(array, start, len) buffer.order(byteOrder) fill(buffer) } - } def length: Int = _length - override def sizeHint(len: Int): Unit = { + override def sizeHint(len: Int): Unit = resizeTemp(len - (_length - _tempLength)) - } - private def clearTemp(): Unit = { + private def clearTemp(): Unit = if (_tempLength > 0) { val arr = new Array[Byte](_tempLength) System.arraycopy(_temp, 0, arr, 0, _tempLength) _builder += ByteString1(arr) _tempLength = 0 } - } private def resizeTemp(size: Int): Unit = { val newtemp = new Array[Byte](size) @@ -1177,13 +1153,12 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { private def shouldResizeTempFor(size: Int): Boolean = _tempCapacity < size || _tempCapacity == 0 - private def ensureTempSize(size: Int): Unit = { + private def ensureTempSize(size: Int): Unit = if (shouldResizeTempFor(size)) { var newSize = if (_tempCapacity == 0) 16 else _tempCapacity * 2 while (newSize < size) newSize *= 2 resizeTemp(newSize) } - } def +=(elem: Byte): this.type = { ensureTempSize(_tempLength + 1) @@ -1256,7 +1231,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { /** * Add a single Short to this builder. */ - def putShort(x: Int)(implicit byteOrder: ByteOrder): this.type = { + def putShort(x: Int)(implicit byteOrder: ByteOrder): this.type = if (byteOrder == ByteOrder.BIG_ENDIAN) { this += (x >>> 8).toByte this += (x >>> 0).toByte @@ -1264,7 +1239,6 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { this += (x >>> 0).toByte this += (x >>> 8).toByte } else throw new IllegalArgumentException("Unknown byte order " + byteOrder) - } /** * Add a single Int to this builder. @@ -1317,7 +1291,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { /** * Add the `n` least significant bytes of the given Long to this builder. */ - def putLongPart(x: Long, n: Int)(implicit byteOrder: ByteOrder): this.type = { + def putLongPart(x: Long, n: Int)(implicit byteOrder: ByteOrder): this.type = fillArray(n) { (target, offset) => if (byteOrder == ByteOrder.BIG_ENDIAN) { val start = n * 8 - 8 @@ -1330,7 +1304,6 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { } } else throw new IllegalArgumentException("Unknown byte order " + byteOrder) } - } /** * Add a single Float to this builder. @@ -1366,7 +1339,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { * Add a number of Shorts from an array to this builder. */ def putShorts(array: Array[Short], start: Int, len: Int)(implicit byteOrder: ByteOrder): this.type = - fillByteBuffer(len * 2, byteOrder) { _.asShortBuffer.put(array, start, len) } + fillByteBuffer(len * 2, byteOrder)(_.asShortBuffer.put(array, start, len)) /** * Add a number of Ints from an array to this builder. @@ -1378,7 +1351,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { * Add a number of Ints from an array to this builder. */ def putInts(array: Array[Int], start: Int, len: Int)(implicit byteOrder: ByteOrder): this.type = - fillByteBuffer(len * 4, byteOrder) { _.asIntBuffer.put(array, start, len) } + fillByteBuffer(len * 4, byteOrder)(_.asIntBuffer.put(array, start, len)) /** * Add a number of Longs from an array to this builder. @@ -1390,7 +1363,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { * Add a number of Longs from an array to this builder. */ def putLongs(array: Array[Long], start: Int, len: Int)(implicit byteOrder: ByteOrder): this.type = - fillByteBuffer(len * 8, byteOrder) { _.asLongBuffer.put(array, start, len) } + fillByteBuffer(len * 8, byteOrder)(_.asLongBuffer.put(array, start, len)) /** * Add a number of Floats from an array to this builder. @@ -1402,7 +1375,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { * Add a number of Floats from an array to this builder. */ def putFloats(array: Array[Float], start: Int, len: Int)(implicit byteOrder: ByteOrder): this.type = - fillByteBuffer(len * 4, byteOrder) { _.asFloatBuffer.put(array, start, len) } + fillByteBuffer(len * 4, byteOrder)(_.asFloatBuffer.put(array, start, len)) /** * Add a number of Doubles from an array to this builder. @@ -1414,7 +1387,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { * Add a number of Doubles from an array to this builder. */ def putDoubles(array: Array[Double], start: Int, len: Int)(implicit byteOrder: ByteOrder): this.type = - fillByteBuffer(len * 8, byteOrder) { _.asDoubleBuffer.put(array, start, len) } + fillByteBuffer(len * 8, byteOrder)(_.asDoubleBuffer.put(array, start, len)) def clear(): Unit = { _builder.clear() @@ -1439,7 +1412,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { */ def asOutputStream: java.io.OutputStream = new java.io.OutputStream { override def write(b: Int): Unit = builder += b.toByte - override def write(b: Array[Byte], off: Int, len: Int): Unit = { builder.putBytes(b, off, len) } + override def write(b: Array[Byte], off: Int, len: Int): Unit = builder.putBytes(b, off, len) } /** diff --git a/actor/src/main/scala-2.13+/org/apache/pekko/compat/Future.scala b/actor/src/main/scala-2.13+/org/apache/pekko/compat/Future.scala index 1d962d5d93d..100f355f7a2 100644 --- a/actor/src/main/scala-2.13+/org/apache/pekko/compat/Future.scala +++ b/actor/src/main/scala-2.13+/org/apache/pekko/compat/Future.scala @@ -28,30 +28,27 @@ import org.apache.pekko.annotation.InternalApi */ @InternalApi private[pekko] object Future { def fold[T, R](futures: IterableOnce[SFuture[T]])(zero: R)(op: (R, T) => R)( - implicit executor: ExecutionContext): SFuture[R] = { + implicit executor: ExecutionContext): SFuture[R] = // This will have performance implications since the elements are copied to a Vector SFuture.foldLeft[T, R](futures.iterator.to(immutable.Iterable))(zero)(op)(executor) - } def fold[T, R](futures: immutable.Iterable[SFuture[T]])(zero: R)(op: (R, T) => R)( implicit executor: ExecutionContext): SFuture[R] = SFuture.foldLeft[T, R](futures)(zero)(op)(executor) def reduce[T, R >: T](futures: IterableOnce[SFuture[T]])(op: (R, T) => R)( - implicit executor: ExecutionContext): SFuture[R] = { + implicit executor: ExecutionContext): SFuture[R] = // This will have performance implications since the elements are copied to a Vector SFuture.reduceLeft[T, R](futures.iterator.to(immutable.Iterable))(op)(executor) - } def reduce[T, R >: T](futures: immutable.Iterable[SFuture[T]])(op: (R, T) => R)( implicit executor: ExecutionContext): SFuture[R] = SFuture.reduceLeft[T, R](futures)(op)(executor) def find[T](futures: IterableOnce[SFuture[T]])(p: T => Boolean)( - implicit executor: ExecutionContext): SFuture[Option[T]] = { + implicit executor: ExecutionContext): SFuture[Option[T]] = // This will have performance implications since the elements are copied to a Vector SFuture.find[T](futures.iterator.to(immutable.Iterable))(p)(executor) - } def find[T](futures: immutable.Iterable[SFuture[T]])(p: T => Boolean)( implicit executor: ExecutionContext): SFuture[Option[T]] = diff --git a/actor/src/main/scala-2.13/org/apache/pekko/util/ByteIterator.scala b/actor/src/main/scala-2.13/org/apache/pekko/util/ByteIterator.scala index 412ae84c099..6442e23126a 100644 --- a/actor/src/main/scala-2.13/org/apache/pekko/util/ByteIterator.scala +++ b/actor/src/main/scala-2.13/org/apache/pekko/util/ByteIterator.scala @@ -45,12 +45,11 @@ object ByteIterator { final def head: Byte = array(from) - final def next(): Byte = { + final def next(): Byte = if (!hasNext) EmptyImmutableSeq.iterator.next() else { val i = from; from = from + 1; array(i) } - } def clear(): Unit = { this.array = Array.emptyByteArray; from = 0; until = from } @@ -81,12 +80,12 @@ object ByteIterator { final override def clone: ByteArrayIterator = new ByteArrayIterator(array, from, until) final override def take(n: Int): this.type = { - if (n < len) until = { if (n > 0) from + n else from } + if (n < len) until = if (n > 0) from + n else from this } final override def drop(n: Int): this.type = { - if (n > 0) from = { if (n < len) from + n else until } + if (n > 0) from = if (n < len) from + n else until this } @@ -99,13 +98,12 @@ object ByteIterator { final override def dropWhile(p: Byte => Boolean): this.type = { var stop = false - while (!stop && hasNext) { + while (!stop && hasNext) if (p(array(from))) { from = from + 1 } else { stop = true } - } this } @@ -133,12 +131,11 @@ object ByteIterator { } @throws[NoSuchElementException] - def getBytes(xs: Array[Byte], offset: Int, n: Int): this.type = { + def getBytes(xs: Array[Byte], offset: Int, n: Int): this.type = if (n <= this.len) { System.arraycopy(this.array, this.from, xs, offset, n) this.drop(n) } else throw new NoSuchElementException("next on empty iterator") - } private def wrappedByteBuffer: ByteBuffer = ByteBuffer.wrap(array, from, len).asReadOnlyBuffer @@ -208,19 +205,18 @@ object ByteIterator { // * iterators.isEmpty == false // * (!iterator.head.isEmpty || iterators.tail.isEmpty) == true private def normalize(): this.type = { - @tailrec def norm(xs: LinearSeq[ByteArrayIterator]): LinearSeq[ByteArrayIterator] = { + @tailrec def norm(xs: LinearSeq[ByteArrayIterator]): LinearSeq[ByteArrayIterator] = if (xs.isEmpty) MultiByteArrayIterator.clearedList else if (xs.head.isEmpty) norm(xs.tail) else xs - } iterators = norm(iterators) this } normalize() private def current: ByteArrayIterator = iterators.head - private def dropCurrent(): Unit = { iterators = iterators.tail } - final def clear(): Unit = { iterators = MultiByteArrayIterator.empty.iterators } + private def dropCurrent(): Unit = iterators = iterators.tail + final def clear(): Unit = iterators = MultiByteArrayIterator.empty.iterators final def hasNext: Boolean = current.hasNext @@ -232,7 +228,7 @@ object ByteIterator { result } - final override def len: Int = iterators.foldLeft(0) { _ + _.len } + final override def len: Int = iterators.foldLeft(0)(_ + _.len) final override def size: Int = { val result = len @@ -336,18 +332,17 @@ object ByteIterator { } override def foreach[@specialized U](f: Byte => U): Unit = { - iterators.foreach { _.foreach(f) } + iterators.foreach(_.foreach(f)) clear() } - final override def toByteString: ByteString = { + final override def toByteString: ByteString = if (iterators.tail.isEmpty) iterators.head.toByteString else { - val result = iterators.foldLeft(ByteString.empty) { _ ++ _.toByteString } + val result = iterators.foldLeft(ByteString.empty)(_ ++ _.toByteString) clear() result } - } @tailrec protected final def getToArray[A](xs: Array[A], offset: Int, n: Int, elemSize: Int)(getSingle: => A)( getMult: (Array[A], Int, Int) => Unit): this.type = @@ -367,27 +362,27 @@ object ByteIterator { } def getBytes(xs: Array[Byte], offset: Int, n: Int): this.type = - getToArray(xs, offset, n, 1) { getByte } { current.getBytes(_, _, _) } + getToArray(xs, offset, n, 1)(getByte)(current.getBytes(_, _, _)) def getShorts(xs: Array[Short], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type = - getToArray(xs, offset, n, 2) { getShort(byteOrder) } { current.getShorts(_, _, _)(byteOrder) } + getToArray(xs, offset, n, 2)(getShort(byteOrder))(current.getShorts(_, _, _)(byteOrder)) def getInts(xs: Array[Int], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type = - getToArray(xs, offset, n, 4) { getInt(byteOrder) } { current.getInts(_, _, _)(byteOrder) } + getToArray(xs, offset, n, 4)(getInt(byteOrder))(current.getInts(_, _, _)(byteOrder)) def getLongs(xs: Array[Long], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type = - getToArray(xs, offset, n, 8) { getLong(byteOrder) } { current.getLongs(_, _, _)(byteOrder) } + getToArray(xs, offset, n, 8)(getLong(byteOrder))(current.getLongs(_, _, _)(byteOrder)) def getFloats(xs: Array[Float], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type = - getToArray(xs, offset, n, 8) { getFloat(byteOrder) } { current.getFloats(_, _, _)(byteOrder) } + getToArray(xs, offset, n, 8)(getFloat(byteOrder))(current.getFloats(_, _, _)(byteOrder)) def getDoubles(xs: Array[Double], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type = - getToArray(xs, offset, n, 8) { getDouble(byteOrder) } { current.getDoubles(_, _, _)(byteOrder) } + getToArray(xs, offset, n, 8)(getDouble(byteOrder))(current.getDoubles(_, _, _)(byteOrder)) /** For performance sensitive code, call copyToBuffer() directly on ByteString (it's optimised there) */ override def copyToBuffer(buffer: ByteBuffer): Int = { // the fold here is better than indexing into the LinearSeq - val n = iterators.foldLeft(0) { _ + _.copyToBuffer(buffer) } + val n = iterators.foldLeft(0)(_ + _.copyToBuffer(buffer)) normalize() n } @@ -460,10 +455,9 @@ abstract class ByteIterator extends BufferedIterator[Byte] { override def drop(n: Int): this.type = throw new UnsupportedOperationException("Method drop is not implemented in ByteIterator") - override def slice(from: Int, until: Int): this.type = { + override def slice(from: Int, until: Int): this.type = if (from > 0) drop(from).take(until - from) else take(until) - } // *must* be overridden by derived classes. This construction is necessary // to specialize the return type, as the method is already implemented in @@ -534,18 +528,17 @@ abstract class ByteIterator extends BufferedIterator[Byte] { /** * Get a single Short from this iterator. */ - def getShort(implicit byteOrder: ByteOrder): Short = { + def getShort(implicit byteOrder: ByteOrder): Short = if (byteOrder == ByteOrder.BIG_ENDIAN) ((next() & 0xFF) << 8 | (next() & 0xFF) << 0).toShort else if (byteOrder == ByteOrder.LITTLE_ENDIAN) ((next() & 0xFF) << 0 | (next() & 0xFF) << 8).toShort else throw new IllegalArgumentException("Unknown byte order " + byteOrder) - } /** * Get a single Int from this iterator. */ - def getInt(implicit byteOrder: ByteOrder): Int = { + def getInt(implicit byteOrder: ByteOrder): Int = if (byteOrder == ByteOrder.BIG_ENDIAN) ((next() & 0xFF) << 24 | (next() & 0xFF) << 16 @@ -557,12 +550,11 @@ abstract class ByteIterator extends BufferedIterator[Byte] { | (next() & 0xFF) << 16 | (next() & 0xFF) << 24) else throw new IllegalArgumentException("Unknown byte order " + byteOrder) - } /** * Get a single Long from this iterator. */ - def getLong(implicit byteOrder: ByteOrder): Long = { + def getLong(implicit byteOrder: ByteOrder): Long = if (byteOrder == ByteOrder.BIG_ENDIAN) ((next().toLong & 0xFF) << 56 | (next().toLong & 0xFF) << 48 @@ -582,13 +574,12 @@ abstract class ByteIterator extends BufferedIterator[Byte] { | (next().toLong & 0xFF) << 48 | (next().toLong & 0xFF) << 56) else throw new IllegalArgumentException("Unknown byte order " + byteOrder) - } /** * Get a Long from this iterator where only the least significant `n` * bytes were encoded. */ - def getLongPart(n: Int)(implicit byteOrder: ByteOrder): Long = { + def getLongPart(n: Int)(implicit byteOrder: ByteOrder): Long = if (byteOrder == ByteOrder.BIG_ENDIAN) { var x = 0L (1 to n).foreach(_ => x = (x << 8) | (next() & 0xFF)) @@ -598,7 +589,6 @@ abstract class ByteIterator extends BufferedIterator[Byte] { (0 until n).foreach(i => x |= (next() & 0xFF) << 8 * i) x } else throw new IllegalArgumentException("Unknown byte order " + byteOrder) - } def getFloat(implicit byteOrder: ByteOrder): Float = java.lang.Float.intBitsToFloat(getInt(byteOrder)) diff --git a/actor/src/main/scala-2.13/org/apache/pekko/util/ByteString.scala b/actor/src/main/scala-2.13/org/apache/pekko/util/ByteString.scala index 826d1b81209..ade970ce1f6 100644 --- a/actor/src/main/scala-2.13/org/apache/pekko/util/ByteString.scala +++ b/actor/src/main/scala-2.13/org/apache/pekko/util/ByteString.scala @@ -211,11 +211,10 @@ object ByteString { override def encodeBase64: ByteString = if (isEmpty) this else ByteString1C(Base64.getEncoder.encode(bytes)) - override def ++(that: ByteString): ByteString = { + override def ++(that: ByteString): ByteString = if (that.isEmpty) this else if (this.isEmpty) that else toByteString1 ++ that - } override def take(n: Int): ByteString = if (n <= 0) ByteString.empty @@ -230,7 +229,7 @@ object ByteString { if (n <= 0) this else toByteString1.drop(n) - override def indexOf[B >: Byte](elem: B, from: Int): Int = { + override def indexOf[B >: Byte](elem: B, from: Int): Int = if (from >= length) -1 else { var found = -1 @@ -241,9 +240,8 @@ object ByteString { } found } - } - override def indexOf(elem: Byte, from: Int): Int = { + override def indexOf(elem: Byte, from: Int): Int = if (from >= length) -1 else { var found = -1 @@ -254,7 +252,6 @@ object ByteString { } found } - } override def slice(from: Int, until: Int): ByteString = if (from <= 0 && until >= length) this @@ -277,9 +274,8 @@ object ByteString { } /** INTERNAL API: Specialized for internal use, appending ByteString1C to a ByteStringBuilder. */ - private[pekko] def appendToBuilder(buffer: ByteStringBuilder) = { + private[pekko] def appendToBuilder(buffer: ByteStringBuilder) = buffer.putByteArrayUnsafe(bytes) - } override def copyToArray[B >: Byte](dest: Array[B], start: Int, len: Int): Int = { val toCopy = math.min(math.min(len, bytes.length), dest.length - start) @@ -322,12 +318,11 @@ object ByteString { override def iterator: ByteIterator.ByteArrayIterator = ByteIterator.ByteArrayIterator(bytes, startIndex, startIndex + length) - private def checkRangeConvert(index: Int): Int = { + private def checkRangeConvert(index: Int): Int = if (0 <= index && length > index) index + startIndex else throw new IndexOutOfBoundsException(index.toString) - } private[pekko] def writeToOutputStream(os: ObjectOutputStream): Unit = { os.writeInt(length) @@ -420,7 +415,7 @@ object ByteString { } else CompactByteString(dst) } - def ++(that: ByteString): ByteString = { + def ++(that: ByteString): ByteString = if (that.isEmpty) this else if (this.isEmpty) that else @@ -432,9 +427,8 @@ object ByteString { else ByteStrings(this, b) case bs: ByteStrings => ByteStrings(this, bs) } - } - override def indexOf[B >: Byte](elem: B, from: Int): Int = { + override def indexOf[B >: Byte](elem: B, from: Int): Int = if (from >= length) -1 else { var found = -1 @@ -445,9 +439,8 @@ object ByteString { } found } - } - override def indexOf(elem: Byte, from: Int): Int = { + override def indexOf(elem: Byte, from: Int): Int = if (from >= length) -1 else { var found = -1 @@ -458,7 +451,6 @@ object ByteString { } found } - } override def copyToArray[B >: Byte](dest: Array[B], start: Int, len: Int): Int = { // min of the bytes available to copy, bytes there is room for in dest and the requested number of bytes @@ -471,10 +463,9 @@ object ByteString { protected def writeReplace(): AnyRef = new SerializationProxy(this) - override def toArrayUnsafe(): Array[Byte] = { + override def toArrayUnsafe(): Array[Byte] = if (startIndex == 0 && length == bytes.length) bytes else toArray - } override def asInputStream: InputStream = new ByteArrayInputStream(bytes, startIndex, length) @@ -550,7 +541,7 @@ object ByteString { if (bytestrings.isEmpty) throw new IllegalArgumentException("bytestrings must not be empty") if (bytestrings.head.isEmpty) throw new IllegalArgumentException("bytestrings.head must not be empty") - def apply(idx: Int): Byte = { + def apply(idx: Int): Byte = if (0 <= idx && idx < length) { var pos = 0 var seen = 0 @@ -562,13 +553,12 @@ object ByteString { } frag(idx - seen) } else throw new IndexOutOfBoundsException(idx.toString) - } /** Avoid `iterator` in performance sensitive code, call ops directly on ByteString instead */ override def iterator: ByteIterator.MultiByteArrayIterator = - ByteIterator.MultiByteArrayIterator(bytestrings.to(LazyList).map { _.iterator }) + ByteIterator.MultiByteArrayIterator(bytestrings.to(LazyList).map(_.iterator)) - def ++(that: ByteString): ByteString = { + def ++(that: ByteString): ByteString = if (that.isEmpty) this else if (this.isEmpty) that else @@ -577,7 +567,6 @@ object ByteString { case b: ByteString1 => ByteStrings(this, b) case bs: ByteStrings => ByteStrings(this, bs) } - } private[pekko] def byteStringCompanion = ByteStrings @@ -591,7 +580,7 @@ object ByteString { copyItToTheBuffer(buffer, 0, 0) } - def compact: CompactByteString = { + def compact: CompactByteString = if (isCompact) bytestrings.head.compact else { val ar = new Array[Byte](length) @@ -602,11 +591,10 @@ object ByteString { } ByteString1C(ar) } - } def asByteBuffer: ByteBuffer = compact.asByteBuffer - def asByteBuffers: scala.collection.immutable.Iterable[ByteBuffer] = bytestrings.map { _.asByteBuffer } + def asByteBuffers: scala.collection.immutable.Iterable[ByteBuffer] = bytestrings.map(_.asByteBuffer) override def asInputStream: InputStream = new SequenceInputStream(bytestrings.iterator.map(_.asInputStream).asJavaEnumeration) @@ -701,13 +689,13 @@ object ByteString { new ByteStrings(bytestrings(fullDrops).drop1(remainingToDrop) +: bytestrings.drop(fullDrops + 1), length - n) } - override def indexOf[B >: Byte](elem: B, from: Int): Int = { + override def indexOf[B >: Byte](elem: B, from: Int): Int = if (from >= length) -1 else { val byteStringsSize = bytestrings.size @tailrec - def find(bsIdx: Int, relativeIndex: Int, bytesPassed: Int): Int = { + def find(bsIdx: Int, relativeIndex: Int, bytesPassed: Int): Int = if (bsIdx >= byteStringsSize) -1 else { val bs = bytestrings(bsIdx) @@ -721,19 +709,17 @@ object ByteString { } else subIndexOf + bytesPassed } } - } find(0, math.max(from, 0), 0) } - } - override def indexOf(elem: Byte, from: Int): Int = { + override def indexOf(elem: Byte, from: Int): Int = if (from >= length) -1 else { val byteStringsSize = bytestrings.size @tailrec - def find(bsIdx: Int, relativeIndex: Int, bytesPassed: Int): Int = { + def find(bsIdx: Int, relativeIndex: Int, bytesPassed: Int): Int = if (bsIdx >= byteStringsSize) -1 else { val bs = bytestrings(bsIdx) @@ -747,13 +733,11 @@ object ByteString { } else subIndexOf + bytesPassed } } - } find(0, math.max(from, 0), 0) } - } - override def copyToArray[B >: Byte](dest: Array[B], start: Int, len: Int): Int = { + override def copyToArray[B >: Byte](dest: Array[B], start: Int, len: Int): Int = if (bytestrings.size == 1) bytestrings.head.copyToArray(dest, start, len) else { // min of the bytes available to copy, bytes there is room for in dest and the requested number of bytes @@ -768,7 +752,6 @@ object ByteString { } totalToCopy } - } protected def writeReplace(): AnyRef = new SerializationProxy(this) } @@ -929,10 +912,9 @@ sealed abstract class ByteString } @nowarn("msg=deprecated") - final override def copyToArray[B >: Byte](xs: Array[B], start: Int): Int = { + final override def copyToArray[B >: Byte](xs: Array[B], start: Int): Int = // super uses byteiterator copyToArray(xs, start, size.min(xs.size)) - } // optimized in all subclasses, avoiding usage of the iterator to save allocations/transformations override def copyToArray[B >: Byte](xs: Array[B], start: Int, len: Int): Int = @@ -1021,9 +1003,8 @@ sealed abstract class ByteString * Java API: Returns an Iterable of read-only ByteBuffers that directly wraps this ByteStrings * all fragments. Will always have at least one entry. */ - def getByteBuffers(): JIterable[ByteBuffer] = { + def getByteBuffers(): JIterable[ByteBuffer] = asByteBuffers.asJava - } /** * Creates a new ByteBuffer with a copy of all bytes contained in this @@ -1078,14 +1059,13 @@ object CompactByteString { /** * Creates a new CompactByteString by copying bytes. */ - def apply(bytes: Byte*): CompactByteString = { + def apply(bytes: Byte*): CompactByteString = if (bytes.isEmpty) empty else { val ar = new Array[Byte](bytes.size) bytes.copyToArray(ar) ByteString.ByteString1C(ar) } - } /** * Creates a new CompactByteString by traversing bytes. @@ -1099,22 +1079,20 @@ object CompactByteString { /** * Creates a new CompactByteString by converting from integral numbers to bytes. */ - def apply[T](bytes: T*)(implicit num: Integral[T]): CompactByteString = { + def apply[T](bytes: T*)(implicit num: Integral[T]): CompactByteString = if (bytes.isEmpty) empty else ByteString.ByteString1C(bytes.iterator.map(x => num.toInt(x).toByte).to(Array)) - } /** * Creates a new CompactByteString by copying bytes from a ByteBuffer. */ - def apply(bytes: ByteBuffer): CompactByteString = { + def apply(bytes: ByteBuffer): CompactByteString = if (bytes.remaining < 1) empty else { val ar = new Array[Byte](bytes.remaining) bytes.get(ar) ByteString.ByteString1C(ar) } - } /** * Creates a new CompactByteString by encoding a String as UTF-8. @@ -1185,29 +1163,26 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { this } - protected final def fillByteBuffer(len: Int, byteOrder: ByteOrder)(fill: ByteBuffer => Unit): this.type = { + protected final def fillByteBuffer(len: Int, byteOrder: ByteOrder)(fill: ByteBuffer => Unit): this.type = fillArray(len) { case (array, start) => val buffer = ByteBuffer.wrap(array, start, len) buffer.order(byteOrder) fill(buffer) } - } def length: Int = _length - override def sizeHint(len: Int): Unit = { + override def sizeHint(len: Int): Unit = resizeTemp(len - (_length - _tempLength)) - } - private def clearTemp(): Unit = { + private def clearTemp(): Unit = if (_tempLength > 0) { val arr = new Array[Byte](_tempLength) System.arraycopy(_temp, 0, arr, 0, _tempLength) _builder += ByteString1(arr) _tempLength = 0 } - } private def resizeTemp(size: Int): Unit = { val newtemp = new Array[Byte](size) @@ -1218,13 +1193,12 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { private def shouldResizeTempFor(size: Int): Boolean = _tempCapacity < size || _tempCapacity == 0 - private def ensureTempSize(size: Int): Unit = { + private def ensureTempSize(size: Int): Unit = if (shouldResizeTempFor(size)) { var newSize = if (_tempCapacity == 0) 16 else _tempCapacity * 2 while (newSize < size) newSize *= 2 resizeTemp(newSize) } - } // We'd really like to have this overload to prevent boxing, but it's forbidden because sc.mutable.Growable makes // it final. I guess it assumes to prevent the boxing overhead by using @inline but that doesn't seem to be true. @@ -1303,7 +1277,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { /** * Add a single Short to this builder. */ - def putShort(x: Int)(implicit byteOrder: ByteOrder): this.type = { + def putShort(x: Int)(implicit byteOrder: ByteOrder): this.type = if (byteOrder == ByteOrder.BIG_ENDIAN) { this += (x >>> 8).toByte this += (x >>> 0).toByte @@ -1311,7 +1285,6 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { this += (x >>> 0).toByte this += (x >>> 8).toByte } else throw new IllegalArgumentException("Unknown byte order " + byteOrder) - } /** * Add a single Int to this builder. @@ -1364,7 +1337,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { /** * Add the `n` least significant bytes of the given Long to this builder. */ - def putLongPart(x: Long, n: Int)(implicit byteOrder: ByteOrder): this.type = { + def putLongPart(x: Long, n: Int)(implicit byteOrder: ByteOrder): this.type = fillArray(n) { (target, offset) => if (byteOrder == ByteOrder.BIG_ENDIAN) { val start = n * 8 - 8 @@ -1377,7 +1350,6 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { } } else throw new IllegalArgumentException("Unknown byte order " + byteOrder) } - } /** * Add a single Float to this builder. @@ -1413,7 +1385,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { * Add a number of Shorts from an array to this builder. */ def putShorts(array: Array[Short], start: Int, len: Int)(implicit byteOrder: ByteOrder): this.type = - fillByteBuffer(len * 2, byteOrder) { _.asShortBuffer.put(array, start, len) } + fillByteBuffer(len * 2, byteOrder)(_.asShortBuffer.put(array, start, len)) /** * Add a number of Ints from an array to this builder. @@ -1425,7 +1397,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { * Add a number of Ints from an array to this builder. */ def putInts(array: Array[Int], start: Int, len: Int)(implicit byteOrder: ByteOrder): this.type = - fillByteBuffer(len * 4, byteOrder) { _.asIntBuffer.put(array, start, len) } + fillByteBuffer(len * 4, byteOrder)(_.asIntBuffer.put(array, start, len)) /** * Add a number of Longs from an array to this builder. @@ -1437,7 +1409,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { * Add a number of Longs from an array to this builder. */ def putLongs(array: Array[Long], start: Int, len: Int)(implicit byteOrder: ByteOrder): this.type = - fillByteBuffer(len * 8, byteOrder) { _.asLongBuffer.put(array, start, len) } + fillByteBuffer(len * 8, byteOrder)(_.asLongBuffer.put(array, start, len)) /** * Add a number of Floats from an array to this builder. @@ -1449,7 +1421,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { * Add a number of Floats from an array to this builder. */ def putFloats(array: Array[Float], start: Int, len: Int)(implicit byteOrder: ByteOrder): this.type = - fillByteBuffer(len * 4, byteOrder) { _.asFloatBuffer.put(array, start, len) } + fillByteBuffer(len * 4, byteOrder)(_.asFloatBuffer.put(array, start, len)) /** * Add a number of Doubles from an array to this builder. @@ -1461,7 +1433,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { * Add a number of Doubles from an array to this builder. */ def putDoubles(array: Array[Double], start: Int, len: Int)(implicit byteOrder: ByteOrder): this.type = - fillByteBuffer(len * 8, byteOrder) { _.asDoubleBuffer.put(array, start, len) } + fillByteBuffer(len * 8, byteOrder)(_.asDoubleBuffer.put(array, start, len)) def clear(): Unit = { _builder.clear() @@ -1487,7 +1459,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { def asOutputStream: java.io.OutputStream = new java.io.OutputStream { def write(b: Int): Unit = builder += b.toByte - override def write(b: Array[Byte], off: Int, len: Int): Unit = { builder.putBytes(b, off, len) } + override def write(b: Array[Byte], off: Int, len: Int): Unit = builder.putBytes(b, off, len) } /** diff --git a/actor/src/main/scala-3/org/apache/pekko/util/ByteIterator.scala b/actor/src/main/scala-3/org/apache/pekko/util/ByteIterator.scala index 42d1d83e6aa..1a061afcbe5 100644 --- a/actor/src/main/scala-3/org/apache/pekko/util/ByteIterator.scala +++ b/actor/src/main/scala-3/org/apache/pekko/util/ByteIterator.scala @@ -45,12 +45,11 @@ object ByteIterator { final def head: Byte = array(from) - final def next(): Byte = { + final def next(): Byte = if (!hasNext) EmptyImmutableSeq.iterator.next() else { val i = from; from = from + 1; array(i) } - } def clear(): Unit = { this.array = Array.emptyByteArray; from = 0; until = from } @@ -80,12 +79,12 @@ object ByteIterator { final override def clone: ByteArrayIterator = new ByteArrayIterator(array, from, until) final override def take(n: Int): this.type = { - if (n < len) until = { if (n > 0) from + n else from } + if (n < len) until = if (n > 0) from + n else from this } final override def drop(n: Int): this.type = { - if (n > 0) from = { if (n < len) from + n else until } + if (n > 0) from = if (n < len) from + n else until this } @@ -98,13 +97,12 @@ object ByteIterator { final override def dropWhile(p: Byte => Boolean): this.type = { var stop = false - while (!stop && hasNext) { + while (!stop && hasNext) if (p(array(from))) { from = from + 1 } else { stop = true } - } this } @@ -130,12 +128,11 @@ object ByteIterator { } @throws[NoSuchElementException] - def getBytes(xs: Array[Byte], offset: Int, n: Int): this.type = { + def getBytes(xs: Array[Byte], offset: Int, n: Int): this.type = if (n <= this.len) { System.arraycopy(this.array, this.from, xs, offset, n) this.drop(n) } else throw new NoSuchElementException("next on empty iterator") - } private def wrappedByteBuffer: ByteBuffer = ByteBuffer.wrap(array, from, len).asReadOnlyBuffer @@ -205,19 +202,18 @@ object ByteIterator { // * iterators.isEmpty == false // * (!iterator.head.isEmpty || iterators.tail.isEmpty) == true private def normalize(): this.type = { - @tailrec def norm(xs: LinearSeq[ByteArrayIterator]): LinearSeq[ByteArrayIterator] = { + @tailrec def norm(xs: LinearSeq[ByteArrayIterator]): LinearSeq[ByteArrayIterator] = if (xs.isEmpty) MultiByteArrayIterator.clearedList else if (xs.head.isEmpty) norm(xs.tail) else xs - } iterators = norm(iterators) this } normalize() private def current: ByteArrayIterator = iterators.head - private def dropCurrent(): Unit = { iterators = iterators.tail } - def clear(): Unit = { iterators = MultiByteArrayIterator.empty.iterators } + private def dropCurrent(): Unit = iterators = iterators.tail + def clear(): Unit = iterators = MultiByteArrayIterator.empty.iterators final def hasNext: Boolean = current.hasNext @@ -229,7 +225,7 @@ object ByteIterator { result } - final override def len: Int = iterators.foldLeft(0) { _ + _.len } + final override def len: Int = iterators.foldLeft(0)(_ + _.len) final override def size: Int = { val result = len @@ -332,18 +328,17 @@ object ByteIterator { } override def foreach[@specialized U](f: Byte => U): Unit = { - iterators.foreach { _.foreach(f) } + iterators.foreach(_.foreach(f)) clear() } - final override def toByteString: ByteString = { + final override def toByteString: ByteString = if (iterators.tail.isEmpty) iterators.head.toByteString else { - val result = iterators.foldLeft(ByteString.empty) { _ ++ _.toByteString } + val result = iterators.foldLeft(ByteString.empty)(_ ++ _.toByteString) clear() result } - } @tailrec protected final def getToArray[A](xs: Array[A], offset: Int, n: Int, elemSize: Int)(getSingle: => A)( getMult: (Array[A], Int, Int) => Unit): this.type = @@ -363,27 +358,27 @@ object ByteIterator { } def getBytes(xs: Array[Byte], offset: Int, n: Int): this.type = - getToArray(xs, offset, n, 1) { getByte } { current.getBytes(_, _, _) } + getToArray(xs, offset, n, 1)(getByte)(current.getBytes(_, _, _)) def getShorts(xs: Array[Short], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type = - getToArray(xs, offset, n, 2) { getShort(byteOrder) } { current.getShorts(_, _, _)(byteOrder) } + getToArray(xs, offset, n, 2)(getShort(byteOrder))(current.getShorts(_, _, _)(byteOrder)) def getInts(xs: Array[Int], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type = - getToArray(xs, offset, n, 4) { getInt(byteOrder) } { current.getInts(_, _, _)(byteOrder) } + getToArray(xs, offset, n, 4)(getInt(byteOrder))(current.getInts(_, _, _)(byteOrder)) def getLongs(xs: Array[Long], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type = - getToArray(xs, offset, n, 8) { getLong(byteOrder) } { current.getLongs(_, _, _)(byteOrder) } + getToArray(xs, offset, n, 8)(getLong(byteOrder))(current.getLongs(_, _, _)(byteOrder)) def getFloats(xs: Array[Float], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type = - getToArray(xs, offset, n, 8) { getFloat(byteOrder) } { current.getFloats(_, _, _)(byteOrder) } + getToArray(xs, offset, n, 8)(getFloat(byteOrder))(current.getFloats(_, _, _)(byteOrder)) def getDoubles(xs: Array[Double], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type = - getToArray(xs, offset, n, 8) { getDouble(byteOrder) } { current.getDoubles(_, _, _)(byteOrder) } + getToArray(xs, offset, n, 8)(getDouble(byteOrder))(current.getDoubles(_, _, _)(byteOrder)) /** For performance sensitive code, call copyToBuffer() directly on ByteString (it's optimised there) */ override def copyToBuffer(buffer: ByteBuffer): Int = { // the fold here is better than indexing into the LinearSeq - val n = iterators.foldLeft(0) { _ + _.copyToBuffer(buffer) } + val n = iterators.foldLeft(0)(_ + _.copyToBuffer(buffer)) normalize() n } @@ -456,10 +451,9 @@ abstract class ByteIterator extends BufferedIterator[Byte] { override def drop(n: Int): this.type = throw new UnsupportedOperationException("Method drop is not implemented in ByteIterator") - override def slice(from: Int, until: Int): this.type = { + override def slice(from: Int, until: Int): this.type = if (from > 0) drop(from).take(until - from) else take(until) - } // *must* be overridden by derived classes. This construction is necessary // to specialize the return type, as the method is already implemented in @@ -530,18 +524,17 @@ abstract class ByteIterator extends BufferedIterator[Byte] { /** * Get a single Short from this iterator. */ - def getShort(implicit byteOrder: ByteOrder): Short = { + def getShort(implicit byteOrder: ByteOrder): Short = if (byteOrder == ByteOrder.BIG_ENDIAN) ((next() & 0xFF) << 8 | (next() & 0xFF) << 0).toShort else if (byteOrder == ByteOrder.LITTLE_ENDIAN) ((next() & 0xFF) << 0 | (next() & 0xFF) << 8).toShort else throw new IllegalArgumentException("Unknown byte order " + byteOrder) - } /** * Get a single Int from this iterator. */ - def getInt(implicit byteOrder: ByteOrder): Int = { + def getInt(implicit byteOrder: ByteOrder): Int = if (byteOrder == ByteOrder.BIG_ENDIAN) ((next() & 0xFF) << 24 | (next() & 0xFF) << 16 @@ -553,12 +546,11 @@ abstract class ByteIterator extends BufferedIterator[Byte] { | (next() & 0xFF) << 16 | (next() & 0xFF) << 24) else throw new IllegalArgumentException("Unknown byte order " + byteOrder) - } /** * Get a single Long from this iterator. */ - def getLong(implicit byteOrder: ByteOrder): Long = { + def getLong(implicit byteOrder: ByteOrder): Long = if (byteOrder == ByteOrder.BIG_ENDIAN) ((next().toLong & 0xFF) << 56 | (next().toLong & 0xFF) << 48 @@ -578,13 +570,12 @@ abstract class ByteIterator extends BufferedIterator[Byte] { | (next().toLong & 0xFF) << 48 | (next().toLong & 0xFF) << 56) else throw new IllegalArgumentException("Unknown byte order " + byteOrder) - } /** * Get a Long from this iterator where only the least significant `n` * bytes were encoded. */ - def getLongPart(n: Int)(implicit byteOrder: ByteOrder): Long = { + def getLongPart(n: Int)(implicit byteOrder: ByteOrder): Long = if (byteOrder == ByteOrder.BIG_ENDIAN) { var x = 0L (1 to n).foreach(_ => x = (x << 8) | (next() & 0xFF)) @@ -594,7 +585,6 @@ abstract class ByteIterator extends BufferedIterator[Byte] { (0 until n).foreach(i => x |= (next() & 0xFF) << 8 * i) x } else throw new IllegalArgumentException("Unknown byte order " + byteOrder) - } def getFloat(implicit byteOrder: ByteOrder): Float = java.lang.Float.intBitsToFloat(getInt(byteOrder)) diff --git a/actor/src/main/scala-3/org/apache/pekko/util/ByteString.scala b/actor/src/main/scala-3/org/apache/pekko/util/ByteString.scala index 7aba8dc5151..4cecdabc119 100644 --- a/actor/src/main/scala-3/org/apache/pekko/util/ByteString.scala +++ b/actor/src/main/scala-3/org/apache/pekko/util/ByteString.scala @@ -212,11 +212,10 @@ object ByteString { override def encodeBase64: ByteString = if (isEmpty) this else ByteString1C(Base64.getEncoder.encode(bytes)) - override def ++(that: ByteString): ByteString = { + override def ++(that: ByteString): ByteString = if (that.isEmpty) this else if (this.isEmpty) that else toByteString1 ++ that - } override def take(n: Int): ByteString = if (n <= 0) ByteString.empty @@ -231,7 +230,7 @@ object ByteString { if (n <= 0) this else toByteString1.drop(n) - override def indexOf[B >: Byte](elem: B, from: Int): Int = { + override def indexOf[B >: Byte](elem: B, from: Int): Int = if (from >= length) -1 else { var found = -1 @@ -242,9 +241,8 @@ object ByteString { } found } - } - override def indexOf(elem: Byte, from: Int): Int = { + override def indexOf(elem: Byte, from: Int): Int = if (from >= length) -1 else { var found = -1 @@ -255,7 +253,6 @@ object ByteString { } found } - } override def slice(from: Int, until: Int): ByteString = if (from <= 0 && until >= length) this @@ -278,9 +275,8 @@ object ByteString { } /** INTERNAL API: Specialized for internal use, appending ByteString1C to a ByteStringBuilder. */ - private[pekko] def appendToBuilder(buffer: ByteStringBuilder) = { + private[pekko] def appendToBuilder(buffer: ByteStringBuilder) = buffer.putByteArrayUnsafe(bytes) - } override def copyToArray[B >: Byte](dest: Array[B], start: Int, len: Int): Int = { val toCopy = math.min(math.min(len, bytes.length), dest.length - start) @@ -323,12 +319,11 @@ object ByteString { override def iterator: ByteIterator.ByteArrayIterator = ByteIterator.ByteArrayIterator(bytes, startIndex, startIndex + length) - private def checkRangeConvert(index: Int): Int = { + private def checkRangeConvert(index: Int): Int = if (0 <= index && length > index) index + startIndex else throw new IndexOutOfBoundsException(index.toString) - } private[pekko] def writeToOutputStream(os: ObjectOutputStream): Unit = { os.writeInt(length) @@ -421,7 +416,7 @@ object ByteString { } else CompactByteString(dst) } - def ++(that: ByteString): ByteString = { + def ++(that: ByteString): ByteString = if (that.isEmpty) this else if (this.isEmpty) that else @@ -433,9 +428,8 @@ object ByteString { else ByteStrings(this, b) case bs: ByteStrings => ByteStrings(this, bs) } - } - override def indexOf[B >: Byte](elem: B, from: Int): Int = { + override def indexOf[B >: Byte](elem: B, from: Int): Int = if (from >= length) -1 else { var found = -1 @@ -446,9 +440,8 @@ object ByteString { } found } - } - override def indexOf(elem: Byte, from: Int): Int = { + override def indexOf(elem: Byte, from: Int): Int = if (from >= length) -1 else { var found = -1 @@ -459,7 +452,6 @@ object ByteString { } found } - } override def copyToArray[B >: Byte](dest: Array[B], start: Int, len: Int): Int = { // min of the bytes available to copy, bytes there is room for in dest and the requested number of bytes @@ -472,10 +464,9 @@ object ByteString { protected def writeReplace(): AnyRef = new SerializationProxy(this) - override def toArrayUnsafe(): Array[Byte] = { + override def toArrayUnsafe(): Array[Byte] = if (startIndex == 0 && length == bytes.length) bytes else toArray - } override def asInputStream: InputStream = new ByteArrayInputStream(bytes, startIndex, length) @@ -551,7 +542,7 @@ object ByteString { if (bytestrings.isEmpty) throw new IllegalArgumentException("bytestrings must not be empty") if (bytestrings.head.isEmpty) throw new IllegalArgumentException("bytestrings.head must not be empty") - def apply(idx: Int): Byte = { + def apply(idx: Int): Byte = if (0 <= idx && idx < length) { var pos = 0 var seen = 0 @@ -563,13 +554,12 @@ object ByteString { } frag(idx - seen) } else throw new IndexOutOfBoundsException(idx.toString) - } /** Avoid `iterator` in performance sensitive code, call ops directly on ByteString instead */ override def iterator: ByteIterator.MultiByteArrayIterator = - ByteIterator.MultiByteArrayIterator(bytestrings.to(LazyList).map { _.iterator }) + ByteIterator.MultiByteArrayIterator(bytestrings.to(LazyList).map(_.iterator)) - def ++(that: ByteString): ByteString = { + def ++(that: ByteString): ByteString = if (that.isEmpty) this else if (this.isEmpty) that else @@ -578,7 +568,6 @@ object ByteString { case b: ByteString1 => ByteStrings(this, b) case bs: ByteStrings => ByteStrings(this, bs) } - } private[pekko] def byteStringCompanion = ByteStrings @@ -592,7 +581,7 @@ object ByteString { copyItToTheBuffer(buffer, 0, 0) } - def compact: CompactByteString = { + def compact: CompactByteString = if (isCompact) bytestrings.head.compact else { val ar = new Array[Byte](length) @@ -603,11 +592,10 @@ object ByteString { } ByteString1C(ar) } - } def asByteBuffer: ByteBuffer = compact.asByteBuffer - def asByteBuffers: scala.collection.immutable.Iterable[ByteBuffer] = bytestrings.map { _.asByteBuffer } + def asByteBuffers: scala.collection.immutable.Iterable[ByteBuffer] = bytestrings.map(_.asByteBuffer) override def asInputStream: InputStream = new SequenceInputStream(bytestrings.iterator.map(_.asInputStream).asJavaEnumeration) @@ -702,13 +690,13 @@ object ByteString { new ByteStrings(bytestrings(fullDrops).drop1(remainingToDrop) +: bytestrings.drop(fullDrops + 1), length - n) } - override def indexOf[B >: Byte](elem: B, from: Int): Int = { + override def indexOf[B >: Byte](elem: B, from: Int): Int = if (from >= length) -1 else { val byteStringsSize = bytestrings.size @tailrec - def find(bsIdx: Int, relativeIndex: Int, bytesPassed: Int): Int = { + def find(bsIdx: Int, relativeIndex: Int, bytesPassed: Int): Int = if (bsIdx >= byteStringsSize) -1 else { val bs = bytestrings(bsIdx) @@ -722,19 +710,17 @@ object ByteString { } else subIndexOf + bytesPassed } } - } find(0, math.max(from, 0), 0) } - } - override def indexOf(elem: Byte, from: Int): Int = { + override def indexOf(elem: Byte, from: Int): Int = if (from >= length) -1 else { val byteStringsSize = bytestrings.size @tailrec - def find(bsIdx: Int, relativeIndex: Int, bytesPassed: Int): Int = { + def find(bsIdx: Int, relativeIndex: Int, bytesPassed: Int): Int = if (bsIdx >= byteStringsSize) -1 else { val bs = bytestrings(bsIdx) @@ -748,13 +734,11 @@ object ByteString { } else subIndexOf + bytesPassed } } - } find(0, math.max(from, 0), 0) } - } - override def copyToArray[B >: Byte](dest: Array[B], start: Int, len: Int): Int = { + override def copyToArray[B >: Byte](dest: Array[B], start: Int, len: Int): Int = if (bytestrings.size == 1) bytestrings.head.copyToArray(dest, start, len) else { // min of the bytes available to copy, bytes there is room for in dest and the requested number of bytes @@ -769,7 +753,6 @@ object ByteString { } totalToCopy } - } protected def writeReplace(): AnyRef = new SerializationProxy(this) } @@ -932,10 +915,9 @@ sealed abstract class ByteString array } - final override def copyToArray[B >: Byte](xs: Array[B], start: Int): Int = { + final override def copyToArray[B >: Byte](xs: Array[B], start: Int): Int = // super uses byteiterator copyToArray(xs, start, size.min(xs.size)) - } // optimized in all subclasses, avoiding usage of the iterator to save allocations/transformations override def copyToArray[B >: Byte](xs: Array[B], start: Int, len: Int): Int = @@ -1024,9 +1006,8 @@ sealed abstract class ByteString * Java API: Returns an Iterable of read-only ByteBuffers that directly wraps this ByteStrings * all fragments. Will always have at least one entry. */ - def getByteBuffers(): JIterable[ByteBuffer] = { + def getByteBuffers(): JIterable[ByteBuffer] = asByteBuffers.asJava - } /** * Creates a new ByteBuffer with a copy of all bytes contained in this @@ -1081,14 +1062,13 @@ object CompactByteString { /** * Creates a new CompactByteString by copying bytes. */ - def apply(bytes: Byte*): CompactByteString = { + def apply(bytes: Byte*): CompactByteString = if (bytes.isEmpty) empty else { val ar = new Array[Byte](bytes.size) bytes.copyToArray(ar) ByteString.ByteString1C(ar) } - } /** * Creates a new CompactByteString by traversing bytes. @@ -1102,22 +1082,20 @@ object CompactByteString { /** * Creates a new CompactByteString by converting from integral numbers to bytes. */ - def apply[T](bytes: T*)(implicit num: Integral[T]): CompactByteString = { + def apply[T](bytes: T*)(implicit num: Integral[T]): CompactByteString = if (bytes.isEmpty) empty else ByteString.ByteString1C(bytes.iterator.map(x => num.toInt(x).toByte).to(Array)) - } /** * Creates a new CompactByteString by copying bytes from a ByteBuffer. */ - def apply(bytes: ByteBuffer): CompactByteString = { + def apply(bytes: ByteBuffer): CompactByteString = if (bytes.remaining < 1) empty else { val ar = new Array[Byte](bytes.remaining) bytes.get(ar) ByteString.ByteString1C(ar) } - } /** * Creates a new CompactByteString by encoding a String as UTF-8. @@ -1188,29 +1166,26 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { this } - protected final def fillByteBuffer(len: Int, byteOrder: ByteOrder)(fill: ByteBuffer => Unit): this.type = { + protected final def fillByteBuffer(len: Int, byteOrder: ByteOrder)(fill: ByteBuffer => Unit): this.type = fillArray(len) { case (array, start) => val buffer = ByteBuffer.wrap(array, start, len) buffer.order(byteOrder) fill(buffer) } - } def length: Int = _length - override def sizeHint(len: Int): Unit = { + override def sizeHint(len: Int): Unit = resizeTemp(len - (_length - _tempLength)) - } - private def clearTemp(): Unit = { + private def clearTemp(): Unit = if (_tempLength > 0) { val arr = new Array[Byte](_tempLength) System.arraycopy(_temp, 0, arr, 0, _tempLength) _builder += ByteString1(arr) _tempLength = 0 } - } private def resizeTemp(size: Int): Unit = { val newtemp = new Array[Byte](size) @@ -1221,13 +1196,12 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { private def shouldResizeTempFor(size: Int): Boolean = _tempCapacity < size || _tempCapacity == 0 - private def ensureTempSize(size: Int): Unit = { + private def ensureTempSize(size: Int): Unit = if (shouldResizeTempFor(size)) { var newSize = if (_tempCapacity == 0) 16 else _tempCapacity * 2 while (newSize < size) newSize *= 2 resizeTemp(newSize) } - } // We'd really like to have this overload to prevent boxing, but it's forbidden because sc.mutable.Growable makes // it final. I guess it assumes to prevent the boxing overhead by using @inline but that doesn't seem to be true. @@ -1306,7 +1280,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { /** * Add a single Short to this builder. */ - def putShort(x: Int)(implicit byteOrder: ByteOrder): this.type = { + def putShort(x: Int)(implicit byteOrder: ByteOrder): this.type = if (byteOrder == ByteOrder.BIG_ENDIAN) { this += (x >>> 8).toByte this += (x >>> 0).toByte @@ -1314,7 +1288,6 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { this += (x >>> 0).toByte this += (x >>> 8).toByte } else throw new IllegalArgumentException("Unknown byte order " + byteOrder) - } /** * Add a single Int to this builder. @@ -1367,7 +1340,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { /** * Add the `n` least significant bytes of the given Long to this builder. */ - def putLongPart(x: Long, n: Int)(implicit byteOrder: ByteOrder): this.type = { + def putLongPart(x: Long, n: Int)(implicit byteOrder: ByteOrder): this.type = fillArray(n) { (target, offset) => if (byteOrder == ByteOrder.BIG_ENDIAN) { val start = n * 8 - 8 @@ -1380,7 +1353,6 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { } } else throw new IllegalArgumentException("Unknown byte order " + byteOrder) } - } /** * Add a single Float to this builder. @@ -1416,7 +1388,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { * Add a number of Shorts from an array to this builder. */ def putShorts(array: Array[Short], start: Int, len: Int)(implicit byteOrder: ByteOrder): this.type = - fillByteBuffer(len * 2, byteOrder) { _.asShortBuffer.put(array, start, len) } + fillByteBuffer(len * 2, byteOrder)(_.asShortBuffer.put(array, start, len)) /** * Add a number of Ints from an array to this builder. @@ -1428,7 +1400,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { * Add a number of Ints from an array to this builder. */ def putInts(array: Array[Int], start: Int, len: Int)(implicit byteOrder: ByteOrder): this.type = - fillByteBuffer(len * 4, byteOrder) { _.asIntBuffer.put(array, start, len) } + fillByteBuffer(len * 4, byteOrder)(_.asIntBuffer.put(array, start, len)) /** * Add a number of Longs from an array to this builder. @@ -1440,7 +1412,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { * Add a number of Longs from an array to this builder. */ def putLongs(array: Array[Long], start: Int, len: Int)(implicit byteOrder: ByteOrder): this.type = - fillByteBuffer(len * 8, byteOrder) { _.asLongBuffer.put(array, start, len) } + fillByteBuffer(len * 8, byteOrder)(_.asLongBuffer.put(array, start, len)) /** * Add a number of Floats from an array to this builder. @@ -1452,7 +1424,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { * Add a number of Floats from an array to this builder. */ def putFloats(array: Array[Float], start: Int, len: Int)(implicit byteOrder: ByteOrder): this.type = - fillByteBuffer(len * 4, byteOrder) { _.asFloatBuffer.put(array, start, len) } + fillByteBuffer(len * 4, byteOrder)(_.asFloatBuffer.put(array, start, len)) /** * Add a number of Doubles from an array to this builder. @@ -1464,7 +1436,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { * Add a number of Doubles from an array to this builder. */ def putDoubles(array: Array[Double], start: Int, len: Int)(implicit byteOrder: ByteOrder): this.type = - fillByteBuffer(len * 8, byteOrder) { _.asDoubleBuffer.put(array, start, len) } + fillByteBuffer(len * 8, byteOrder)(_.asDoubleBuffer.put(array, start, len)) def clear(): Unit = { _builder.clear() @@ -1490,7 +1462,7 @@ final class ByteStringBuilder extends Builder[Byte, ByteString] { def asOutputStream: java.io.OutputStream = new java.io.OutputStream { def write(b: Int): Unit = builder += b.toByte - override def write(b: Array[Byte], off: Int, len: Int): Unit = { builder.putBytes(b, off, len) } + override def write(b: Array[Byte], off: Int, len: Int): Unit = builder.putBytes(b, off, len) } /** diff --git a/actor/src/main/scala/org/apache/pekko/Main.scala b/actor/src/main/scala/org/apache/pekko/Main.scala index 414b00da52a..4b8efdc0cb1 100644 --- a/actor/src/main/scala/org/apache/pekko/Main.scala +++ b/actor/src/main/scala/org/apache/pekko/Main.scala @@ -35,7 +35,7 @@ object Main { /** * @param args one argument: the class of the application supervisor actor */ - def main(args: Array[String]): Unit = { + def main(args: Array[String]): Unit = if (args.length != 1) { println("you need to provide exactly one argument: the class of the application supervisor actor") } else { @@ -48,7 +48,6 @@ object Main { case NonFatal(e) => system.terminate(); throw e } } - } class Terminator(app: ActorRef) extends Actor with ActorLogging { context.watch(app) diff --git a/actor/src/main/scala/org/apache/pekko/PekkoVersion.scala b/actor/src/main/scala/org/apache/pekko/PekkoVersion.scala index c7fab1dcb24..ab48d319991 100644 --- a/actor/src/main/scala/org/apache/pekko/PekkoVersion.scala +++ b/actor/src/main/scala/org/apache/pekko/PekkoVersion.scala @@ -29,15 +29,14 @@ object PekkoVersion { * @param libraryName The name of the library or component requiring the Pekko version, used in the error message. * @param requiredVersion Minimal version that this library works with */ - def require(libraryName: String, requiredVersion: String): Unit = { + def require(libraryName: String, requiredVersion: String): Unit = require(libraryName, requiredVersion, Version.current) - } /** * Internal API: */ @InternalApi - private[pekko] def require(libraryName: String, requiredVersion: String, currentVersion: String): Unit = { + private[pekko] def require(libraryName: String, requiredVersion: String, currentVersion: String): Unit = if (requiredVersion != currentVersion) { val VersionPattern = """(\d+)\.(\d+)\.(\d+)(-(?:M|RC)\d+)?""".r currentVersion match { @@ -59,6 +58,5 @@ object PekkoVersion { case _ => // SNAPSHOT or unknown - you're on your own } } - } } diff --git a/actor/src/main/scala/org/apache/pekko/actor/AbstractFSM.scala b/actor/src/main/scala/org/apache/pekko/actor/AbstractFSM.scala index d9b63c6a3e2..4b9ad682559 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/AbstractFSM.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/AbstractFSM.scala @@ -122,9 +122,8 @@ abstract class AbstractFSM[S, D] extends FSM[S, D] { final def when( stateName: S, stateTimeout: java.time.Duration, - stateFunctionBuilder: FSMStateFunctionBuilder[S, D]): Unit = { + stateFunctionBuilder: FSMStateFunctionBuilder[S, D]): Unit = when(stateName, stateTimeout.asScala, stateFunctionBuilder) - } /** * Set initial state. Call this method from the constructor before the [[initialize]] method. @@ -158,9 +157,8 @@ abstract class AbstractFSM[S, D] extends FSM[S, D] { * @param stateData initial state data * @param timeout state timeout for the initial state, overriding the default timeout for that state */ - final def startWith(stateName: S, stateData: D, timeout: java.time.Duration): Unit = { + final def startWith(stateName: S, stateData: D, timeout: java.time.Duration): Unit = startWith(stateName, stateData, timeout.asScala) - } /** * Add a handler which is called upon each state transition, i.e. not when @@ -524,9 +522,8 @@ abstract class AbstractFSM[S, D] extends FSM[S, D] { * @param timeout delay of first message delivery and between subsequent messages */ @deprecated("Use startSingleTimer instead.", since = "Akka 2.6.0") - final def setTimer(name: String, msg: Any, timeout: java.time.Duration): Unit = { + final def setTimer(name: String, msg: Any, timeout: java.time.Duration): Unit = setTimer(name, msg, timeout.asScala, false) - } /** * Schedule named timer to deliver message after given delay, possibly repeating. @@ -541,9 +538,8 @@ abstract class AbstractFSM[S, D] extends FSM[S, D] { "Use startSingleTimer, startTimerWithFixedDelay or startTimerAtFixedRate instead. This has the same semantics as " + "startTimerAtFixedRate, but startTimerWithFixedDelay is often preferred.", since = "Akka 2.6.0") - final def setTimer(name: String, msg: Any, timeout: java.time.Duration, repeat: Boolean): Unit = { + final def setTimer(name: String, msg: Any, timeout: java.time.Duration, repeat: Boolean): Unit = setTimer(name, msg, timeout.asScala, repeat) - } /** * Default reason if calling `stop()`. diff --git a/actor/src/main/scala/org/apache/pekko/actor/AbstractProps.scala b/actor/src/main/scala/org/apache/pekko/actor/AbstractProps.scala index b8f9a4d77ca..5297c40fda5 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/AbstractProps.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/AbstractProps.scala @@ -31,7 +31,7 @@ private[pekko] trait AbstractProps { /** * INTERNAL API */ - private[pekko] def validate(clazz: Class[_]): Unit = { + private[pekko] def validate(clazz: Class[_]): Unit = if (Modifier.isAbstract(clazz.getModifiers)) { throw new IllegalArgumentException(s"Actor class [${clazz.getName}] must not be abstract") } else if (!classOf[Actor].isAssignableFrom(clazz) && @@ -39,7 +39,6 @@ private[pekko] trait AbstractProps { throw new IllegalArgumentException( s"Actor class [${clazz.getName}] must be subClass of org.apache.pekko.actor.Actor or org.apache.pekko.actor.IndirectActorProducer.") } - } /** * Java API: create a Props given a class and its constructor arguments. @@ -93,7 +92,7 @@ private[pekko] trait AbstractProps { val enclosingClass = clazz.getEnclosingClass def hasDeclaredConstructorWithEmptyParams(declaredConstructors: Array[Constructor[_]]): Boolean = { - @tailrec def loop(i: Int): Boolean = { + @tailrec def loop(i: Int): Boolean = if (i == declaredConstructors.length) false else { if (declaredConstructors(i).getParameterCount == 0) @@ -101,12 +100,11 @@ private[pekko] trait AbstractProps { else loop(i + 1) // recur } - } loop(0) } def hasDeclaredConstructorWithEnclosingClassParam(declaredConstructors: Array[Constructor[_]]): Boolean = { - @tailrec def loop(i: Int): Boolean = { + @tailrec def loop(i: Int): Boolean = if (i == declaredConstructors.length) false else { val c = declaredConstructors(i) @@ -115,7 +113,6 @@ private[pekko] trait AbstractProps { else loop(i + 1) // recur } - } loop(0) } diff --git a/actor/src/main/scala/org/apache/pekko/actor/Actor.scala b/actor/src/main/scala/org/apache/pekko/actor/Actor.scala index b0bfad7ad15..c9fd4141c7b 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/Actor.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/Actor.scala @@ -376,9 +376,8 @@ trait DiagnosticActorLogging extends Actor { try { log.mdc(mdc(msg)) super.aroundReceive(receive, msg) - } finally { + } finally log.clearMDC() - } } object Actor { @@ -542,12 +541,11 @@ trait Actor { * @param msg current message. */ @InternalApi - protected[pekko] def aroundReceive(receive: Actor.Receive, msg: Any): Unit = { + protected[pekko] def aroundReceive(receive: Actor.Receive, msg: Any): Unit = // optimization: avoid allocation of lambda if (receive.applyOrElse(msg, Actor.notHandledFun).asInstanceOf[AnyRef] eq Actor.NotHandled) { unhandled(msg) } - } /** * INTERNAL API. @@ -640,9 +638,8 @@ trait Actor { */ @throws(classOf[Exception]) // when changing this you MUST also change ActorDocTest // #lifecycle-hooks - def postRestart(@unused reason: Throwable): Unit = { + def postRestart(@unused reason: Throwable): Unit = preStart() - } // #lifecycle-hooks /** @@ -653,10 +650,9 @@ trait Actor { * case of an unhandled [[pekko.actor.Terminated]] message) or publishes an [[pekko.actor.UnhandledMessage]] * to the actor's system's [[pekko.event.EventStream]] */ - def unhandled(message: Any): Unit = { + def unhandled(message: Any): Unit = message match { case Terminated(dead) => throw DeathPactException(dead) case _ => context.system.eventStream.publish(UnhandledMessage(message, sender(), self)) } - } } diff --git a/actor/src/main/scala/org/apache/pekko/actor/ActorCell.scala b/actor/src/main/scala/org/apache/pekko/actor/ActorCell.scala index 26131a979cc..19fc18ae398 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/ActorCell.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/ActorCell.scala @@ -515,7 +515,7 @@ private[pekko] class ActorCell( val rest = messages.tail val message = messages.head message.unlink() - try { + try message match { case message: SystemMessage if shouldStash(message, currentState) => stash(message) case f: Failed => handleFailure(f) @@ -530,7 +530,7 @@ private[pekko] class ActorCell( case Supervise(child, async) => supervise(child, async) case NoMessage => // only here to suppress warning } - } catch handleNonFatalOrInterruptedException { e => + catch handleNonFatalOrInterruptedException { e => handleInvokeFailure(Nil, e) } val newState = calculateState @@ -646,7 +646,7 @@ private[pekko] class ActorCell( _actor = null // ensure that we know that we failed during creation } - failure.foreach { throw _ } + failure.foreach(throw _) try { val created = newActor() @@ -683,12 +683,11 @@ private[pekko] class ActorCell( } @tailrec - private def rootCauseOf(throwable: Throwable): Throwable = { + private def rootCauseOf(throwable: Throwable): Throwable = if (throwable.getCause != null && throwable.getCause != throwable) rootCauseOf(throwable.getCause) else throwable - } private def supervise(child: ActorRef, async: Boolean): Unit = if (!isTerminating) { diff --git a/actor/src/main/scala/org/apache/pekko/actor/ActorPath.scala b/actor/src/main/scala/org/apache/pekko/actor/ActorPath.scala index 71f0b09b083..37972f3f9cb 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/ActorPath.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/ActorPath.scala @@ -384,7 +384,7 @@ final class ChildActorPath private[pekko] (val parent: ActorPath, val name: Stri case c: ChildActorPath => c.toStringLength + 1 } - override def toStringWithAddress(addr: Address): String = { + override def toStringWithAddress(addr: Address): String = if (IgnoreActorRef.isIgnoreRefPath(this)) { // we never change address for IgnoreActorRef this.toString @@ -393,9 +393,8 @@ final class ChildActorPath private[pekko] (val parent: ActorPath, val name: Stri val length = toStringLength + diff buildToString(new JStringBuilder(length), length, diff, _.toStringWithAddress(addr)).toString } - } - override def toSerializationFormatWithAddress(addr: Address): String = { + override def toSerializationFormatWithAddress(addr: Address): String = if (IgnoreActorRef.isIgnoreRefPath(this)) { // we never change address for IgnoreActorRef this.toString @@ -405,7 +404,6 @@ final class ChildActorPath private[pekko] (val parent: ActorPath, val name: Stri val sb = buildToString(new JStringBuilder(length + 12), length, diff, _.toStringWithAddress(addr)) appendUidFragment(sb).toString } - } private def addressStringLengthDiff(address: Address): Int = { val r = root @@ -446,10 +444,9 @@ final class ChildActorPath private[pekko] (val parent: ActorPath, val name: Stri rec(this) } - private def appendUidFragment(sb: JStringBuilder): JStringBuilder = { + private def appendUidFragment(sb: JStringBuilder): JStringBuilder = if (uid == ActorCell.undefinedUid) sb else sb.append("#").append(uid) - } override def equals(other: Any): Boolean = { @tailrec diff --git a/actor/src/main/scala/org/apache/pekko/actor/ActorRef.scala b/actor/src/main/scala/org/apache/pekko/actor/ActorRef.scala index df2f8720d75..20932ef3458 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/ActorRef.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/ActorRef.scala @@ -172,10 +172,9 @@ abstract class ActorRef extends java.lang.Comparable[ActorRef] with Serializable @InternalApi private[pekko] def isTerminated: Boolean - final override def hashCode: Int = { + final override def hashCode: Int = if (path.uid == ActorCell.undefinedUid) path.hashCode else path.uid - } /** * Equals takes path and the unique id of the actor cell into account. @@ -471,9 +470,8 @@ private[pekko] class LocalActorRef private[pekko] ( private[pekko] final case class SerializedActorRef private (path: String) { import pekko.serialization.JavaSerializer.currentSystem - def this(actorRef: ActorRef) = { + def this(actorRef: ActorRef) = this(Serialization.serializedActorPath(actorRef)) - } @throws(classOf[java.io.ObjectStreamException]) def readResolve(): AnyRef = currentSystem.value match { @@ -490,9 +488,8 @@ private[pekko] final case class SerializedActorRef private (path: String) { * INTERNAL API */ private[pekko] object SerializedActorRef { - def apply(actorRef: ActorRef): SerializedActorRef = { + def apply(actorRef: ActorRef): SerializedActorRef = new SerializedActorRef(actorRef) - } } /** @@ -635,13 +632,12 @@ object WrappedMessage { /** * Unwrap [[WrappedMessage]] recursively. */ - @tailrec def unwrap(message: Any): Any = { + @tailrec def unwrap(message: Any): Any = message match { case w: WrappedMessage => unwrap(w.message) case _ => message } - } } /** @@ -719,9 +715,8 @@ private[pekko] class EmptyLocalActorRef( case _ => false } - private def publishSupressedDeadLetter(msg: DeadLetterSuppression, sender: ActorRef): Unit = { + private def publishSupressedDeadLetter(msg: DeadLetterSuppression, sender: ActorRef): Unit = eventStream.publish(SuppressedDeadLetter(msg, if (sender eq Actor.noSender) provider.deadLetters else sender, this)) - } } /** @@ -774,7 +769,7 @@ private[pekko] class VirtualPathContainer( * are supported, otherwise messages are sent to [[EmptyLocalActorRef]]. */ override def !(message: Any)(implicit sender: ActorRef = Actor.noSender): Unit = message match { - case sel @ ActorSelectionMessage(msg, elements, wildcardFanOut) => { + case sel @ ActorSelectionMessage(msg, elements, wildcardFanOut) => require(elements.nonEmpty) def emptyRef = @@ -800,11 +795,10 @@ private[pekko] class VirtualPathContainer( if (!wildcardFanOut) emptyRef.tell(msg, sender) } - } case _ => super.!(message) } - def addChild(name: String, ref: InternalActorRef): Unit = { + def addChild(name: String, ref: InternalActorRef): Unit = children.put(name, ref) match { case null => // okay case old => @@ -813,7 +807,6 @@ private[pekko] class VirtualPathContainer( log.debug("{} replacing child {} ({} -> {})", path, name, old, ref) old.stop() } - } def removeChild(name: String): Unit = if (children.remove(name) eq null) log.warning("{} trying to remove non-child {}", path, name) @@ -832,7 +825,7 @@ private[pekko] class VirtualPathContainer( def getChild(name: String): InternalActorRef = children.get(name) - override def getChild(name: Iterator[String]): InternalActorRef = { + override def getChild(name: Iterator[String]): InternalActorRef = if (name.isEmpty) this else { val n = name.next() @@ -845,7 +838,6 @@ private[pekko] class VirtualPathContainer( else some.getChild(name) } } - } def hasChildren: Boolean = !children.isEmpty @@ -893,14 +885,13 @@ private[pekko] class VirtualPathContainer( // var because it's replaced in `stop` private var messageHandler: (ActorRef, Any) => Unit = f - override def !(message: Any)(implicit sender: ActorRef = Actor.noSender): Unit = { + override def !(message: Any)(implicit sender: ActorRef = Actor.noSender): Unit = message match { case AddressTerminated(address) => addressTerminated(address) case _ => messageHandler(sender, message) } - } - override def sendSystemMessage(message: SystemMessage): Unit = { + override def sendSystemMessage(message: SystemMessage): Unit = message match { case w: Watch => addWatcher(w.watchee, w.watcher) case u: Unwatch => remWatcher(u.watchee, u.watcher) @@ -908,7 +899,6 @@ private[pekko] class VirtualPathContainer( this.!(Terminated(actorRef)(existenceConfirmed = true, addressTerminated = false))(actorRef) case _ => // ignore all other messages } - } // watching, _watchedBy and maintainAddressTerminatedSubscription requires synchronized access because // AddressTerminatedTopic must be updated together with the variables here. @@ -978,9 +968,8 @@ private[pekko] class VirtualPathContainer( // outside of synchronized block // send DeathWatchNotification to self for all matching subjects - for (a <- toNotify; if a.path.address == address) { + for (a <- toNotify; if a.path.address == address) this.sendSystemMessage(DeathWatchNotification(a, existenceConfirmed = false, addressTerminated = true)) - } } override def stop(): Unit = { diff --git a/actor/src/main/scala/org/apache/pekko/actor/ActorRefProvider.scala b/actor/src/main/scala/org/apache/pekko/actor/ActorRefProvider.scala index 79c0e7c811e..3a5416f1cf4 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/ActorRefProvider.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/ActorRefProvider.scala @@ -341,7 +341,7 @@ private[pekko] object LocalActorRefProvider { // termination hooks, they will reply with TerminationHookDone // and when all are done the systemGuardian is stopped context.become(terminating) - terminationHooks.foreach { _ ! TerminationHook } + terminationHooks.foreach(_ ! TerminationHook) stopWhenAllTerminationHooksDone() case Terminated(a) => // a registered, and watched termination hook terminated before @@ -626,7 +626,7 @@ private[pekko] class LocalActorRefProvider private[pekko] ( deadLetters } - def resolveActorRef(path: ActorPath): ActorRef = { + def resolveActorRef(path: ActorPath): ActorRef = if (path.root == rootPath) resolveActorRef(rootGuardian, path.elements) else { logDeser.debug( @@ -635,7 +635,6 @@ private[pekko] class LocalActorRefProvider private[pekko] ( rootPath) deadLetters } - } /** * INTERNAL API @@ -664,7 +663,7 @@ private[pekko] class LocalActorRefProvider private[pekko] ( systemService: Boolean, deploy: Option[Deploy], lookupDeploy: Boolean, - async: Boolean): InternalActorRef = { + async: Boolean): InternalActorRef = props.deploy.routerConfig match { case NoRouter => if (settings.DebugRouterMisconfiguration) { @@ -754,7 +753,6 @@ private[pekko] class LocalActorRefProvider private[pekko] ( e) } } - } def getExternalAddressFor(addr: Address): Option[Address] = if (addr == rootPath.address) Some(addr) else None @@ -780,7 +778,7 @@ private[pekko] class LocalActorRefProvider private[pekko] ( // lazily initialized with fallback since it can depend on transport which is not initialized up front // worth caching since if it is used once in a system it will very likely be used many times @volatile private var _addressString: OptionVal[String] = OptionVal.None - override private[pekko] def addressString: String = { + override private[pekko] def addressString: String = _addressString match { case OptionVal.Some(addr) => addr case _ => @@ -788,5 +786,4 @@ private[pekko] class LocalActorRefProvider private[pekko] ( _addressString = OptionVal.Some(addr) addr } - } } diff --git a/actor/src/main/scala/org/apache/pekko/actor/ActorSelection.scala b/actor/src/main/scala/org/apache/pekko/actor/ActorSelection.scala index 1747c218bff..bef3edf27e2 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/ActorSelection.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/ActorSelection.scala @@ -243,7 +243,7 @@ object ActorSelection { val iter = sel.elements.iterator - @tailrec def rec(ref: InternalActorRef): Unit = { + @tailrec def rec(ref: InternalActorRef): Unit = ref match { case refWithCell: ActorRefWithCell => def emptyRef = @@ -296,7 +296,6 @@ object ActorSelection { // foreign ref, continue by sending ActorSelectionMessage to it with remaining elements ref.tell(sel.copy(elements = iter.toVector), sender) } - } rec(anchor) } diff --git a/actor/src/main/scala/org/apache/pekko/actor/ActorSystem.scala b/actor/src/main/scala/org/apache/pekko/actor/ActorSystem.scala index e7b9f6aa676..23bed1587a2 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/ActorSystem.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/ActorSystem.scala @@ -51,9 +51,8 @@ object BootstrapSetup { * same as not passing any [[BootstrapSetup]] at all. You can use the returned instance to derive * one that has other values than defaults using the various `with`-methods. */ - def apply(): BootstrapSetup = { + def apply(): BootstrapSetup = new BootstrapSetup() - } /** * Scala API: Create bootstrap settings needed for starting the actor system @@ -92,9 +91,8 @@ object BootstrapSetup { * same as not passing any [[BootstrapSetup]] at all. You can use the returned instance to derive * one that has other values than defaults using the various `with`-methods. */ - def create(): BootstrapSetup = { + def create(): BootstrapSetup = new BootstrapSetup() - } } @@ -837,7 +835,7 @@ private[pekko] class ActorSystemImpl( protected def uncaughtExceptionHandler: Thread.UncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() { - def uncaughtException(thread: Thread, cause: Throwable): Unit = { + def uncaughtException(thread: Thread, cause: Throwable): Unit = cause match { case NonFatal(_) | _: InterruptedException | _: NotImplementedError | _: ControlThrowable => log.error(cause, "Uncaught error from thread [{}]", thread.getName) @@ -858,7 +856,6 @@ private[pekko] class ActorSystemImpl( try logFatalError("shutting down", cause, thread) finally terminate() } - } private def logFatalError(message: String, cause: Throwable, thread: Thread): Unit = { // First log to stderr as this has the best chance to get through in an 'emergency panic' situation: @@ -1061,8 +1058,8 @@ private[pekko] class ActorSystemImpl( } def start(): this.type = _start - def registerOnTermination[T](code: => T): Unit = { registerOnTermination(new Runnable { def run() = code }) } - def registerOnTermination(code: Runnable): Unit = { terminationCallbacks.add(code) } + def registerOnTermination[T](code: => T): Unit = registerOnTermination(new Runnable { def run() = code }) + def registerOnTermination(code: Runnable): Unit = terminationCallbacks.add(code) @volatile private var terminating = false @@ -1090,9 +1087,8 @@ private[pekko] class ActorSystemImpl( guardian.stop() } - override private[pekko] def isTerminating(): Boolean = { + override private[pekko] def isTerminating(): Boolean = terminating || aborting || CoordinatedShutdown(this).shutdownReason().isDefined - } @volatile var aborting = false @@ -1166,13 +1162,13 @@ private[pekko] class ActorSystemImpl( } @tailrec - final def registerExtension[T <: Extension](ext: ExtensionId[T]): T = { + final def registerExtension[T <: Extension](ext: ExtensionId[T]): T = findExtension(ext) match { case null => // Doesn't already exist, commence registration val inProcessOfRegistration = new CountDownLatch(1) extensions.putIfAbsent(ext, inProcessOfRegistration) match { // Signal that registration is in process case null => - try { // Signal was successfully sent + try // Signal was successfully sent ext.createExtension(this) match { // Create and initialize the extension case null => throw new IllegalStateException(s"Extension instance created as 'null' for extension [$ext]") @@ -1180,19 +1176,17 @@ private[pekko] class ActorSystemImpl( extensions.replace(ext, inProcessOfRegistration, instance) // Replace our in process signal with the initialized extension instance // Profit! } - } catch { + catch { case t: Throwable => extensions.replace(ext, inProcessOfRegistration, t) // In case shit hits the fan, remove the inProcess signal throw t // Escalate to caller - } finally { + } finally inProcessOfRegistration.countDown() // Always notify listeners of the inProcess signal - } case _ => registerExtension(ext) // Someone else is in process of registering an extension for this Extension, retry } case existing => existing.asInstanceOf[T] } - } def extension[T <: Extension](ext: ExtensionId[T]): T = findExtension(ext) match { case null => throw new IllegalArgumentException(s"Trying to get non-registered extension [$ext]") @@ -1208,8 +1202,7 @@ private[pekko] class ActorSystemImpl( * Throw exception when an extension fails to load (needed for backwards compatibility. * when the extension cannot be found at all we throw regardless of this setting) */ - def loadExtensions(key: String, throwOnLoadFail: Boolean): Unit = { - + def loadExtensions(key: String, throwOnLoadFail: Boolean): Unit = immutableSeq(settings.config.getStringList(key)).foreach { fqcn => dynamicAccess.getObjectFor[AnyRef](fqcn).recoverWith { case firstProblem => @@ -1227,7 +1220,6 @@ private[pekko] class ActorSystemImpl( else throw new RuntimeException(s"While trying to load extension [$fqcn]", problem) } } - } loadExtensions("pekko.library-extensions", throwOnLoadFail = true) loadExtensions("pekko.extensions", throwOnLoadFail = false) @@ -1236,7 +1228,7 @@ private[pekko] class ActorSystemImpl( override def toString: String = lookupRoot.path.root.address.toString override def printTree: String = { - def printNode(node: ActorRef, indent: String): String = { + def printNode(node: ActorRef, indent: String): String = node match { case wc: ActorRefWithCell => val cell = wc.underlying @@ -1270,7 +1262,6 @@ private[pekko] class ActorSystemImpl( case _ => indent + node.path.name + " " + Logging.simpleName(node) } - } printNode(lookupRoot, "") } diff --git a/actor/src/main/scala/org/apache/pekko/actor/Address.scala b/actor/src/main/scala/org/apache/pekko/actor/Address.scala index b7d5be3b4db..cb9dd37446b 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/Address.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/Address.scala @@ -47,9 +47,8 @@ final case class Address private[pekko] (protocol: String, system: String, host: protocol: String = protocol, system: String = system, host: Option[String] = host, - port: Option[Int] = port) = { + port: Option[Int] = port) = Address(protocol, system, host, port) - } /** * Java API: The hostname if specified or empty optional if not @@ -167,7 +166,7 @@ private[pekko] trait PathUtils { * * "/user/hello/world" */ object RelativeActorPath extends PathUtils { - def unapply(addr: String): Option[immutable.Seq[String]] = { + def unapply(addr: String): Option[immutable.Seq[String]] = try { val uri = new URI(addr) if (uri.isAbsolute) None @@ -175,7 +174,6 @@ object RelativeActorPath extends PathUtils { } catch { case _: URISyntaxException => None } - } } /** diff --git a/actor/src/main/scala/org/apache/pekko/actor/CoordinatedShutdown.scala b/actor/src/main/scala/org/apache/pekko/actor/CoordinatedShutdown.scala index 4b7baf9dacf..a111ad41e22 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/CoordinatedShutdown.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/CoordinatedShutdown.scala @@ -203,14 +203,13 @@ object CoordinatedShutdown extends ExtensionId[CoordinatedShutdown] with Extensi } // locate reason-specific overrides and merge with defaults. - @InternalApi private[pekko] def confWithOverrides(conf: Config, reason: Option[Reason]): Config = { + @InternalApi private[pekko] def confWithOverrides(conf: Config, reason: Option[Reason]): Config = reason .flatMap { r => val basePath = s"""reason-overrides."${r.getClass.getName}"""" if (conf.hasPath(basePath)) Some(conf.getConfig(basePath).withFallback(conf)) else None } .getOrElse(conf) - } /** INTERNAL API */ @InternalApi @@ -222,14 +221,13 @@ object CoordinatedShutdown extends ExtensionId[CoordinatedShutdown] with Extensi // Catching RejectedExecutionException in case extension is accessed first time when // system is already terminated, see #25592. The extension is eagerly loaded when ActorSystem // is started but it might be a race between (failing?) startup and shutdown. - def cleanupActorSystemJvmHook(): Unit = { + def cleanupActorSystemJvmHook(): Unit = coord.actorSystemJvmHook match { case OptionVal.Some(cancellable) if !runningJvmHook && !cancellable.isCancelled => cancellable.cancel() coord.actorSystemJvmHook = OptionVal.None case _ => } - } try system.registerOnTermination(cleanupActorSystemJvmHook()) catch { case _: RejectedExecutionException => cleanupActorSystemJvmHook() @@ -239,7 +237,7 @@ object CoordinatedShutdown extends ExtensionId[CoordinatedShutdown] with Extensi private def initPhaseActorSystemTerminate( system: ExtendedActorSystem, conf: Config, - coord: CoordinatedShutdown): Unit = { + coord: CoordinatedShutdown): Unit = coord.addTask(PhaseActorSystemTerminate, "terminate-system") { () => val confForReason = confWithOverrides(conf, coord.shutdownReason()) val terminateActorSystem = confForReason.getBoolean("terminate-actor-system") @@ -253,10 +251,9 @@ object CoordinatedShutdown extends ExtensionId[CoordinatedShutdown] with Extensi // since that would have blocked the shutdown of the ActorSystem. val timeout = coord.timeout(PhaseActorSystemTerminate) val t = new Thread { - override def run(): Unit = { + override def run(): Unit = if (Try(Await.ready(system.whenTerminated, timeout)).isFailure && !runningJvmHook) System.exit(exitCode) - } } t.setName("CoordinatedShutdown-exit") t.start() @@ -274,7 +271,6 @@ object CoordinatedShutdown extends ExtensionId[CoordinatedShutdown] with Extensi } else Future.successful(Done) } - } private def initJvmHook(system: ActorSystem, conf: Config, coord: CoordinatedShutdown): Unit = { val runByJvmShutdownHook = system.settings.JvmShutdownHooks && conf.getBoolean("run-by-jvm-shutdown-hook") @@ -339,9 +335,8 @@ object CoordinatedShutdown extends ExtensionId[CoordinatedShutdown] with Extensi var unmarked = phases.keySet ++ phases.values.flatMap(_.dependsOn) // in case phase is not defined as key var tempMark = Set.empty[String] // for detecting cycles - while (unmarked.nonEmpty) { + while (unmarked.nonEmpty) depthFirstSearch(unmarked.head) - } def depthFirstSearch(u: String): Unit = { if (tempMark(u)) @@ -434,13 +429,13 @@ final class CoordinatedShutdown private[pekko] ( if (log.isDebugEnabled) { log.debug("Performing task [{}] in CoordinatedShutdown phase [{}]", name, phaseName) } - job.completeWith(try { + job.completeWith(try task.apply().recover { case NonFatal(exc) if recoverEnabled => log.warning("Task [{}] failed in phase [{}]: {}", name, phaseName, exc.getMessage) Done } - } catch { // in case task.apply() throws + catch { // in case task.apply() throws case NonFatal(exc) if recoverEnabled => log.warning( "Task [{}] in phase [{}] threw an exception before its future could be constructed: {}", @@ -482,9 +477,8 @@ final class CoordinatedShutdown private[pekko] ( } // must be side-effect free - override def isCancelled: Boolean = { + override def isCancelled: Boolean = taskState.get() == Cancelled - } } } @@ -492,9 +486,8 @@ final class CoordinatedShutdown private[pekko] ( // This is a case class so that the update methods on ConcurrentHashMap can correctly deal with equality override val size: Int = tasks.size - override def run(recoverEnabled: Boolean)(implicit ec: ExecutionContext): Future[Done] = { + override def run(recoverEnabled: Boolean)(implicit ec: ExecutionContext): Future[Done] = Future.sequence(tasks.map(_.run(recoverEnabled))).map(_ => Done)(ExecutionContexts.parasitic) - } // This method may be run multiple times during the compare-and-set loop of ConcurrentHashMap, so it must be side-effect-free def merge(other: StrictPhaseDefinition): StrictPhaseDefinition = { @@ -504,9 +497,8 @@ final class CoordinatedShutdown private[pekko] ( } private object StrictPhaseDefinition { - def single(taskDefinition: TaskDefinition): StrictPhaseDefinition = { + def single(taskDefinition: TaskDefinition): StrictPhaseDefinition = StrictPhaseDefinition(Set(taskDefinition)) - } val empty: StrictPhaseDefinition = StrictPhaseDefinition(Set.empty) } @@ -587,9 +579,8 @@ final class CoordinatedShutdown private[pekko] ( * shutdown begins, tasks may be added without ever being run. A task may add tasks * to a later stage with confidence that they will be run. */ - def addCancellableTask(phase: String, taskName: String, task: Supplier[CompletionStage[Done]]): Cancellable = { + def addCancellableTask(phase: String, taskName: String, task: Supplier[CompletionStage[Done]]): Cancellable = addCancellableTask(phase, taskName)(() => task.get().asScala) - } /** * Scala API: Add a task to a phase. It doesn't remove previously added tasks. @@ -724,7 +715,7 @@ final class CoordinatedShutdown private[pekko] ( implicit val ec: ExecutionContext = system.dispatchers.internalDispatcher val debugEnabled = log.isDebugEnabled log.info("Running CoordinatedShutdown with reason [{}]", reason) - def loop(remainingPhases: List[String]): Future[Done] = { + def loop(remainingPhases: List[String]): Future[Done] = remainingPhases match { case Nil => Future.successful(Done) case phaseName :: remaining if !phases(phaseName).enabled => @@ -746,7 +737,7 @@ final class CoordinatedShutdown private[pekko] ( val timeout = phases(phaseName).timeout val deadline = Deadline.now + timeout val timeoutFut = - try { + try after(timeout, system.scheduler) { if (phaseName == CoordinatedShutdown.PhaseActorSystemTerminate && deadline.hasTimeLeft()) { // too early, i.e. triggered by system termination @@ -760,7 +751,7 @@ final class CoordinatedShutdown private[pekko] ( Future.failed( new TimeoutException(s"Coordinated shutdown phase [$phaseName] timed out after $timeout")) } - } catch { + catch { case _: IllegalStateException => // The call to `after` threw IllegalStateException, triggered by system termination result @@ -772,7 +763,6 @@ final class CoordinatedShutdown private[pekko] ( else phaseResult.flatMap(_ => loop(remaining)) } - } val remainingPhases = fromPhase match { case None => orderedPhases // all @@ -817,9 +807,8 @@ final class CoordinatedShutdown private[pekko] ( /** * Sum of timeouts of all phases that have some task. */ - def totalTimeout(): FiniteDuration = { + def totalTimeout(): FiniteDuration = tasks.totalDuration() - } /** * Scala API: Add a JVM shutdown hook that will be run when the JVM process @@ -841,24 +830,23 @@ final class CoordinatedShutdown private[pekko] ( * For shutdown hooks that does not have any requirements on running before the Akka * shutdown hooks the standard library JVM shutdown hooks APIs are better suited. */ - @tailrec def addCancellableJvmShutdownHook[T](hook: => T): Cancellable = { + @tailrec def addCancellableJvmShutdownHook[T](hook: => T): Cancellable = if (runStarted.get.isEmpty) { val currentLatch = _jvmHooksLatch.get val newLatch = new CountDownLatch(currentLatch.getCount.toInt + 1) if (_jvmHooksLatch.compareAndSet(currentLatch, newLatch)) { val thread = new Thread { - override def run(): Unit = { + override def run(): Unit = try hook finally _jvmHooksLatch.get.countDown() - } } thread.setName(s"${system.name}-shutdown-hook-${newLatch.getCount}") try { jvmShutdownHooks.addHook(thread) new Cancellable { @volatile var cancelled = false - def cancel(): Boolean = { - try { + def cancel(): Boolean = + try if (jvmShutdownHooks.removeHook(thread)) { cancelled = true _jvmHooksLatch.get.countDown() @@ -866,12 +854,11 @@ final class CoordinatedShutdown private[pekko] ( } else { false } - } catch { + catch { case _: IllegalStateException => // shutdown already in progress false } - } def isCancelled: Boolean = cancelled } } catch { @@ -886,7 +873,6 @@ final class CoordinatedShutdown private[pekko] ( } else { Cancellable.alreadyCancelled } - } /** * Java API: Add a JVM shutdown hook that will be run when the JVM process @@ -956,11 +942,10 @@ private[pekko] class CoordinatedShutdownTerminationWatcher extends Actor with Ti for { waitingPromises <- waitingForActor.get(actor) waitingPromise <- waitingPromises - } { + } if (waitingPromise.trySuccess(Done)) { timers.cancel(waitingPromise) } - } waitingForActor = waitingForActor - actor alreadySeenTerminated += actor diff --git a/actor/src/main/scala/org/apache/pekko/actor/Deployer.scala b/actor/src/main/scala/org/apache/pekko/actor/Deployer.scala index 77953cc3d94..6a891256164 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/Deployer.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/Deployer.scala @@ -106,7 +106,7 @@ final class Deploy( * precedence. The “path” of the other Deploy is not taken into account. All * other members are merged using `X.withFallback(other.X)`. */ - def withFallback(other: Deploy): Deploy = { + def withFallback(other: Deploy): Deploy = Deploy( path, config.withFallback(other.config), @@ -114,7 +114,6 @@ final class Deploy( scope.withFallback(other.scope), if (dispatcher == Deploy.NoDispatcherGiven) other.dispatcher else dispatcher, if (mailbox == Deploy.NoMailboxGiven) other.mailbox else mailbox) - } def withTags(tags: Set[String]): Deploy = new Deploy(path, config, routerConfig, scope, dispatcher, mailbox, tags) diff --git a/actor/src/main/scala/org/apache/pekko/actor/Extension.scala b/actor/src/main/scala/org/apache/pekko/actor/Extension.scala index 00dc881af39..4c87c7c45a1 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/Extension.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/Extension.scala @@ -83,9 +83,8 @@ trait ExtensionId[T <: Extension] { /** * Returns an instance of the extension identified by this ExtensionId instance. */ - def apply(system: ActorSystem): T = { + def apply(system: ActorSystem): T = java.util.Objects.requireNonNull(system, "system must not be null!").registerExtension(this) - } /** * Returns an instance of the extension identified by this ExtensionId instance. diff --git a/actor/src/main/scala/org/apache/pekko/actor/FSM.scala b/actor/src/main/scala/org/apache/pekko/actor/FSM.scala index 7ee801a2476..75a84a693c3 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/FSM.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/FSM.scala @@ -193,9 +193,8 @@ object FSM { stateData: D = stateData, timeout: Option[FiniteDuration] = timeout, stopReason: Option[Reason] = stopReason, - replies: List[Any] = replies): State[S, D] = { + replies: List[Any] = replies): State[S, D] = new SilentState(stateName, stateData, timeout, stopReason, replies) - } } @@ -210,13 +209,11 @@ object FSM { stateData: D, timeout: Option[FiniteDuration] = None, stopReason: Option[Reason] = None, - replies: List[Any] = Nil) = { + replies: List[Any] = Nil) = new State(stateName, stateData, timeout, stopReason, replies) - } - def unapply[S, D](state: State[S, D]): Option[(S, D, Option[FiniteDuration], Option[Reason], List[Any])] = { + def unapply[S, D](state: State[S, D]): Option[(S, D, Option[FiniteDuration], Option[Reason], List[Any])] = Some((state.stateName, state.stateData, state.timeout, state.stopReason, state.replies)) - } } class State[S, D]( val stateName: S, @@ -227,12 +224,11 @@ object FSM { extends Product with Serializable { - def canEqual(that: Any): Boolean = { + def canEqual(that: Any): Boolean = that match { case _: State[_, _] => true case _ => false } - } override def equals(that: Any) = that match { case other: State[_, _] => @@ -268,9 +264,8 @@ object FSM { stateData: D = stateData, timeout: Option[FiniteDuration] = timeout, stopReason: Option[Reason] = stopReason, - replies: List[Any] = replies): State[S, D] = { + replies: List[Any] = replies): State[S, D] = new State(stateName, stateData, timeout, stopReason, replies) - } /** * Modify state transition descriptor to include a state timeout for the @@ -303,35 +298,31 @@ object FSM { * * @return this state transition descriptor */ - def replying(replyValue: Any): State[S, D] = { + def replying(replyValue: Any): State[S, D] = copy(replies = replyValue :: replies) - } /** * Modify state transition descriptor with new state data. The data will be * set when transitioning to the new state. */ @nowarn("msg=deprecated") - def using(@deprecatedName(Symbol("nextStateDate")) nextStateData: D): State[S, D] = { + def using(@deprecatedName(Symbol("nextStateDate")) nextStateData: D): State[S, D] = copy(stateData = nextStateData) - } /** * INTERNAL API. */ - private[pekko] def withStopReason(reason: Reason): State[S, D] = { + private[pekko] def withStopReason(reason: Reason): State[S, D] = copy(stopReason = Some(reason)) - } /** * INTERNAL API. */ - private[pekko] def withNotification(notifies: Boolean): State[S, D] = { + private[pekko] def withNotification(notifies: Boolean): State[S, D] = if (notifies) State(stateName, stateData, timeout, stopReason, replies) else new SilentState(stateName, stateData, timeout, stopReason, replies) - } } /** @@ -688,7 +679,7 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging { implicit final def total2pf(transitionHandler: (S, S) => Unit): TransitionHandler = new TransitionHandler { def isDefinedAt(in: (S, S)) = true - def apply(in: (S, S)): Unit = { transitionHandler(in._1, in._2) } + def apply(in: (S, S)): Unit = transitionHandler(in._1, in._2) } /** @@ -723,10 +714,9 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging { /** * Return current state name (i.e. object of type S) */ - final def stateName: S = { + final def stateName: S = if (currentState != null) currentState.stateName else throw new IllegalStateException("You must call `startWith` before using `stateName`") - } /** * Return current state data (i.e. object of type D) @@ -771,7 +761,7 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging { private val stateFunctions = mutable.Map[S, StateFunction]() private val stateTimeouts = mutable.Map[S, Timeout]() - private def register(name: S, function: StateFunction, timeout: Timeout): Unit = { + private def register(name: S, function: StateFunction, timeout: Timeout): Unit = if (stateFunctions contains name) { stateFunctions(name) = stateFunctions(name).orElse(function) stateTimeouts(name) = timeout.orElse(stateTimeouts(name)) @@ -779,7 +769,6 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging { stateFunctions(name) = function stateTimeouts(name) = timeout } - } /* * unhandled event handler @@ -802,7 +791,7 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging { private var transitionEvent: List[TransitionHandler] = Nil private def handleTransition(prev: S, next: S): Unit = { val tuple = (prev, next) - for (te <- transitionEvent) { if (te.isDefinedAt(tuple)) te(tuple) } + for (te <- transitionEvent) if (te.isDefinedAt(tuple)) te(tuple) } /* @@ -866,7 +855,7 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging { applyState(nextState) } - private[pekko] def applyState(nextState: State): Unit = { + private[pekko] def applyState(nextState: State): Unit = nextState.stopReason match { case None => makeTransition(nextState) case _ => @@ -876,9 +865,8 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging { terminate(nextState) context.stop(self) } - } - private[pekko] def makeTransition(nextState: State): Unit = { + private[pekko] def makeTransition(nextState: State): Unit = if (!stateFunctions.contains(nextState.stateName)) { terminate(stay().withStopReason(Failure("Next state %s does not exist".format(nextState.stateName)))) } else { @@ -906,7 +894,6 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging { if (timeout.isDefined) timeoutFuture = scheduleTimeout(timeout.get) } } - } /** * Call `onTermination` hook; if you want to retain this behavior when @@ -925,20 +912,19 @@ trait FSM[S, D] extends Actor with Listeners with ActorLogging { super.postStop() } - private def terminate(nextState: State): Unit = { + private def terminate(nextState: State): Unit = if (currentState.stopReason.isEmpty) { val reason = nextState.stopReason.get logTermination(reason) for (timer <- timers.values) timer.cancel() timers.clear() - timeoutFuture.foreach { _.cancel() } + timeoutFuture.foreach(_.cancel()) currentState = nextState val stopEvent = StopEvent(reason, currentState.stateName, currentState.stateData) if (terminateEvent.isDefinedAt(stopEvent)) terminateEvent(stopEvent) } - } /** * By default [[pekko.actor.FSM.Failure]] is logged at error level and other reason diff --git a/actor/src/main/scala/org/apache/pekko/actor/FaultHandling.scala b/actor/src/main/scala/org/apache/pekko/actor/FaultHandling.scala index 4039cc340c3..371ec9fdac8 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/FaultHandling.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/FaultHandling.scala @@ -226,9 +226,8 @@ object SupervisorStrategy extends SupervisorStrategyLowPriorityImplicits { * is used by default. OneForOneStrategy with decider defined in * [[#defaultDecider]]. */ - final val defaultStrategy: SupervisorStrategy = { + final val defaultStrategy: SupervisorStrategy = OneForOneStrategy()(defaultDecider) - } /** * This strategy resembles Erlang in that failing children are always @@ -555,14 +554,13 @@ case class AllForOneStrategy( child: ActorRef, cause: Throwable, stats: ChildRestartStats, - children: Iterable[ChildRestartStats]): Unit = { + children: Iterable[ChildRestartStats]): Unit = if (children.nonEmpty) { if (restart && children.forall(_.requestRestartPermission(retriesWindow))) children.foreach(crs => restartChild(crs.child, cause, suspendFirst = crs.child != child)) else for (c <- children) context.stop(c.child) } - } } /** @@ -667,10 +665,9 @@ case class OneForOneStrategy( child: ActorRef, cause: Throwable, stats: ChildRestartStats, - children: Iterable[ChildRestartStats]): Unit = { + children: Iterable[ChildRestartStats]): Unit = if (restart && stats.requestRestartPermission(retriesWindow)) restartChild(child, cause, suspendFirst = false) else context.stop(child) // TODO optimization to drop child here already? - } } diff --git a/actor/src/main/scala/org/apache/pekko/actor/IndirectActorProducer.scala b/actor/src/main/scala/org/apache/pekko/actor/IndirectActorProducer.scala index d10c99eb485..3525e381a9a 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/IndirectActorProducer.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/IndirectActorProducer.scala @@ -53,7 +53,7 @@ private[pekko] object IndirectActorProducer { val CreatorConsumerClass = classOf[CreatorConsumer] val TypedCreatorFunctionConsumerClass = classOf[TypedCreatorFunctionConsumer] @nowarn - def apply(clazz: Class[_], args: immutable.Seq[Any]): IndirectActorProducer = { + def apply(clazz: Class[_], args: immutable.Seq[Any]): IndirectActorProducer = if (classOf[IndirectActorProducer].isAssignableFrom(clazz)) { def get1stArg[T]: T = args.head.asInstanceOf[T] def get2ndArg[T]: T = args.tail.head.asInstanceOf[T] @@ -73,7 +73,6 @@ private[pekko] object IndirectActorProducer { if (args.isEmpty) new NoArgsReflectConstructor(clazz.asInstanceOf[Class[_ <: Actor]]) else new ArgsReflectConstructor(clazz.asInstanceOf[Class[_ <: Actor]], args) } else throw new IllegalArgumentException(s"unknown actor creator [$clazz]") - } } /** diff --git a/actor/src/main/scala/org/apache/pekko/actor/LightArrayRevolverScheduler.scala b/actor/src/main/scala/org/apache/pekko/actor/LightArrayRevolverScheduler.scala index c82969ba592..a979e3655dd 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/LightArrayRevolverScheduler.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/LightArrayRevolverScheduler.scala @@ -140,7 +140,7 @@ class LightArrayRevolverScheduler(config: Config, log: LoggingAdapter, threadFac schedule( executor, new AtomicLong(clock() + initialDelay.toNanos) with Runnable { - override def run(): Unit = { + override def run(): Unit = try { runnable.run() val driftNanos = clock() - getAndAdd(delay.toNanos) @@ -149,7 +149,6 @@ class LightArrayRevolverScheduler(config: Config, log: LoggingAdapter, threadFac } catch { case _: SchedulerException => // ignore failure to enqueue or terminated target actor } - } }, roundUp(initialDelay)) } @@ -164,14 +163,13 @@ class LightArrayRevolverScheduler(config: Config, log: LoggingAdapter, threadFac override def close(): Unit = { - def runTask(task: Runnable): Unit = { + def runTask(task: Runnable): Unit = try task.run() catch { case e: InterruptedException => throw e case _: SchedulerException => // ignore terminated actors case NonFatal(e) => log.error(e, "exception while executing timer task") } - } Await.result(stop(), getShutdownTimeout).foreach { case task: Scheduler.TaskRunOnClose => @@ -249,12 +247,11 @@ class LightArrayRevolverScheduler(config: Config, log: LoggingAdapter, threadFac var spareTaskQueue = new TaskQueue private def clearAll(): immutable.Seq[TimerTask] = { - @tailrec def collect(q: TaskQueue, acc: Vector[TimerTask]): Vector[TimerTask] = { + @tailrec def collect(q: TaskQueue, acc: Vector[TimerTask]): Vector[TimerTask] = q.poll() match { case null => acc case x => collect(q, acc :+ x) } - } (0 until WheelSize).flatMap(i => collect(wheel(i), Vector.empty)) ++ collect(queue, Vector.empty) } diff --git a/actor/src/main/scala/org/apache/pekko/actor/Props.scala b/actor/src/main/scala/org/apache/pekko/actor/Props.scala index 80637e04fe2..fd58195d634 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/Props.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/Props.scala @@ -232,7 +232,6 @@ final case class Props(deploy: Deploy, clazz: Class[_], args: immutable.Seq[Any] * actor creation by the ActorSystem, i.e. for user-level code it can only be * used within the implementation of [[IndirectActorProducer#produce]]. */ - private[pekko] def newActor(): Actor = { + private[pekko] def newActor(): Actor = producer.produce() - } } diff --git a/actor/src/main/scala/org/apache/pekko/actor/RepointableActorRef.scala b/actor/src/main/scala/org/apache/pekko/actor/RepointableActorRef.scala index bcd8eb8d0a1..afeee64095f 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/RepointableActorRef.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/RepointableActorRef.scala @@ -220,7 +220,7 @@ private[pekko] class UnstartedCell( def replaceWith(cell: Cell): Unit = locked { try { - def drainSysmsgQueue(): Unit = { + def drainSysmsgQueue(): Unit = // using while in case a sys msg enqueues another sys msg while (sysmsgQueue.nonEmpty) { var sysQ = sysmsgQueue.reverse @@ -232,7 +232,6 @@ private[pekko] class UnstartedCell( cell.sendSystemMessage(msg) } } - } drainSysmsgQueue() @@ -241,9 +240,8 @@ private[pekko] class UnstartedCell( // drain sysmsgQueue in case a msg enqueues a sys msg drainSysmsgQueue() } - } finally { + } finally self.swapCell(cell) - } } def system: ActorSystem = systemImpl @@ -261,7 +259,7 @@ private[pekko] class UnstartedCell( def getChildByName(name: String): Option[ChildRestartStats] = None override def getSingleChild(name: String): InternalActorRef = Nobody - def sendMessage(msg: Envelope): Unit = { + def sendMessage(msg: Envelope): Unit = if (lock.tryLock(timeout.length, timeout.unit)) { try { val cell = self.underlying @@ -284,7 +282,6 @@ private[pekko] class UnstartedCell( "dropping message of type" + msg.message.getClass + " due to lock timeout")) system.deadLetters.tell(DeadLetter(msg.message, msg.sender, self), msg.sender) } - } def sendSystemMessage(msg: SystemMessage): Unit = { lock.lock() // we cannot lose system messages, ever, and we cannot throw an Error from here as well diff --git a/actor/src/main/scala/org/apache/pekko/actor/Scheduler.scala b/actor/src/main/scala/org/apache/pekko/actor/Scheduler.scala index 5095c9ed7db..ed1bba9da41 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/Scheduler.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/Scheduler.scala @@ -86,7 +86,7 @@ trait Scheduler { scheduleOnce( initialDelay, new Runnable { - override def run(): Unit = { + override def run(): Unit = try { runnable.run() if (get != null) @@ -96,7 +96,6 @@ trait Scheduler { case _: SchedulerException => case e: IllegalStateException if e.getCause != null && e.getCause.isInstanceOf[SchedulerException] => } - } }) } @@ -153,7 +152,7 @@ trait Scheduler { message: Any)( implicit executor: ExecutionContext, - sender: ActorRef = Actor.noSender): Cancellable = { + sender: ActorRef = Actor.noSender): Cancellable = scheduleWithFixedDelay(initialDelay, delay)(new Runnable { def run(): Unit = { receiver ! message @@ -161,7 +160,6 @@ trait Scheduler { throw SchedulerException("timer active for terminated actor") } }) - } /** * Java API: Schedules a message to be sent repeatedly with an initial delay and @@ -555,32 +553,30 @@ object Scheduler { extends AtomicReference[Cancellable](initialValue) with Cancellable { - try { + try compareAndSet(initialValue, scheduledFirst()) - } catch { + catch { case cause @ SchedulerException(msg) => throw new IllegalStateException(msg, cause) } protected def scheduledFirst(): Cancellable - @tailrec final protected def swap(c: Cancellable): Unit = { + @tailrec final protected def swap(c: Cancellable): Unit = get match { case null => if (c != null) c.cancel() case old => if (!compareAndSet(old, c)) swap(c) } - } final def cancel(): Boolean = { - @tailrec def tailrecCancel(): Boolean = { + @tailrec def tailrecCancel(): Boolean = get match { case null => false case c => if (c.cancel()) compareAndSet(c, null) else compareAndSet(c, null) || tailrecCancel() } - } tailrecCancel() } diff --git a/actor/src/main/scala/org/apache/pekko/actor/Stash.scala b/actor/src/main/scala/org/apache/pekko/actor/Stash.scala index a56f9bfc497..9c2007df77b 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/Stash.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/Stash.scala @@ -86,10 +86,9 @@ trait UnrestrictedStash extends Actor with StashSupport { * clears the stash, stops all children and invokes the postStop() callback. */ @throws(classOf[Exception]) - override def preRestart(reason: Throwable, message: Option[Any]): Unit = { + override def preRestart(reason: Throwable, message: Option[Any]): Unit = try unstashAll() finally super.preRestart(reason, message) - } /** * Overridden callback. Prepends all messages in the stash to the mailbox and clears the stash. @@ -157,7 +156,7 @@ private[pekko] trait StashSupport { * The actor's deque-based message queue. * `mailbox.queue` is the underlying `Deque`. */ - private[pekko] val mailbox: DequeBasedMessageQueueSemantics = { + private[pekko] val mailbox: DequeBasedMessageQueueSemantics = actorCell.mailbox.messageQueue match { case queue: DequeBasedMessageQueueSemantics => queue case other => @@ -170,7 +169,6 @@ private[pekko] trait StashSupport { | } |""".stripMargin) } - } /** * Adds the current message (the message that the actor received last) to the @@ -209,11 +207,10 @@ private[pekko] trait StashSupport { */ private[pekko] def unstash(): Unit = if (theStash.nonEmpty) - try { + try enqueueFirst(theStash.head) - } finally { + finally theStash = theStash.tail - } /** * Prepends all messages in the stash to the mailbox, and then clears the stash. @@ -242,14 +239,12 @@ private[pekko] trait StashSupport { * prepended to the mailbox. */ @InternalStableApi - private[pekko] def unstashAll(filterPredicate: Any => Boolean): Unit = { + private[pekko] def unstashAll(filterPredicate: Any => Boolean): Unit = try { val i = theStash.reverseIterator.filter(envelope => filterPredicate(envelope.message)) while (i.hasNext) enqueueFirst(i.next()) - } finally { + } finally theStash = Vector.empty[Envelope] - } - } /** * INTERNAL API. diff --git a/actor/src/main/scala/org/apache/pekko/actor/Timers.scala b/actor/src/main/scala/org/apache/pekko/actor/Timers.scala index 7393eb097a1..e515abb6956 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/Timers.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/Timers.scala @@ -48,7 +48,7 @@ trait Timers extends Actor { super.aroundPostStop() } - override protected[pekko] def aroundReceive(receive: Actor.Receive, msg: Any): Unit = { + override protected[pekko] def aroundReceive(receive: Actor.Receive, msg: Any): Unit = msg match { case timerMsg: TimerSchedulerImpl.TimerMsg => _timers.interceptTimerMsg(timerMsg) match { @@ -65,7 +65,6 @@ trait Timers extends Actor { case _ => super.aroundReceive(receive, msg) } - } } diff --git a/actor/src/main/scala/org/apache/pekko/actor/TypedActor.scala b/actor/src/main/scala/org/apache/pekko/actor/TypedActor.scala index 9274ebc6266..46077af6be3 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/TypedActor.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/TypedActor.scala @@ -158,13 +158,13 @@ object TypedActor extends ExtensionId[TypedActorExtension] with ExtensionIdProvi * Throws the underlying exception if there's an InvocationTargetException thrown on the invocation. */ def apply(instance: AnyRef): AnyRef = - try { + try parameters match { case null => method.invoke(instance) case args if args.length == 0 => method.invoke(instance) case args => method.invoke(instance, args: _*) } - } catch { case i: InvocationTargetException => throw i.getTargetException } + catch { case i: InvocationTargetException => throw i.getTargetException } @throws(classOf[ObjectStreamException]) private def writeReplace(): AnyRef = parameters match { case null => SerializedMethodCall(method.getDeclaringClass, method.getName, method.getParameterTypes, null) @@ -299,21 +299,20 @@ object TypedActor extends ExtensionId[TypedActorExtension] with ExtensionIdProvi @nowarn("msg=deprecated") override def postStop(): Unit = - try { + try withContext { me match { case l: PostStop => l.postStop() case _ => super.postStop() } } - } finally { + finally pekko.actor.TypedActor(self.context.system).invocationHandlerFor(proxyVar.get) match { case null => case some => some.actorVar.set(self.context.system.deadLetters) // Point it to the DLQ proxyVar.set(null.asInstanceOf[R]) } - } override def preRestart(reason: Throwable, message: Option[Any]): Unit = withContext { me match { @@ -482,9 +481,9 @@ object TypedActor extends ExtensionId[TypedActorExtension] with ExtensionIdProvi } case m if m.returnsJOption || m.returnsOption => val f = ask(actor, m)(timeout) - (try { + (try Await.ready(f, timeout.duration).value - } catch { case _: TimeoutException => None }) match { + catch { case _: TimeoutException => None }) match { case None | Some(Success(NullResponse)) | Some(Failure(_: AskTimeoutException)) => if (m.returnsJOption) JOption.none[Any] else None case Some(t: Try[_]) => diff --git a/actor/src/main/scala/org/apache/pekko/actor/dungeon/Children.scala b/actor/src/main/scala/org/apache/pekko/actor/dungeon/Children.scala index aee8ff8ca66..e3314bf64a3 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/dungeon/Children.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/dungeon/Children.scala @@ -173,13 +173,12 @@ private[pekko] trait Children { this: ActorCell => } } - @tailrec final protected def setChildrenTerminationReason(reason: ChildrenContainer.SuspendReason): Boolean = { + @tailrec final protected def setChildrenTerminationReason(reason: ChildrenContainer.SuspendReason): Boolean = childrenRefs match { case c: ChildrenContainer.TerminatingChildrenContainer => swapChildrenRefs(c, c.copy(reason = reason)) || setChildrenTerminationReason(reason) case _ => false } - } final protected def setTerminated(): Unit = Unsafe.instance.putObjectVolatile(this, AbstractActorCell.childrenOffset, TerminatedChildrenContainer) @@ -258,7 +257,7 @@ private[pekko] trait Children { this: ActorCell => * Private helpers */ - private def checkName(name: String): String = { + private def checkName(name: String): String = name match { case null => throw InvalidActorNameException("actor name must not be null") case "" => throw InvalidActorNameException("actor name must not be empty") @@ -266,7 +265,6 @@ private[pekko] trait Children { this: ActorCell => ActorPath.validatePathElement(name) name } - } private def makeChild( cell: ActorCell, diff --git a/actor/src/main/scala/org/apache/pekko/actor/dungeon/DeathWatch.scala b/actor/src/main/scala/org/apache/pekko/actor/dungeon/DeathWatch.scala index 4c67e848b9d..8296929bca7 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/dungeon/DeathWatch.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/dungeon/DeathWatch.scala @@ -155,24 +155,23 @@ private[pekko] trait DeathWatch { this: ActorCell => */ watchedBy.foreach(sendTerminated(ifLocal = false)) watchedBy.foreach(sendTerminated(ifLocal = true)) - } finally { + } finally maintainAddressTerminatedSubscription() { watchedBy = ActorCell.emptyActorRefSet } - } } protected def unwatchWatchedActors(@unused actor: Actor): Unit = if (watching.nonEmpty) { maintainAddressTerminatedSubscription() { - try { + try watching.foreach { // ➡➡➡ NEVER SEND THE SAME SYSTEM MESSAGE OBJECT TO TWO ACTORS ⬅⬅⬅ case (watchee: InternalActorRef, _) => watchee.sendSystemMessage(Unwatch(watchee, self)) case (watchee, _) => // should never happen, suppress "match may not be exhaustive" compiler warning throw new IllegalStateException(s"Expected InternalActorRef, but got [${watchee.getClass.getName}]") } - } finally { + finally { watching = Map.empty terminatedQueued = Map.empty } @@ -226,10 +225,9 @@ private[pekko] trait DeathWatch { this: ActorCell => // When a parent is watching a child and it terminates due to AddressTerminated // it is removed by sending DeathWatchNotification with existenceConfirmed = true to support // immediate creation of child with same name. - for ((a, _) <- watching; if a.path.address == address) { + for ((a, _) <- watching; if a.path.address == address) self.sendSystemMessage( DeathWatchNotification(a, existenceConfirmed = childrenRefs.getByRef(a).isDefined, addressTerminated = true)) - } } /** diff --git a/actor/src/main/scala/org/apache/pekko/actor/dungeon/Dispatch.scala b/actor/src/main/scala/org/apache/pekko/actor/dungeon/Dispatch.scala index 99211122951..b78ace31a84 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/dungeon/Dispatch.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/dungeon/Dispatch.scala @@ -48,9 +48,8 @@ private[pekko] trait Dispatch { this: ActorCell => @nowarn @volatile private var _mailboxDoNotCallMeDirectly: Mailbox = _ // This must be volatile since it isn't protected by the mailbox status - @nowarn private def _preventPrivateUnusedErasure = { + @nowarn private def _preventPrivateUnusedErasure = _mailboxDoNotCallMeDirectly - } final def mailbox: Mailbox = Unsafe.instance.getObjectVolatile(this, AbstractActorCell.mailboxOffset).asInstanceOf[Mailbox] @@ -187,9 +186,9 @@ private[pekko] trait Dispatch { this: ActorCell => envelope else { val deserializedMsg = - try { + try serializeAndDeserializePayload(msg) - } catch { + catch { case NonFatal(e) => throw SerializationCheckFailedException(msg, e) } envelope.message match { diff --git a/actor/src/main/scala/org/apache/pekko/actor/dungeon/FaultHandling.scala b/actor/src/main/scala/org/apache/pekko/actor/dungeon/FaultHandling.scala index c952b685b35..79a2c25cb5d 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/dungeon/FaultHandling.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/dungeon/FaultHandling.scala @@ -99,16 +99,15 @@ private[pekko] trait FaultHandling { this: ActorCell => if (system.settings.DebugLifecycle) publish(Debug(self.path.toString, clazz(failedActor), "restarting")) if (failedActor ne null) { val optionalMessage = if (currentMessage ne null) Some(currentMessage.message) else None - try { + try // if the actor fails in preRestart, we can do nothing but log it: it’s best-effort if (!isFailedFatally) failedActor.aroundPreRestart(cause, optionalMessage) - } catch handleNonFatalOrInterruptedException { e => + catch handleNonFatalOrInterruptedException { e => val ex = PreRestartException(self, e, cause, optionalMessage) publish(Error(ex, self.path.toString, clazz(failedActor), e.getMessage)) } - finally { + finally clearActorFields(failedActor, recreate = true) - } } assert(mailbox.isSuspended, "mailbox must be suspended during restart, status=" + mailbox.currentStatus) if (!setChildrenTerminationReason(ChildrenContainer.Recreation(cause))) finishRecreate(cause) @@ -133,7 +132,7 @@ private[pekko] trait FaultHandling { this: ActorCell => * @param causedByFailure signifies if it was our own failure which * prompted this action. */ - protected def faultResume(causedByFailure: Throwable): Unit = { + protected def faultResume(causedByFailure: Throwable): Unit = if (actor == null) { system.eventStream.publish( Error(self.path.toString, clazz(actor), "changing Resume into Create after " + causedByFailure)) @@ -150,7 +149,6 @@ private[pekko] trait FaultHandling { this: ActorCell => finally if (causedByFailure != null) clearFailed() resumeChildren(causedByFailure, perp) } - } /** * Do create the actor in response to a failure. @@ -212,7 +210,7 @@ private[pekko] trait FaultHandling { this: ActorCell => } @InternalStableApi - final def handleInvokeFailure(childrenNotToSuspend: immutable.Iterable[ActorRef], t: Throwable): Unit = { + final def handleInvokeFailure(childrenNotToSuspend: immutable.Iterable[ActorRef], t: Throwable): Unit = // prevent any further messages to be processed until the actor has been restarted try { suspendNonRecursive() @@ -242,7 +240,6 @@ private[pekko] trait FaultHandling { this: ActorCell => try children.foreach(stop) finally finishTerminate() } - } private def finishTerminate(): Unit = { val a = actor diff --git a/actor/src/main/scala/org/apache/pekko/actor/dungeon/TimerSchedulerImpl.scala b/actor/src/main/scala/org/apache/pekko/actor/dungeon/TimerSchedulerImpl.scala index 0350996fee5..2effd6f2f6c 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/dungeon/TimerSchedulerImpl.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/dungeon/TimerSchedulerImpl.scala @@ -114,12 +114,11 @@ import pekko.util.OptionVal override def isTimerActive(key: Any): Boolean = timers.contains(key) - override def cancel(key: Any): Unit = { + override def cancel(key: Any): Unit = timers.get(key) match { case None => // already removed/canceled case Some(t) => cancelTimer(t) } - } private def cancelTimer(timer: Timer): Unit = { timer.task.cancel() @@ -133,7 +132,7 @@ import pekko.util.OptionVal timers = Map.empty } - def interceptTimerMsg(timerMsg: TimerMsg): OptionVal[AnyRef] = { + def interceptTimerMsg(timerMsg: TimerMsg): OptionVal[AnyRef] = timers.get(timerMsg.key) match { case None => // it was from canceled timer that was already enqueued in mailbox @@ -159,6 +158,5 @@ import pekko.util.OptionVal OptionVal.None // message should be ignored } } - } } diff --git a/actor/src/main/scala/org/apache/pekko/actor/setup/ActorSystemSetup.scala b/actor/src/main/scala/org/apache/pekko/actor/setup/ActorSystemSetup.scala index db019283793..49e994b03f8 100644 --- a/actor/src/main/scala/org/apache/pekko/actor/setup/ActorSystemSetup.scala +++ b/actor/src/main/scala/org/apache/pekko/actor/setup/ActorSystemSetup.scala @@ -66,9 +66,8 @@ final class ActorSystemSetup private[pekko] (@InternalApi private[pekko] val set /** * Java API: Extract a concrete [[pekko.actor.setup.Setup]] of type `T` if it is defined in the settings. */ - def get[T <: Setup](clazz: Class[T]): Optional[T] = { + def get[T <: Setup](clazz: Class[T]): Optional[T] = setups.get(clazz).map(_.asInstanceOf[T]).toJava - } /** * Scala API: Extract a concrete [[pekko.actor.setup.Setup]] of type `T` if it is defined in the settings. @@ -82,9 +81,8 @@ final class ActorSystemSetup private[pekko] (@InternalApi private[pekko] val set * Add a concrete [[pekko.actor.setup.Setup]]. If a setting of the same concrete [[pekko.actor.setup.Setup]] already is * present it will be replaced. */ - def withSetup[T <: Setup](t: T): ActorSystemSetup = { + def withSetup[T <: Setup](t: T): ActorSystemSetup = new ActorSystemSetup(setups + (t.getClass -> t)) - } /** * alias for `withSetup` allowing for fluent combination of settings: `a and b and c`, where `a`, `b` and `c` are diff --git a/actor/src/main/scala/org/apache/pekko/dispatch/AbstractDispatcher.scala b/actor/src/main/scala/org/apache/pekko/dispatch/AbstractDispatcher.scala index f163f01960d..c732852525f 100644 --- a/actor/src/main/scala/org/apache/pekko/dispatch/AbstractDispatcher.scala +++ b/actor/src/main/scala/org/apache/pekko/dispatch/AbstractDispatcher.scala @@ -34,9 +34,8 @@ import com.typesafe.config.Config final case class Envelope private (message: Any, sender: ActorRef) { - def copy(message: Any = message, sender: ActorRef = sender) = { + def copy(message: Any = message, sender: ActorRef = sender) = Envelope(message, sender) - } } object Envelope { @@ -172,9 +171,9 @@ abstract class MessageDispatcher(val configurator: MessageDispatcherConfigurator final override protected def unbatchedExecute(r: Runnable): Unit = { val invocation = TaskInvocation(eventStream, r, taskCleanup) addInhabitants(+1) - try { + try executeTask(invocation) - } catch { + catch { case t: Throwable => addInhabitants(-1) throw t @@ -187,7 +186,7 @@ abstract class MessageDispatcher(val configurator: MessageDispatcherConfigurator } @tailrec - private final def ifSensibleToDoSoThenScheduleShutdown(): Unit = { + private final def ifSensibleToDoSoThenScheduleShutdown(): Unit = if (inhabitants <= 0) shutdownSchedule match { case UNSCHEDULED => if (updateShutdownSchedule(UNSCHEDULED, SCHEDULED)) scheduleShutdownAction() @@ -199,9 +198,8 @@ abstract class MessageDispatcher(val configurator: MessageDispatcherConfigurator case unexpected => throw new IllegalArgumentException(s"Unexpected actor class marker: $unexpected") // will not happen, for exhaustiveness check } - } - private def scheduleShutdownAction(): Unit = { + private def scheduleShutdownAction(): Unit = // IllegalStateException is thrown if scheduler has been shutdown try prerequisites.scheduler.scheduleOnce(shutdownTimeout, shutdownAction)(new ExecutionContext { override def execute(runnable: Runnable): Unit = runnable.run() @@ -216,7 +214,6 @@ abstract class MessageDispatcher(val configurator: MessageDispatcherConfigurator // (as per ifSensibleToDoSoThenScheduleShutdown above) updateShutdownSchedule(SCHEDULED, UNSCHEDULED) } - } private final val taskCleanup: () => Unit = () => if (addInhabitants(-1) == 0) ifSensibleToDoSoThenScheduleShutdown() @@ -245,14 +242,13 @@ abstract class MessageDispatcher(val configurator: MessageDispatcherConfigurator private val shutdownAction = new Scheduler.TaskRunOnClose { @tailrec - final def run(): Unit = { + final def run(): Unit = shutdownSchedule match { case SCHEDULED => - try { + try if (inhabitants == 0) shutdown() // Warning, racy - } finally { + finally while (!updateShutdownSchedule(shutdownSchedule, UNSCHEDULED)) {} - } case RESCHEDULED => if (updateShutdownSchedule(RESCHEDULED, SCHEDULED)) scheduleShutdownAction() else run() @@ -260,7 +256,6 @@ abstract class MessageDispatcher(val configurator: MessageDispatcherConfigurator case unexpected => throw new IllegalArgumentException(s"Unexpected actor class marker: $unexpected") // will not happen, for exhaustiveness check } - } } /** diff --git a/actor/src/main/scala/org/apache/pekko/dispatch/BatchingExecutor.scala b/actor/src/main/scala/org/apache/pekko/dispatch/BatchingExecutor.scala index 437989654fe..33a5e16bfb6 100644 --- a/actor/src/main/scala/org/apache/pekko/dispatch/BatchingExecutor.scala +++ b/actor/src/main/scala/org/apache/pekko/dispatch/BatchingExecutor.scala @@ -131,7 +131,7 @@ private[pekko] trait BatchingExecutor extends Executor { protected def resubmitOnBlock: Boolean - override def execute(runnable: Runnable): Unit = { + override def execute(runnable: Runnable): Unit = if (batchable(runnable)) { // If we can batch the runnable _tasksLocal.get match { case null => @@ -141,7 +141,6 @@ private[pekko] trait BatchingExecutor extends Executor { case batch => batch.add(runnable) // If we are already in batching mode, add to batch } } else unbatchedExecute(runnable) // If not batchable, just delegate to underlying - } /** Override this to define which runnables will be batched. */ def batchable(runnable: Runnable): Boolean = pekko.dispatch.internal.ScalaBatchable.isBatchable(runnable) diff --git a/actor/src/main/scala/org/apache/pekko/dispatch/CachingConfig.scala b/actor/src/main/scala/org/apache/pekko/dispatch/CachingConfig.scala index 4f798882bf8..87658775f45 100644 --- a/actor/src/main/scala/org/apache/pekko/dispatch/CachingConfig.scala +++ b/actor/src/main/scala/org/apache/pekko/dispatch/CachingConfig.scala @@ -60,11 +60,11 @@ private[pekko] class CachingConfig(_config: Config) extends Config { private def getPathEntry(path: String): PathEntry = entryMap.get(path) match { case null => - val ne = Try { config.hasPath(path) } match { + val ne = Try(config.hasPath(path)) match { case Failure(_) => invalidPathEntry case Success(false) => nonExistingPathEntry case _ => - Try { config.getValue(path) } match { + Try(config.getValue(path)) match { case Failure(_) => emptyPathEntry case Success(v) => @@ -83,9 +83,8 @@ private[pekko] class CachingConfig(_config: Config) extends Config { case e => e } - def checkValid(reference: Config, restrictToPaths: String*): Unit = { + def checkValid(reference: Config, restrictToPaths: String*): Unit = config.checkValid(reference, restrictToPaths: _*) - } def root() = config.root() @@ -125,13 +124,12 @@ private[pekko] class CachingConfig(_config: Config) extends Config { def getDouble(path: String) = config.getDouble(path) - def getString(path: String) = { + def getString(path: String) = getPathEntry(path) match { case StringPathEntry(_, _, _, string) => string case e => e.config.getString("cached") } - } def getObject(path: String) = config.getObject(path) diff --git a/actor/src/main/scala/org/apache/pekko/dispatch/Dispatcher.scala b/actor/src/main/scala/org/apache/pekko/dispatch/Dispatcher.scala index 01fe66f0a26..3d9ba118f67 100644 --- a/actor/src/main/scala/org/apache/pekko/dispatch/Dispatcher.scala +++ b/actor/src/main/scala/org/apache/pekko/dispatch/Dispatcher.scala @@ -86,27 +86,25 @@ class Dispatcher( /** * INTERNAL API */ - protected[pekko] def executeTask(invocation: TaskInvocation): Unit = { - try { + protected[pekko] def executeTask(invocation: TaskInvocation): Unit = + try executorService.execute(invocation) - } catch { + catch { case e: RejectedExecutionException => - try { + try executorService.execute(invocation) - } catch { + catch { case e2: RejectedExecutionException => eventStream.publish(Error(e, getClass.getName, getClass, "executeTask was rejected twice!")) throw e2 } } - } /** * INTERNAL API */ - protected[pekko] def createMailbox(actor: pekko.actor.Cell, mailboxType: MailboxType): Mailbox = { + protected[pekko] def createMailbox(actor: pekko.actor.Cell, mailboxType: MailboxType): Mailbox = new Mailbox(mailboxType.create(Some(actor.self), Some(actor.system))) with DefaultSystemMessageQueue - } private val esUpdater = AtomicReferenceFieldUpdater.newUpdater( classOf[Dispatcher], @@ -130,7 +128,7 @@ class Dispatcher( protected[pekko] override def registerForExecution( mbox: Mailbox, hasMessageHint: Boolean, - hasSystemMessageHint: Boolean): Boolean = { + hasSystemMessageHint: Boolean): Boolean = if (mbox.canBeScheduledForExecution(hasMessageHint, hasSystemMessageHint)) { // This needs to be here to ensure thread safety and no races if (mbox.setAsScheduled()) { try { @@ -150,7 +148,6 @@ class Dispatcher( } } else false } else false - } override val toString: String = Logging.simpleName(this) + "[" + id + "]" } diff --git a/actor/src/main/scala/org/apache/pekko/dispatch/Dispatchers.scala b/actor/src/main/scala/org/apache/pekko/dispatch/Dispatchers.scala index 06d7c2f5106..e1bc5eda6a9 100644 --- a/actor/src/main/scala/org/apache/pekko/dispatch/Dispatchers.scala +++ b/actor/src/main/scala/org/apache/pekko/dispatch/Dispatchers.scala @@ -82,7 +82,7 @@ object Dispatchers { * Get (possibly aliased) dispatcher config. Returns empty config if not found. */ @tailrec - private[pekko] def getConfig(config: Config, id: String, depth: Int = 0): Config = { + private[pekko] def getConfig(config: Config, id: String, depth: Int = 0): Config = if (depth > MaxDispatcherAliasDepth) ConfigFactory.empty(s"Didn't find dispatcher config after $MaxDispatcherAliasDepth aliases") else if (config.hasPath(id)) { @@ -92,7 +92,6 @@ object Dispatchers { case unexpected => ConfigFactory.empty(s"Expected either config or alias at [$id] but found [$unexpected]") } } else ConfigFactory.empty(s"Dispatcher [$id] not configured") - } } /** @@ -213,9 +212,8 @@ class Dispatchers @InternalApi private[pekko] ( /** * INTERNAL API */ - private[pekko] def config(id: String): Config = { + private[pekko] def config(id: String): Config = config(id, settings.config.getConfig(id)) - } /** * INTERNAL API diff --git a/actor/src/main/scala/org/apache/pekko/dispatch/ForkJoinExecutorConfigurator.scala b/actor/src/main/scala/org/apache/pekko/dispatch/ForkJoinExecutorConfigurator.scala index 661dfb8dd70..8ad74053490 100644 --- a/actor/src/main/scala/org/apache/pekko/dispatch/ForkJoinExecutorConfigurator.scala +++ b/actor/src/main/scala/org/apache/pekko/dispatch/ForkJoinExecutorConfigurator.scala @@ -99,7 +99,7 @@ class ForkJoinExecutorConfigurator(config: Config, prerequisites: DispatcherPrer private def pekkoJdk9ForkJoinPoolClassOpt: Option[Class[_]] = Try(Class.forName("org.apache.pekko.dispatch.PekkoJdk9ForkJoinPool")).toOption - private lazy val pekkoJdk9ForkJoinPoolHandleOpt: Option[MethodHandle] = { + private lazy val pekkoJdk9ForkJoinPoolHandleOpt: Option[MethodHandle] = if (JavaVersion.majorVersion == 8) { None } else { @@ -111,7 +111,6 @@ class ForkJoinExecutorConfigurator(config: Config, prerequisites: DispatcherPrer methodHandleLookup.findConstructor(clz, mt) } } - } def this(threadFactory: ForkJoinPool.ForkJoinWorkerThreadFactory, parallelism: Int) = this(threadFactory, parallelism, asyncMode = true) diff --git a/actor/src/main/scala/org/apache/pekko/dispatch/Mailbox.scala b/actor/src/main/scala/org/apache/pekko/dispatch/Mailbox.scala index b9df8ee00d7..0a226f66dd9 100644 --- a/actor/src/main/scala/org/apache/pekko/dispatch/Mailbox.scala +++ b/actor/src/main/scala/org/apache/pekko/dispatch/Mailbox.scala @@ -226,17 +226,16 @@ private[pekko] abstract class Mailbox(val messageQueue: MessageQueue) case _ => hasSystemMessageHint || hasSystemMessages } - override final def run(): Unit = { - try { + override final def run(): Unit = + try if (!isClosed) { // Volatile read, needed here processAllSystemMessages() // First, deal with any system messages processMailbox() // Then deal with messages } - } finally { + finally { setAsIdle() // Volatile write, needed here dispatcher.registerForExecution(this, false, false) } - } override final def getRawResult(): Unit = () override final def setRawResult(unit: Unit): Unit = () @@ -514,7 +513,7 @@ trait QueueBasedMessageQueue extends MessageQueue with MultipleConsumerSemantics def queue: Queue[Envelope] def numberOfMessages = queue.size def hasMessages = !queue.isEmpty - def cleanUp(owner: ActorRef, deadLetters: MessageQueue): Unit = { + def cleanUp(owner: ActorRef, deadLetters: MessageQueue): Unit = if (hasMessages) { var envelope = dequeue() while (envelope ne null) { @@ -522,7 +521,6 @@ trait QueueBasedMessageQueue extends MessageQueue with MultipleConsumerSemantics envelope = dequeue() } } - } } /** @@ -989,11 +987,10 @@ object BoundedControlAwareMailbox { private def signalNotFull(): Unit = { putLock.lock() - try { + try notFull.signal() - } finally { + finally putLock.unlock() - } } private final def enqueueWithTimeout(q: Queue[Envelope], receiver: ActorRef, envelope: Envelope): Unit = { @@ -1018,9 +1015,8 @@ object BoundedControlAwareMailbox { true } - } finally { + } finally putLock.unlock() - } if (!inserted) { receiver diff --git a/actor/src/main/scala/org/apache/pekko/dispatch/Mailboxes.scala b/actor/src/main/scala/org/apache/pekko/dispatch/Mailboxes.scala index 428cba3c18b..d2440ecc266 100644 --- a/actor/src/main/scala/org/apache/pekko/dispatch/Mailboxes.scala +++ b/actor/src/main/scala/org/apache/pekko/dispatch/Mailboxes.scala @@ -220,7 +220,7 @@ private[pekko] class Mailboxes( case Some(s) => s } - private def lookupConfigurator(id: String): MailboxType = { + private def lookupConfigurator(id: String): MailboxType = mailboxTypeConfigurators.get(id) match { case null => // It doesn't matter if we create a mailbox type configurator that isn't used due to concurrent lookup. @@ -276,7 +276,6 @@ private[pekko] class Mailboxes( case existing => existing } - } private val defaultMailboxConfig = settings.config.getConfig(DefaultMailboxId) @@ -301,10 +300,9 @@ private[pekko] class Mailboxes( */ private[pekko] final def stashCapacity(dispatcher: String, mailbox: String): Int = { - @tailrec def updateCache(cache: Map[String, Int], key: String, value: Int): Boolean = { + @tailrec def updateCache(cache: Map[String, Int], key: String, value: Int): Boolean = stashCapacityCache.compareAndSet(cache, cache.updated(key, value)) || updateCache(stashCapacityCache.get, key, value) // recursive, try again - } if (dispatcher == Dispatchers.DefaultDispatcherId && mailbox == Mailboxes.DefaultMailboxId) defaultStashCapacity diff --git a/actor/src/main/scala/org/apache/pekko/dispatch/ThreadPoolBuilder.scala b/actor/src/main/scala/org/apache/pekko/dispatch/ThreadPoolBuilder.scala index b11f9aa42a0..036a9c6b45f 100644 --- a/actor/src/main/scala/org/apache/pekko/dispatch/ThreadPoolBuilder.scala +++ b/actor/src/main/scala/org/apache/pekko/dispatch/ThreadPoolBuilder.scala @@ -231,7 +231,7 @@ trait ExecutorServiceDelegate extends ExecutorService { def execute(command: Runnable) = executor.execute(command) - def shutdown(): Unit = { executor.shutdown() } + def shutdown(): Unit = executor.shutdown() def shutdownNow() = executor.shutdownNow() @@ -264,8 +264,7 @@ trait ExecutorServiceDelegate extends ExecutorService { * (CallerRunsPolicy silently discards the runnable in this case, which is arguably broken) */ class SaneRejectedExecutionHandler extends RejectedExecutionHandler { - def rejectedExecution(runnable: Runnable, threadPoolExecutor: ThreadPoolExecutor): Unit = { + def rejectedExecution(runnable: Runnable, threadPoolExecutor: ThreadPoolExecutor): Unit = if (threadPoolExecutor.isShutdown) throw new RejectedExecutionException("Shutdown") else runnable.run() - } } diff --git a/actor/src/main/scala/org/apache/pekko/dispatch/affinity/AffinityPool.scala b/actor/src/main/scala/org/apache/pekko/dispatch/affinity/AffinityPool.scala index 256a1686733..6703cee7038 100644 --- a/actor/src/main/scala/org/apache/pekko/dispatch/affinity/AffinityPool.scala +++ b/actor/src/main/scala/org/apache/pekko/dispatch/affinity/AffinityPool.scala @@ -79,7 +79,7 @@ private[affinity] object AffinityPool { def isIdling: Boolean = idling - def idle(): Unit = { + def idle(): Unit = (state: @switch) match { case Initial => idling = true @@ -99,7 +99,6 @@ private[affinity] object AffinityPool { LockSupport.parkNanos(parkPeriodNs) parkPeriodNs = Math.min(parkPeriodNs << 1, maxParkPeriodNs) } - } def reset(): Unit = { idling = false @@ -201,11 +200,10 @@ private[pekko] class AffinityPool( override def awaitTermination(timeout: Long, unit: TimeUnit): Boolean = { // recurse until pool is terminated or time out reached @tailrec - def awaitTermination(nanos: Long): Boolean = { + def awaitTermination(nanos: Long): Boolean = if (poolState == Terminated) true else if (nanos <= 0) false else awaitTermination(terminationCondition.awaitNanos(nanos)) - } bookKeepingLock.withGuard { // need to hold the lock to avoid monitor exception @@ -290,9 +288,8 @@ private[pekko] class AffinityPool( try { runLoop() abruptTermination = false // if we have reached here, our termination is not due to an exception - } finally { + } finally onWorkerExit(this, abruptTermination) - } } def stop(): Unit = if (!thread.isInterrupted) thread.interrupt() diff --git a/actor/src/main/scala/org/apache/pekko/dispatch/sysmsg/SystemMessage.scala b/actor/src/main/scala/org/apache/pekko/dispatch/sysmsg/SystemMessage.scala index 1e7b3e2ae13..2363879d7ba 100644 --- a/actor/src/main/scala/org/apache/pekko/dispatch/sysmsg/SystemMessage.scala +++ b/actor/src/main/scala/org/apache/pekko/dispatch/sysmsg/SystemMessage.scala @@ -35,14 +35,13 @@ private[pekko] object SystemMessageList { if (head eq null) acc else sizeInner(head.next, acc + 1) @tailrec - private[sysmsg] def reverseInner(head: SystemMessage, acc: SystemMessage): SystemMessage = { + private[sysmsg] def reverseInner(head: SystemMessage, acc: SystemMessage): SystemMessage = if (head eq null) acc else { val next = head.next head.next = acc reverseInner(next, head) } - } } /** diff --git a/actor/src/main/scala/org/apache/pekko/event/AddressTerminatedTopic.scala b/actor/src/main/scala/org/apache/pekko/event/AddressTerminatedTopic.scala index 0691cebde00..1ddd5a0e151 100644 --- a/actor/src/main/scala/org/apache/pekko/event/AddressTerminatedTopic.scala +++ b/actor/src/main/scala/org/apache/pekko/event/AddressTerminatedTopic.scala @@ -64,8 +64,7 @@ private[pekko] final class AddressTerminatedTopic extends Extension { unsubscribe(subscriber) // retry } - def publish(msg: AddressTerminated): Unit = { - subscribers.get.foreach { _.tell(msg, ActorRef.noSender) } - } + def publish(msg: AddressTerminated): Unit = + subscribers.get.foreach(_.tell(msg, ActorRef.noSender)) } diff --git a/actor/src/main/scala/org/apache/pekko/event/DeadLetterListener.scala b/actor/src/main/scala/org/apache/pekko/event/DeadLetterListener.scala index 398dba099b2..5868502bc3c 100644 --- a/actor/src/main/scala/org/apache/pekko/event/DeadLetterListener.scala +++ b/actor/src/main/scala/org/apache/pekko/event/DeadLetterListener.scala @@ -52,7 +52,7 @@ class DeadLetterListener extends Actor { override def postStop(): Unit = eventStream.unsubscribe(self) - private def incrementCount(): Unit = { + private def incrementCount(): Unit = // `count` is public API (for unknown reason) so for backwards compatibility reasons we // can't change it to Long if (count == Int.MaxValue) { @@ -60,7 +60,6 @@ class DeadLetterListener extends Actor { count = 1 } else count += 1 - } def receive: Receive = if (isAlwaysLoggingDeadLetters) receiveWithAlwaysLogging @@ -147,15 +146,13 @@ class DeadLetterListener extends Actor { ActorLogMarker.deadLetter(messageStr))) } - private def isReal(snd: ActorRef): Boolean = { + private def isReal(snd: ActorRef): Boolean = (snd ne ActorRef.noSender) && (snd ne context.system.deadLetters) && !snd.isInstanceOf[DeadLetterActorRef] - } - private def isWrappedSuppressed(d: AllDeadLetters): Boolean = { + private def isWrappedSuppressed(d: AllDeadLetters): Boolean = d.message match { case w: WrappedMessage if w.message.isInstanceOf[DeadLetterSuppression] => true case _ => false } - } } diff --git a/actor/src/main/scala/org/apache/pekko/event/EventBus.scala b/actor/src/main/scala/org/apache/pekko/event/EventBus.scala index ae11e7235d0..a924b49325b 100644 --- a/actor/src/main/scala/org/apache/pekko/event/EventBus.scala +++ b/actor/src/main/scala/org/apache/pekko/event/EventBus.scala @@ -196,7 +196,7 @@ trait SubchannelClassification { this: EventBus => private[pekko] def hasSubscriptions(subscriber: Subscriber): Boolean = // FIXME binary incompatible, but I think it is safe to filter out this problem, // since it is only called from new functionality in EventStreamUnsubscriber - cache.values.exists { _ contains subscriber } + cache.values.exists(_ contains subscriber) private def removeFromCache(changes: immutable.Seq[(Classifier, Set[Subscriber])]): Unit = cache = changes.foldLeft(cache) { @@ -361,11 +361,10 @@ trait ManagedActorClassification { this: ActorEventBus with ActorClassifier => } } - try { + try dissociateAsMonitored(actor) - } finally { + finally dissociateAsMonitor(actor) - } } @tailrec @@ -397,12 +396,11 @@ trait ManagedActorClassification { this: ActorEventBus with ActorClassifier => */ protected def mapSize: Int - def publish(event: Event): Unit = { + def publish(event: Event): Unit = mappings.get.backing.get(classify(event)) match { case None => () - case Some(refs) => refs.foreach { _ ! event } + case Some(refs) => refs.foreach(_ ! event) } - } def subscribe(subscriber: Subscriber, to: Classifier): Boolean = if (subscriber eq null) throw new IllegalArgumentException("Subscriber is null") diff --git a/actor/src/main/scala/org/apache/pekko/event/EventStream.scala b/actor/src/main/scala/org/apache/pekko/event/EventStream.scala index 90ace42e0e1..3c84524208a 100644 --- a/actor/src/main/scala/org/apache/pekko/event/EventStream.scala +++ b/actor/src/main/scala/org/apache/pekko/event/EventStream.scala @@ -48,10 +48,9 @@ class EventStream(sys: ActorSystem, private val debug: Boolean) extends LoggingB protected def classify(event: Any): Class[_] = event.getClass - protected def publish(event: Any, subscriber: ActorRef) = { + protected def publish(event: Any, subscriber: ActorRef) = if (sys == null && subscriber.isTerminated) unsubscribe(subscriber) else subscriber ! event - } override def subscribe(subscriber: ActorRef, channel: Class[_]): Boolean = { if (subscriber eq null) throw new IllegalArgumentException("subscriber is null") @@ -91,7 +90,7 @@ class EventStream(sys: ActorSystem, private val debug: Boolean) extends LoggingB * INTERNAL API */ @tailrec - final private[pekko] def initUnsubscriber(unsubscriber: ActorRef): Boolean = { + final private[pekko] def initUnsubscriber(unsubscriber: ActorRef): Boolean = // sys may be null for backwards compatibility reasons if (sys eq null) false else @@ -122,13 +121,12 @@ class EventStream(sys: ActorSystem, private val debug: Boolean) extends LoggingB s"not using unsubscriber $unsubscriber, because already initialized with $presentUnsubscriber")) false } - } /** * INTERNAL API */ @tailrec - private def registerWithUnsubscriber(subscriber: ActorRef): Unit = { + private def registerWithUnsubscriber(subscriber: ActorRef): Unit = // sys may be null for backwards compatibility reasons if (sys ne null) initiallySubscribedOrUnsubscriber.get match { case value @ Left(subscribers) => @@ -138,7 +136,6 @@ class EventStream(sys: ActorSystem, private val debug: Boolean) extends LoggingB case Right(unsubscriber) => unsubscriber ! EventStreamUnsubscriber.Register(subscriber) } - } /** * INTERNAL API @@ -148,7 +145,7 @@ class EventStream(sys: ActorSystem, private val debug: Boolean) extends LoggingB * catch up and perform the appropriate operation. */ @tailrec - private def unregisterIfNoMoreSubscribedChannels(subscriber: ActorRef): Unit = { + private def unregisterIfNoMoreSubscribedChannels(subscriber: ActorRef): Unit = // sys may be null for backwards compatibility reasons if (sys ne null) initiallySubscribedOrUnsubscriber.get match { case value @ Left(subscribers) => @@ -158,6 +155,5 @@ class EventStream(sys: ActorSystem, private val debug: Boolean) extends LoggingB case Right(unsubscriber) => unsubscriber ! EventStreamUnsubscriber.UnregisterIfNoMoreSubscribedChannels(subscriber) } - } } diff --git a/actor/src/main/scala/org/apache/pekko/event/Logging.scala b/actor/src/main/scala/org/apache/pekko/event/Logging.scala index cdf49f7b927..9d4697c93b6 100644 --- a/actor/src/main/scala/org/apache/pekko/event/Logging.scala +++ b/actor/src/main/scala/org/apache/pekko/event/Logging.scala @@ -132,26 +132,24 @@ trait LoggingBus extends ActorEventBus { for { loggerName <- defaultLoggers if loggerName != StandardOutLogger.getClass.getName - } yield { - system.dynamicAccess - .getClassFor[Actor](loggerName) - .map { actorClass => - addLogger(system, actorClass, level, logName) - } - .recover { - case e => - throw new ConfigurationException( - "Logger specified in config can't be loaded [" + loggerName + - "] due to [" + e.toString + "]", - e) - } - .get - } + } yield system.dynamicAccess + .getClassFor[Actor](loggerName) + .map { actorClass => + addLogger(system, actorClass, level, logName) + } + .recover { + case e => + throw new ConfigurationException( + "Logger specified in config can't be loaded [" + loggerName + + "] due to [" + e.toString + "]", + e) + } + .get guard.withGuard { loggers = myloggers _logLevel = level } - try { + try if (system.settings.DebugUnhandledMessage) subscribe( system.systemActorOf( @@ -162,7 +160,7 @@ trait LoggingBus extends ActorEventBus { } }), "UnhandledMessageForwarder"), classOf[UnhandledMessage]) - } catch { + catch { case _: InvalidActorNameException => // ignore if it is already running } publish(Debug(logName, this.getClass, "Default Loggers started")) @@ -330,9 +328,9 @@ object LogSource { implicit val fromActorRef: LogSource[ActorRef] = new LogSource[ActorRef] { def genString(a: ActorRef) = a.path.toString override def genString(a: ActorRef, system: ActorSystem) = - try { + try a.path.toStringWithAddress(system.asInstanceOf[ExtendedActorSystem].provider.getDefaultAddress) - } catch { + catch { // it can fail if the ActorSystem (remoting) is not completely started yet case NonFatal(_) => a.path.toString } @@ -529,13 +527,12 @@ object Logging { * Returns the LogLevel associated with the given event class. * Defaults to DebugLevel. */ - def levelFor(eventClass: Class[_ <: LogEvent]): LogLevel = { + def levelFor(eventClass: Class[_ <: LogEvent]): LogLevel = if (classOf[Error].isAssignableFrom(eventClass)) ErrorLevel else if (classOf[Warning].isAssignableFrom(eventClass)) WarningLevel else if (classOf[Info].isAssignableFrom(eventClass)) InfoLevel else if (classOf[Debug].isAssignableFrom(eventClass)) DebugLevel else DebugLevel - } /** * Returns the event class associated with the given LogLevel @@ -1223,7 +1220,7 @@ trait LoggingAdapter { * Log message at error level, including the exception that caused the error. * @see [[LoggingAdapter]] */ - def error(cause: Throwable, message: String): Unit = { if (isErrorEnabled) notifyError(cause, message) } + def error(cause: Throwable, message: String): Unit = if (isErrorEnabled) notifyError(cause, message) /** * Message template with 1 replacement argument. @@ -1232,39 +1229,35 @@ trait LoggingAdapter { * there are more than four arguments. * @see [[LoggingAdapter]] */ - def error(cause: Throwable, template: String, arg1: Any): Unit = { + def error(cause: Throwable, template: String, arg1: Any): Unit = if (isErrorEnabled) notifyError(cause, format1(template, arg1)) - } /** * Message template with 2 replacement arguments. * @see [[LoggingAdapter]] */ - def error(cause: Throwable, template: String, arg1: Any, arg2: Any): Unit = { + def error(cause: Throwable, template: String, arg1: Any, arg2: Any): Unit = if (isErrorEnabled) notifyError(cause, format(template, arg1, arg2)) - } /** * Message template with 3 replacement arguments. * @see [[LoggingAdapter]] */ - def error(cause: Throwable, template: String, arg1: Any, arg2: Any, arg3: Any): Unit = { + def error(cause: Throwable, template: String, arg1: Any, arg2: Any, arg3: Any): Unit = if (isErrorEnabled) notifyError(cause, format(template, arg1, arg2, arg3)) - } /** * Message template with 4 replacement arguments. * @see [[LoggingAdapter]] */ - def error(cause: Throwable, template: String, arg1: Any, arg2: Any, arg3: Any, arg4: Any): Unit = { + def error(cause: Throwable, template: String, arg1: Any, arg2: Any, arg3: Any, arg4: Any): Unit = if (isErrorEnabled) notifyError(cause, format(template, arg1, arg2, arg3, arg4)) - } /** * Log message at error level, without providing the exception that caused the error. * @see [[LoggingAdapter]] */ - def error(message: String): Unit = { if (isErrorEnabled) notifyError(message) } + def error(message: String): Unit = if (isErrorEnabled) notifyError(message) /** * Message template with 1 replacement argument. @@ -1273,39 +1266,35 @@ trait LoggingAdapter { * there are more than four arguments. * @see [[LoggingAdapter]] */ - def error(template: String, arg1: Any): Unit = { if (isErrorEnabled) notifyError(format1(template, arg1)) } + def error(template: String, arg1: Any): Unit = if (isErrorEnabled) notifyError(format1(template, arg1)) /** * Message template with 2 replacement arguments. * @see [[LoggingAdapter]] */ - def error(template: String, arg1: Any, arg2: Any): Unit = { + def error(template: String, arg1: Any, arg2: Any): Unit = if (isErrorEnabled) notifyError(format(template, arg1, arg2)) - } /** * Message template with 3 replacement arguments. * @see [[LoggingAdapter]] */ - def error(template: String, arg1: Any, arg2: Any, arg3: Any): Unit = { + def error(template: String, arg1: Any, arg2: Any, arg3: Any): Unit = if (isErrorEnabled) notifyError(format(template, arg1, arg2, arg3)) - } /** * Message template with 4 replacement arguments. * @see [[LoggingAdapter]] */ - def error(template: String, arg1: Any, arg2: Any, arg3: Any, arg4: Any): Unit = { + def error(template: String, arg1: Any, arg2: Any, arg3: Any, arg4: Any): Unit = if (isErrorEnabled) notifyError(format(template, arg1, arg2, arg3, arg4)) - } /** * Log message at warning level, including the exception that indicated the warning. * @see [[LoggingAdapter]] */ - def warning(cause: Throwable, message: String): Unit = { + def warning(cause: Throwable, message: String): Unit = if (isWarningEnabled) notifyWarning(cause, message) - } /** * Message template with 1 replacement argument. @@ -1314,39 +1303,35 @@ trait LoggingAdapter { * there are more than four arguments. * @see [[LoggingAdapter]] */ - def warning(cause: Throwable, template: String, arg1: Any): Unit = { + def warning(cause: Throwable, template: String, arg1: Any): Unit = if (isWarningEnabled) notifyWarning(cause, format1(template, arg1)) - } /** * Message template with 2 replacement arguments. * @see [[LoggingAdapter]] */ - def warning(cause: Throwable, template: String, arg1: Any, arg2: Any): Unit = { + def warning(cause: Throwable, template: String, arg1: Any, arg2: Any): Unit = if (isWarningEnabled) notifyWarning(cause, format(template, arg1, arg2)) - } /** * Message template with 3 replacement arguments. * @see [[LoggingAdapter]] */ - def warning(cause: Throwable, template: String, arg1: Any, arg2: Any, arg3: Any): Unit = { + def warning(cause: Throwable, template: String, arg1: Any, arg2: Any, arg3: Any): Unit = if (isWarningEnabled) notifyWarning(cause, format(template, arg1, arg2, arg3)) - } /** * Message template with 4 replacement arguments. * @see [[LoggingAdapter]] */ - def warning(cause: Throwable, template: String, arg1: Any, arg2: Any, arg3: Any, arg4: Any): Unit = { + def warning(cause: Throwable, template: String, arg1: Any, arg2: Any, arg3: Any, arg4: Any): Unit = if (isWarningEnabled) notifyWarning(cause, format(template, arg1, arg2, arg3, arg4)) - } /** * Log message at warning level. * @see [[LoggingAdapter]] */ - def warning(message: String): Unit = { if (isWarningEnabled) notifyWarning(message) } + def warning(message: String): Unit = if (isWarningEnabled) notifyWarning(message) /** * Message template with 1 replacement argument. @@ -1355,37 +1340,34 @@ trait LoggingAdapter { * there are more than four arguments. * @see [[LoggingAdapter]] */ - def warning(template: String, arg1: Any): Unit = { if (isWarningEnabled) notifyWarning(format1(template, arg1)) } + def warning(template: String, arg1: Any): Unit = if (isWarningEnabled) notifyWarning(format1(template, arg1)) /** * Message template with 2 replacement arguments. * @see [[LoggingAdapter]] */ - def warning(template: String, arg1: Any, arg2: Any): Unit = { + def warning(template: String, arg1: Any, arg2: Any): Unit = if (isWarningEnabled) notifyWarning(format(template, arg1, arg2)) - } /** * Message template with 3 replacement arguments. * @see [[LoggingAdapter]] */ - def warning(template: String, arg1: Any, arg2: Any, arg3: Any): Unit = { + def warning(template: String, arg1: Any, arg2: Any, arg3: Any): Unit = if (isWarningEnabled) notifyWarning(format(template, arg1, arg2, arg3)) - } /** * Message template with 4 replacement arguments. * @see [[LoggingAdapter]] */ - def warning(template: String, arg1: Any, arg2: Any, arg3: Any, arg4: Any): Unit = { + def warning(template: String, arg1: Any, arg2: Any, arg3: Any, arg4: Any): Unit = if (isWarningEnabled) notifyWarning(format(template, arg1, arg2, arg3, arg4)) - } /** * Log message at info level. * @see [[LoggingAdapter]] */ - def info(message: String): Unit = { if (isInfoEnabled) notifyInfo(message) } + def info(message: String): Unit = if (isInfoEnabled) notifyInfo(message) /** * Message template with 1 replacement argument. @@ -1394,37 +1376,34 @@ trait LoggingAdapter { * there are more than four arguments. * @see [[LoggingAdapter]] */ - def info(template: String, arg1: Any): Unit = { if (isInfoEnabled) notifyInfo(format1(template, arg1)) } + def info(template: String, arg1: Any): Unit = if (isInfoEnabled) notifyInfo(format1(template, arg1)) /** * Message template with 2 replacement arguments. * @see [[LoggingAdapter]] */ - def info(template: String, arg1: Any, arg2: Any): Unit = { + def info(template: String, arg1: Any, arg2: Any): Unit = if (isInfoEnabled) notifyInfo(format(template, arg1, arg2)) - } /** * Message template with 3 replacement arguments. * @see [[LoggingAdapter]] */ - def info(template: String, arg1: Any, arg2: Any, arg3: Any): Unit = { + def info(template: String, arg1: Any, arg2: Any, arg3: Any): Unit = if (isInfoEnabled) notifyInfo(format(template, arg1, arg2, arg3)) - } /** * Message template with 4 replacement arguments. * @see [[LoggingAdapter]] */ - def info(template: String, arg1: Any, arg2: Any, arg3: Any, arg4: Any): Unit = { + def info(template: String, arg1: Any, arg2: Any, arg3: Any, arg4: Any): Unit = if (isInfoEnabled) notifyInfo(format(template, arg1, arg2, arg3, arg4)) - } /** * Log message at debug level. * @see [[LoggingAdapter]] */ - def debug(message: String): Unit = { if (isDebugEnabled) notifyDebug(message) } + def debug(message: String): Unit = if (isDebugEnabled) notifyDebug(message) /** * Message template with 1 replacement argument. @@ -1433,36 +1412,33 @@ trait LoggingAdapter { * there are more than four arguments. * @see [[LoggingAdapter]] */ - def debug(template: String, arg1: Any): Unit = { if (isDebugEnabled) notifyDebug(format1(template, arg1)) } + def debug(template: String, arg1: Any): Unit = if (isDebugEnabled) notifyDebug(format1(template, arg1)) /** * Message template with 2 replacement arguments. * @see [[LoggingAdapter]] */ - def debug(template: String, arg1: Any, arg2: Any): Unit = { + def debug(template: String, arg1: Any, arg2: Any): Unit = if (isDebugEnabled) notifyDebug(format(template, arg1, arg2)) - } /** * Message template with 3 replacement arguments. * @see [[LoggingAdapter]] */ - def debug(template: String, arg1: Any, arg2: Any, arg3: Any): Unit = { + def debug(template: String, arg1: Any, arg2: Any, arg3: Any): Unit = if (isDebugEnabled) notifyDebug(format(template, arg1, arg2, arg3)) - } /** * Message template with 4 replacement arguments. * @see [[LoggingAdapter]] */ - def debug(template: String, arg1: Any, arg2: Any, arg3: Any, arg4: Any): Unit = { + def debug(template: String, arg1: Any, arg2: Any, arg3: Any, arg4: Any): Unit = if (isDebugEnabled) notifyDebug(format(template, arg1, arg2, arg3, arg4)) - } /** * Log message at the specified log level. */ - def log(level: Logging.LogLevel, message: String): Unit = { if (isEnabled(level)) notifyLog(level, message) } + def log(level: Logging.LogLevel, message: String): Unit = if (isEnabled(level)) notifyLog(level, message) /** * Message template with 1 replacement argument. @@ -1470,30 +1446,26 @@ trait LoggingAdapter { * If `arg1` is an `Array` it will be expanded into replacement arguments, which is useful when * there are more than four arguments. */ - def log(level: Logging.LogLevel, template: String, arg1: Any): Unit = { + def log(level: Logging.LogLevel, template: String, arg1: Any): Unit = if (isEnabled(level)) notifyLog(level, format1(template, arg1)) - } /** * Message template with 2 replacement arguments. */ - def log(level: Logging.LogLevel, template: String, arg1: Any, arg2: Any): Unit = { + def log(level: Logging.LogLevel, template: String, arg1: Any, arg2: Any): Unit = if (isEnabled(level)) notifyLog(level, format(template, arg1, arg2)) - } /** * Message template with 3 replacement arguments. */ - def log(level: Logging.LogLevel, template: String, arg1: Any, arg2: Any, arg3: Any): Unit = { + def log(level: Logging.LogLevel, template: String, arg1: Any, arg2: Any, arg3: Any): Unit = if (isEnabled(level)) notifyLog(level, format(template, arg1, arg2, arg3)) - } /** * Message template with 4 replacement arguments. */ - def log(level: Logging.LogLevel, template: String, arg1: Any, arg2: Any, arg3: Any, arg4: Any): Unit = { + def log(level: Logging.LogLevel, template: String, arg1: Any, arg2: Any, arg3: Any, arg4: Any): Unit = if (isEnabled(level)) notifyLog(level, format(template, arg1, arg2, arg3, arg4)) - } /** * @return true if the specified log level is enabled @@ -1524,9 +1496,8 @@ trait LoggingAdapter { case x => format(t, x) } - def format(t: String, arg: Any*): String = { + def format(t: String, arg: Any*): String = formatImpl(t, arg) - } private def formatImpl(t: String, arg: Seq[Any]): String = { val sb = new java.lang.StringBuilder(64) @@ -1986,7 +1957,7 @@ class MarkerLoggingAdapter( /** * Log message at the specified log level. */ - def log(marker: LogMarker, level: Logging.LogLevel, message: String): Unit = { + def log(marker: LogMarker, level: Logging.LogLevel, message: String): Unit = level match { case Logging.DebugLevel => debug(marker, message) case Logging.InfoLevel => info(marker, message) @@ -1994,7 +1965,6 @@ class MarkerLoggingAdapter( case Logging.ErrorLevel => error(marker, message) case _ => } - } // Copy of LoggingAdapter.format1 due to binary compatibility restrictions private def format1(t: String, arg: Any): String = arg match { diff --git a/actor/src/main/scala/org/apache/pekko/io/Dns.scala b/actor/src/main/scala/org/apache/pekko/io/Dns.scala index c728e525a2b..231b1c92127 100644 --- a/actor/src/main/scala/org/apache/pekko/io/Dns.scala +++ b/actor/src/main/scala/org/apache/pekko/io/Dns.scala @@ -104,13 +104,12 @@ object Dns extends ExtensionId[DnsExt] with ExtensionIdProvider { } @deprecated("Use cached(DnsProtocol.Resolve)", "Akka 2.6.0") - def apply(newProtocol: DnsProtocol.Resolved): Resolved = { + def apply(newProtocol: DnsProtocol.Resolved): Resolved = Resolved(newProtocol.name, newProtocol.records.collect { case r: ARecord => r.ip case r: AAAARecord => r.ip }) - } } /** @@ -118,9 +117,8 @@ object Dns extends ExtensionId[DnsExt] with ExtensionIdProvider { * the pekko.actor.io.dns.resolver that is configured. */ @deprecated("use cached(DnsProtocol.Resolve)", "Akka 2.6.0") - def cached(name: String)(system: ActorSystem): Option[Resolved] = { + def cached(name: String)(system: ActorSystem): Option[Resolved] = Dns(system).cache.cached(name) - } /** * If an entry is cached return it immediately. If it is not then @@ -128,25 +126,22 @@ object Dns extends ExtensionId[DnsExt] with ExtensionIdProvider { */ @deprecated("use resolve(DnsProtocol.Resolve)", "Akka 2.6.0") @nowarn("msg=deprecated") - def resolve(name: String)(system: ActorSystem, sender: ActorRef): Option[Resolved] = { + def resolve(name: String)(system: ActorSystem, sender: ActorRef): Option[Resolved] = Dns(system).cache.resolve(name)(system, sender) - } /** * Lookup if a DNS resolved is cached. The exact behavior of caching will depend on * the pekko.actor.io.dns.resolver that is configured. */ - def cached(name: DnsProtocol.Resolve)(system: ActorSystem): Option[DnsProtocol.Resolved] = { + def cached(name: DnsProtocol.Resolve)(system: ActorSystem): Option[DnsProtocol.Resolved] = Dns(system).cache.cached(name) - } /** * If an entry is cached return it immediately. If it is not then * trigger a resolve and return None. */ - def resolve(name: DnsProtocol.Resolve, system: ActorSystem, sender: ActorRef): Option[DnsProtocol.Resolved] = { + def resolve(name: DnsProtocol.Resolve, system: ActorSystem, sender: ActorRef): Option[DnsProtocol.Resolved] = Dns(system).cache.resolve(name, system, sender) - } override def lookup = Dns @@ -175,7 +170,7 @@ class DnsExt private[pekko] (val system: ExtendedActorSystem, resolverName: Stri */ @InternalApi @nowarn("msg=deprecated") - private[pekko] def loadAsyncDns(managerName: String): ActorRef = { + private[pekko] def loadAsyncDns(managerName: String): ActorRef = // This can't pass in `this` as then AsyncDns would pick up the system settings asyncDns.computeIfAbsent( managerName, @@ -199,7 +194,6 @@ class DnsExt private[pekko] (val system: ExtendedActorSystem, resolverName: Stri name = managerName) } }) - } /** * INTERNAL API @@ -239,11 +233,10 @@ class DnsExt private[pekko] (val system: ExtendedActorSystem, resolverName: Stri val cache: Dns = provider.cache // System DNS manager - val manager: ActorRef = { + val manager: ActorRef = system.systemActorOf( props = Props(provider.managerClass, this).withDeploy(Deploy.local).withDispatcher(Settings.Dispatcher), name = managerName) - } // System DNS manager def getResolver: ActorRef = manager diff --git a/actor/src/main/scala/org/apache/pekko/io/InetAddressDnsResolver.scala b/actor/src/main/scala/org/apache/pekko/io/InetAddressDnsResolver.scala index 1dda655cfe4..05f8e852a4c 100644 --- a/actor/src/main/scala/org/apache/pekko/io/InetAddressDnsResolver.scala +++ b/actor/src/main/scala/org/apache/pekko/io/InetAddressDnsResolver.scala @@ -86,25 +86,23 @@ class InetAddressDnsResolver(cache: SimpleDnsCache, config: Config) extends Acto Never } - private def parsePolicy(n: Int): CachePolicy = { + private def parsePolicy(n: Int): CachePolicy = n match { case 0 => Never case x if x < 0 => Forever case x => Ttl.fromPositive(x.seconds) } - } private def getTtl(path: String, positive: Boolean): CachePolicy = config.getString(path) match { case "default" => if (positive) defaultCachePolicy else defaultNegativeCachePolicy case "forever" => Forever case "never" => Never - case _ => { + case _ => val finiteTtl = config .getDuration(path, TimeUnit.SECONDS) .requiring(_ > 0, s"pekko.io.dns.$path must be 'default', 'forever', 'never' or positive duration") Ttl.fromPositive(finiteTtl.seconds) - } } val positiveCachePolicy: CachePolicy = getTtl("positive-ttl", positive = true) @@ -114,13 +112,12 @@ class InetAddressDnsResolver(cache: SimpleDnsCache, config: Config) extends Acto @deprecated("Use negativeCacheDuration instead", "Akka 2.5.17") val negativeTtl: Long = toLongTtl(negativeCachePolicy) - private def toLongTtl(cp: CachePolicy): Long = { + private def toLongTtl(cp: CachePolicy): Long = cp match { case Forever => Long.MaxValue case Never => 0 case ttl: Ttl => ttl.value.toMillis } - } override def receive: Receive = { case DnsProtocol.Resolve(_, Srv) => @@ -178,11 +175,10 @@ class InetAddressDnsResolver(cache: SimpleDnsCache, config: Config) extends Acto name: String, addresses: immutable.Seq[InetAddress], ipv4: Boolean, - ipv6: Boolean): immutable.Seq[ResourceRecord] = { + ipv6: Boolean): immutable.Seq[ResourceRecord] = addresses.collect { case a: Inet4Address if ipv4 => ARecord(name, Ttl.toTll(positiveCachePolicy), a) case a: Inet6Address if ipv6 => AAAARecord(name, Ttl.toTll(positiveCachePolicy), a) } - } } diff --git a/actor/src/main/scala/org/apache/pekko/io/SelectionHandler.scala b/actor/src/main/scala/org/apache/pekko/io/SelectionHandler.scala index f6dfdd58331..bec4d70a846 100644 --- a/actor/src/main/scala/org/apache/pekko/io/SelectionHandler.scala +++ b/actor/src/main/scala/org/apache/pekko/io/SelectionHandler.scala @@ -174,7 +174,7 @@ private[io] object SelectionHandler { readyOps match { case OP_READ => connection ! ChannelReadable case OP_WRITE => connection ! ChannelWritable - case OP_READ_AND_WRITE => { connection ! ChannelWritable; connection ! ChannelReadable } + case OP_READ_AND_WRITE => connection ! ChannelWritable; connection ! ChannelReadable case x if (x & OP_ACCEPT) > 0 => connection ! ChannelAcceptable case x if (x & OP_CONNECT) > 0 => connection ! ChannelConnectable case x => log.warning("Invalid readyOps: [{}]", x) @@ -299,13 +299,12 @@ private[io] object SelectionHandler { // FIXME: Add possibility to signal failure of task to someone private abstract class Task extends Runnable { def tryRun(): Unit - def run(): Unit = { + def run(): Unit = try tryRun() catch { case _: CancelledKeyException => // ok, can be triggered while setting interest ops case NonFatal(e) => log.error(e, "Error during selector management task: [{}]", e) } - } } } } diff --git a/actor/src/main/scala/org/apache/pekko/io/SimpleDnsCache.scala b/actor/src/main/scala/org/apache/pekko/io/SimpleDnsCache.scala index b9239ab35dd..70ce574bf82 100644 --- a/actor/src/main/scala/org/apache/pekko/io/SimpleDnsCache.scala +++ b/actor/src/main/scala/org/apache/pekko/io/SimpleDnsCache.scala @@ -80,9 +80,8 @@ class SimpleDnsCache extends Dns with PeriodicCacheCleanup with NoSerializationV * INTERNAL API */ @InternalApi - private[pekko] final def get(key: (String, RequestType)): Option[Resolved] = { + private[pekko] final def get(key: (String, RequestType)): Option[Resolved] = cacheRef.get().get(key) - } @tailrec private[io] final def put(key: (String, RequestType), records: Resolved, ttl: CachePolicy): Unit = { @@ -109,12 +108,11 @@ object SimpleDnsCache { queue: immutable.SortedSet[ExpiryEntry[K]], cache: immutable.Map[K, CacheEntry[V]], clock: () => Long) { - def get(name: K): Option[V] = { + def get(name: K): Option[V] = for { e <- cache.get(name) if e.isValid(clock()) } yield e.answer - } def put(name: K, answer: V, ttl: CachePolicy): Cache[K, V] = { val until = ttl match { @@ -159,8 +157,7 @@ object SimpleDnsCache { */ @InternalApi private[io] def expiryEntryOrdering[K]() = new Ordering[ExpiryEntry[K]] { - override def compare(x: ExpiryEntry[K], y: ExpiryEntry[K]): Int = { + override def compare(x: ExpiryEntry[K], y: ExpiryEntry[K]): Int = x.until.compareTo(y.until) - } } } diff --git a/actor/src/main/scala/org/apache/pekko/io/SimpleDnsManager.scala b/actor/src/main/scala/org/apache/pekko/io/SimpleDnsManager.scala index 2d6d9a4bfa9..6ed58dff2c9 100644 --- a/actor/src/main/scala/org/apache/pekko/io/SimpleDnsManager.scala +++ b/actor/src/main/scala/org/apache/pekko/io/SimpleDnsManager.scala @@ -65,9 +65,8 @@ final class SimpleDnsManager(val ext: DnsExt) cacheCleanup.foreach(_.cleanup()) } - override def postStop(): Unit = { + override def postStop(): Unit = cleanupTimer.foreach(_.cancel()) - } } object SimpleDnsManager { diff --git a/actor/src/main/scala/org/apache/pekko/io/Tcp.scala b/actor/src/main/scala/org/apache/pekko/io/Tcp.scala index ca56d75ee40..c51417189d2 100644 --- a/actor/src/main/scala/org/apache/pekko/io/Tcp.scala +++ b/actor/src/main/scala/org/apache/pekko/io/Tcp.scala @@ -409,8 +409,8 @@ object Tcp extends ExtensionId[TcpExt] with ExtensionIdProvider { def next(): SimpleWriteCommand = current match { case null => Iterator.empty.next() - case CompoundWrite(h, t) => { current = t; h } - case x: SimpleWriteCommand => { current = null; x } + case CompoundWrite(h, t) => current = t; h + case x: SimpleWriteCommand => current = null; x } } } @@ -491,7 +491,7 @@ object Tcp extends ExtensionId[TcpExt] with ExtensionIdProvider { @InternalApi private[pekko] def causedByString = _cause - .map(t => { + .map { t => val msg = if (t.getCause == null) t.getMessage @@ -501,7 +501,7 @@ object Tcp extends ExtensionId[TcpExt] with ExtensionIdProvider { s"${t.getMessage}, caused by: ${t.getCause}, caused by: ${t.getCause.getCause}" s" because of ${t.getClass.getName}: $msg" - }) + } .getOrElse("") override def toString: String = s"CommandFailed($cmd)$causedByString" @@ -651,11 +651,10 @@ class TcpExt(system: ExtendedActorSystem) extends IO.Extension { /** */ - val manager: ActorRef = { + val manager: ActorRef = system.systemActorOf( props = Props(classOf[TcpManager], this).withDispatcher(Settings.ManagementDispatcher).withDeploy(Deploy.local), name = "IO-TCP") - } /** * Java API: retrieve a reference to the manager actor. @@ -927,7 +926,6 @@ object TcpMessage { */ def resumeAccepting(batchSize: Int): Command = ResumeAccepting(batchSize) - implicit private def fromJava[T](coll: JIterable[T]): immutable.Iterable[T] = { + implicit private def fromJava[T](coll: JIterable[T]): immutable.Iterable[T] = pekko.japi.Util.immutableSeq(coll) - } } diff --git a/actor/src/main/scala/org/apache/pekko/io/TcpConnection.scala b/actor/src/main/scala/org/apache/pekko/io/TcpConnection.scala index 6380b39147f..066a2d6429f 100644 --- a/actor/src/main/scala/org/apache/pekko/io/TcpConnection.scala +++ b/actor/src/main/scala/org/apache/pekko/io/TcpConnection.scala @@ -348,9 +348,8 @@ private[io] abstract class TcpConnection(val tcp: TcpExt, val channel: SocketCha doCloseConnection(info.handler, closeCommander, closedEvent) } - def doCloseConnection(handler: ActorRef, closeCommander: Option[ActorRef], closedEvent: ConnectionClosed): Unit = { + def doCloseConnection(handler: ActorRef, closeCommander: Option[ActorRef], closedEvent: ConnectionClosed): Unit = stopWith(CloseInformation(Set(handler) ++ closeCommander, closedEvent)) - } def handleError(handler: ActorRef, exception: IOException): Unit = { log.debug("Closing connection due to IO error {}", exception) @@ -374,7 +373,7 @@ private[io] abstract class TcpConnection(val tcp: TcpExt, val channel: SocketCha } } - def prepareAbort(): Unit = { + def prepareAbort(): Unit = try channel.socket.setSoLinger(true, 0) // causes the following close() to send TCP RST catch { case NonFatal(e) => @@ -382,13 +381,12 @@ private[io] abstract class TcpConnection(val tcp: TcpExt, val channel: SocketCha // (also affected: OS/X Java 1.6.0_37) if (TraceLogging) log.debug("setSoLinger(true, 0) failed with [{}]", e) } - // Actual channel closing is done in stopWith or postStop by calling registration.cancelAndClose() - // which makes sure the channel is flushed from the selector as well. + // Actual channel closing is done in stopWith or postStop by calling registration.cancelAndClose() + // which makes sure the channel is flushed from the selector as well. - // This is necessary because on Windows (and all platforms starting with JDK 11) the connection is merely added - // to the `cancelledKeys` of the `java.nio.channels.spi.AbstractSelector`, - // and `sun.nio.ch.SelectorImpl` will kill those from `processDeregisterQueue` after the select poll has returned. - } + // This is necessary because on Windows (and all platforms starting with JDK 11) the connection is merely added + // to the `cancelledKeys` of the `java.nio.channels.spi.AbstractSelector`, + // and `sun.nio.ch.SelectorImpl` will kill those from `processDeregisterQueue` after the select poll has returned. def stopWith(closeInfo: CloseInformation, shouldAbort: Boolean = false): Unit = { closedMessage = Some(closeInfo) diff --git a/actor/src/main/scala/org/apache/pekko/io/TcpListener.scala b/actor/src/main/scala/org/apache/pekko/io/TcpListener.scala index 32bdbe9aa10..5a9d7337d3d 100644 --- a/actor/src/main/scala/org/apache/pekko/io/TcpListener.scala +++ b/actor/src/main/scala/org/apache/pekko/io/TcpListener.scala @@ -137,7 +137,7 @@ private[io] class TcpListener( if (limit > 0) { try channel.accept() catch { - case NonFatal(e) => { log.error(e, "Accept error: could not accept new connection"); null } + case NonFatal(e) => log.error(e, "Accept error: could not accept new connection"); null } } else null if (socketChannel != null) { @@ -151,14 +151,13 @@ private[io] class TcpListener( else BatchAcceptLimit } - override def postStop(): Unit = { - try { + override def postStop(): Unit = + try if (channel.isOpen) { log.debug("Closing serverSocketChannel after being stopped") channel.close() } - } catch { + catch { case NonFatal(e) => log.debug("Error closing ServerSocketChannel: {}", e) } - } } diff --git a/actor/src/main/scala/org/apache/pekko/io/TcpOutgoingConnection.scala b/actor/src/main/scala/org/apache/pekko/io/TcpOutgoingConnection.scala index f257eceb857..d2f3a9e9be1 100644 --- a/actor/src/main/scala/org/apache/pekko/io/TcpOutgoingConnection.scala +++ b/actor/src/main/scala/org/apache/pekko/io/TcpOutgoingConnection.scala @@ -58,15 +58,14 @@ private[io] class TcpOutgoingConnection( private def stop(cause: Throwable): Unit = stopWith(CloseInformation(Set(commander), CommandFailed(connect).withCause(cause)), shouldAbort = true) - private def reportConnectFailure(thunk: => Unit): Unit = { - try { + private def reportConnectFailure(thunk: => Unit): Unit = + try thunk - } catch { + catch { case NonFatal(e) => log.debug("Could not establish connection to [{}] due to {}", remoteAddress, e) stop(e) } - } def receive: Receive = { case registration: ChannelRegistration => @@ -102,7 +101,7 @@ private[io] class TcpOutgoingConnection( } } - def register(address: InetSocketAddress, registration: ChannelRegistration): Unit = { + def register(address: InetSocketAddress, registration: ChannelRegistration): Unit = reportConnectFailure { log.debug("Attempting connection to [{}]", address) if (channel.connect(address)) @@ -112,33 +111,30 @@ private[io] class TcpOutgoingConnection( context.become(connecting(registration, tcp.Settings.FinishConnectRetries)) } } - } def connecting(registration: ChannelRegistration, remainingFinishConnectRetries: Int): Receive = { - { - case ChannelConnectable => - reportConnectFailure { - if (channel.finishConnect()) { - if (timeout.isDefined) context.setReceiveTimeout(Duration.Undefined) // Clear the timeout - log.debug("Connection established to [{}]", remoteAddress) - completeConnect(registration, commander, options) + case ChannelConnectable => + reportConnectFailure { + if (channel.finishConnect()) { + if (timeout.isDefined) context.setReceiveTimeout(Duration.Undefined) // Clear the timeout + log.debug("Connection established to [{}]", remoteAddress) + completeConnect(registration, commander, options) + } else { + if (remainingFinishConnectRetries > 0) { + context.system.scheduler.scheduleOnce(1.millisecond) { + channelRegistry.register(channel, SelectionKey.OP_CONNECT) + }(context.dispatcher) + context.become(connecting(registration, remainingFinishConnectRetries - 1)) } else { - if (remainingFinishConnectRetries > 0) { - context.system.scheduler.scheduleOnce(1.millisecond) { - channelRegistry.register(channel, SelectionKey.OP_CONNECT) - }(context.dispatcher) - context.become(connecting(registration, remainingFinishConnectRetries - 1)) - } else { - log.debug( - "Could not establish connection because finishConnect " + - "never returned true (consider increasing pekko.io.tcp.finish-connect-retries)") - stop(FinishConnectNeverReturnedTrueException) - } + log.debug( + "Could not establish connection because finishConnect " + + "never returned true (consider increasing pekko.io.tcp.finish-connect-retries)") + stop(FinishConnectNeverReturnedTrueException) } } - case ReceiveTimeout => - connectionTimeout() - } + } + case ReceiveTimeout => + connectionTimeout() } private def connectionTimeout(): Unit = { diff --git a/actor/src/main/scala/org/apache/pekko/io/Udp.scala b/actor/src/main/scala/org/apache/pekko/io/Udp.scala index 61a3f82898c..ea7a9d64edc 100644 --- a/actor/src/main/scala/org/apache/pekko/io/Udp.scala +++ b/actor/src/main/scala/org/apache/pekko/io/Udp.scala @@ -233,11 +233,10 @@ class UdpExt(system: ExtendedActorSystem) extends IO.Extension { val settings: UdpSettings = new UdpSettings(system.settings.config.getConfig("pekko.io.udp")) - val manager: ActorRef = { + val manager: ActorRef = system.systemActorOf( props = Props(classOf[UdpManager], this).withDispatcher(settings.ManagementDispatcher).withDeploy(Deploy.local), name = "IO-UDP-FF") - } /** * Java API: retrieve the UDP manager actor’s reference. diff --git a/actor/src/main/scala/org/apache/pekko/io/UdpConnected.scala b/actor/src/main/scala/org/apache/pekko/io/UdpConnected.scala index a74935ed55a..7d89f46d416 100644 --- a/actor/src/main/scala/org/apache/pekko/io/UdpConnected.scala +++ b/actor/src/main/scala/org/apache/pekko/io/UdpConnected.scala @@ -171,13 +171,12 @@ class UdpConnectedExt(system: ExtendedActorSystem) extends IO.Extension { val settings: UdpSettings = new UdpSettings(system.settings.config.getConfig("pekko.io.udp-connected")) - val manager: ActorRef = { + val manager: ActorRef = system.systemActorOf( props = Props(classOf[UdpConnectedManager], this) .withDispatcher(settings.ManagementDispatcher) .withDeploy(Deploy.local), name = "IO-UDP-CONN") - } /** * Java API: retrieve the UDP manager actor’s reference. diff --git a/actor/src/main/scala/org/apache/pekko/io/UdpConnection.scala b/actor/src/main/scala/org/apache/pekko/io/UdpConnection.scala index ad281990067..9dd14ed7159 100644 --- a/actor/src/main/scala/org/apache/pekko/io/UdpConnection.scala +++ b/actor/src/main/scala/org/apache/pekko/io/UdpConnection.scala @@ -178,10 +178,10 @@ private[io] class UdpConnection( } } - private def reportConnectFailure(thunk: => Unit): Unit = { - try { + private def reportConnectFailure(thunk: => Unit): Unit = + try thunk - } catch { + catch { case NonFatal(e) => log.debug( "Failure while connecting UDP channel to remote address [{}] local address [{}]: {}", @@ -191,5 +191,4 @@ private[io] class UdpConnection( commander ! CommandFailed(connect) context.stop(self) } - } } diff --git a/actor/src/main/scala/org/apache/pekko/io/UdpListener.scala b/actor/src/main/scala/org/apache/pekko/io/UdpListener.scala index d91c2c2aa9d..13deb24f33f 100644 --- a/actor/src/main/scala/org/apache/pekko/io/UdpListener.scala +++ b/actor/src/main/scala/org/apache/pekko/io/UdpListener.scala @@ -123,7 +123,7 @@ private[io] class UdpListener(val udp: UdpExt, channelRegistry: ChannelRegistry, } } - override def postStop(): Unit = { + override def postStop(): Unit = if (channel.isOpen) { log.debug("Closing DatagramChannel after being stopped") try channel.close() @@ -131,5 +131,4 @@ private[io] class UdpListener(val udp: UdpExt, channelRegistry: ChannelRegistry, case NonFatal(e) => log.debug("Error closing DatagramChannel: {}", e) } } - } } diff --git a/actor/src/main/scala/org/apache/pekko/io/UdpSender.scala b/actor/src/main/scala/org/apache/pekko/io/UdpSender.scala index 6049a120a5d..d75334e2691 100644 --- a/actor/src/main/scala/org/apache/pekko/io/UdpSender.scala +++ b/actor/src/main/scala/org/apache/pekko/io/UdpSender.scala @@ -46,7 +46,7 @@ private[io] class UdpSender( .create() datagramChannel.configureBlocking(false) val socket = datagramChannel.socket - options.foreach { _.beforeDatagramBind(socket) } + options.foreach(_.beforeDatagramBind(socket)) datagramChannel } diff --git a/actor/src/main/scala/org/apache/pekko/io/WithUdpSend.scala b/actor/src/main/scala/org/apache/pekko/io/WithUdpSend.scala index cf262fdc294..f6b5f6151ea 100644 --- a/actor/src/main/scala/org/apache/pekko/io/WithUdpSend.scala +++ b/actor/src/main/scala/org/apache/pekko/io/WithUdpSend.scala @@ -109,8 +109,7 @@ private[io] trait WithUdpSend { pendingSend = null pendingCommander = null } - } finally { + } finally udp.bufferPool.release(buffer) - } } } diff --git a/actor/src/main/scala/org/apache/pekko/io/dns/DnsResourceRecords.scala b/actor/src/main/scala/org/apache/pekko/io/dns/DnsResourceRecords.scala index 362da803e91..d97b0a61da4 100644 --- a/actor/src/main/scala/org/apache/pekko/io/dns/DnsResourceRecords.scala +++ b/actor/src/main/scala/org/apache/pekko/io/dns/DnsResourceRecords.scala @@ -83,9 +83,8 @@ private[dns] object CNameRecord { * INTERNAL API */ @InternalApi - def parseBody(name: String, ttl: Ttl, @unused length: Short, it: ByteIterator, msg: ByteString): CNameRecord = { + def parseBody(name: String, ttl: Ttl, @unused length: Short, it: ByteIterator, msg: ByteString): CNameRecord = CNameRecord(name, ttl, DomainName.parse(it, msg)) - } } final case class SRVRecord( diff --git a/actor/src/main/scala/org/apache/pekko/io/dns/DnsSettings.scala b/actor/src/main/scala/org/apache/pekko/io/dns/DnsSettings.scala index 7a542a51407..8956f5a9ca5 100644 --- a/actor/src/main/scala/org/apache/pekko/io/dns/DnsSettings.scala +++ b/actor/src/main/scala/org/apache/pekko/io/dns/DnsSettings.scala @@ -59,7 +59,7 @@ private[dns] final class DnsSettings(system: ExtendedActorSystem, c: Config) { import DnsSettings._ - val NameServers: List[InetSocketAddress] = { + val NameServers: List[InetSocketAddress] = c.getValue("nameservers").valueType() match { case ConfigValueType.STRING => c.getString("nameservers") match { @@ -77,14 +77,13 @@ private[dns] final class DnsSettings(system: ExtendedActorSystem, c: Config) { userAddresses.toList case _ => throw new IllegalArgumentException("Invalid type for nameservers. Must be a string or string list") } - } val ResolveTimeout: FiniteDuration = c.getDuration("resolve-timeout").asScala val PositiveCachePolicy: CachePolicy = getTtl("positive-ttl") val NegativeCachePolicy: CachePolicy = getTtl("negative-ttl") - lazy val IdGeneratorPolicy: IdGenerator.Policy = { + lazy val IdGeneratorPolicy: IdGenerator.Policy = c.getString("id-generator-policy") match { case "thread-local-random" => Policy.ThreadLocalRandom case "secure-random" => Policy.SecureRandom @@ -94,7 +93,6 @@ private[dns] final class DnsSettings(system: ExtendedActorSystem, c: Config) { "Invalid value for id-generator-policy, id-generator-policy must be 'thread-local-random', 'secure-random' or" + s"`enhanced-double-hash-random`") } - } private def getTtl(path: String): CachePolicy = c.getString(path) match { @@ -126,7 +124,7 @@ private[dns] final class DnsSettings(system: ExtendedActorSystem, c: Config) { } else None } - val SearchDomains: List[String] = { + val SearchDomains: List[String] = c.getValue("search-domains").valueType() match { case ConfigValueType.STRING => c.getString("search-domains") match { @@ -137,9 +135,8 @@ private[dns] final class DnsSettings(system: ExtendedActorSystem, c: Config) { c.getStringList("search-domains").asScala.toList case _ => throw new IllegalArgumentException("Invalid type for search-domains. Must be a string or string list.") } - } - val NDots: Int = { + val NDots: Int = c.getValue("ndots").valueType() match { case ConfigValueType.STRING => c.getString("ndots") match { @@ -156,7 +153,6 @@ private[dns] final class DnsSettings(system: ExtendedActorSystem, c: Config) { case _ => throw new IllegalArgumentException("Invalid value for ndots. Must be the string 'default' or an integer.") } - } // ------------------------- @@ -193,7 +189,7 @@ object DnsSettings { * Based on: https://github.com/netty/netty/blob/4.1/resolver-dns/src/main/java/io/netty/resolver/dns/DefaultDnsServerAddressStreamProvider.java#L58-L146 */ private[pekko] def getDefaultNameServers(system: ExtendedActorSystem): Try[List[InetSocketAddress]] = { - def asInetSocketAddress(server: String): Try[InetSocketAddress] = { + def asInetSocketAddress(server: String): Try[InetSocketAddress] = Try { val uri = new URI(server) val host = uri.getHost @@ -203,7 +199,6 @@ object DnsSettings { } new InetSocketAddress(host, port) } - } def getNameserversUsingJNDI: Try[List[InetSocketAddress]] = { import java.util @@ -233,7 +228,7 @@ object DnsSettings { // this method is used as a fallback in case JNDI results in an empty list // this method will not work when running modularised of course since it needs access to internal sun classes - def getNameserversUsingReflection: Try[List[InetSocketAddress]] = { + def getNameserversUsingReflection: Try[List[InetSocketAddress]] = system.dynamicAccess.getClassFor[Any]("sun.net.dns.ResolverConfiguration").flatMap { c => Try { val open = c.getMethod("open") @@ -247,7 +242,6 @@ object DnsSettings { res.flatMap(s => asInetSocketAddress(s).toOption) } } - } getNameserversUsingJNDI.orElse(getNameserversUsingReflection) } diff --git a/actor/src/main/scala/org/apache/pekko/io/dns/RecordType.scala b/actor/src/main/scala/org/apache/pekko/io/dns/RecordType.scala index 862e6f738d5..49a4835b7e0 100644 --- a/actor/src/main/scala/org/apache/pekko/io/dns/RecordType.scala +++ b/actor/src/main/scala/org/apache/pekko/io/dns/RecordType.scala @@ -29,10 +29,9 @@ object RecordType { private final val lookupTable = Array.ofDim[RecordType](256) private[pekko] def lookup(code: Int): RecordType = lookupTable(code) - def apply(id: Short): OptionVal[RecordType] = { + def apply(id: Short): OptionVal[RecordType] = if (id < 1 || id > 255) OptionVal.None else OptionVal(RecordType.lookup(id)) - } private def register(t: RecordType): RecordType = { lookupTable(t.code) = t diff --git a/actor/src/main/scala/org/apache/pekko/io/dns/internal/AsyncDnsManager.scala b/actor/src/main/scala/org/apache/pekko/io/dns/internal/AsyncDnsManager.scala index 21c9b41bfed..ad45292fa17 100644 --- a/actor/src/main/scala/org/apache/pekko/io/dns/internal/AsyncDnsManager.scala +++ b/actor/src/main/scala/org/apache/pekko/io/dns/internal/AsyncDnsManager.scala @@ -82,9 +82,9 @@ private[io] final class AsyncDnsManager( private val resolver = { val props: Props = FromConfig.props( Props(provider.actorClass, settings, cache, - (factory: ActorRefFactory, dns: List[InetSocketAddress]) => { + (factory: ActorRefFactory, dns: List[InetSocketAddress]) => dns.map(ns => factory.actorOf(Props(new DnsClient(ns)))) - }).withDeploy(Deploy.local).withDispatcher(dispatcher)) + ).withDeploy(Deploy.local).withDispatcher(dispatcher)) context.actorOf(props, name) } @@ -93,13 +93,12 @@ private[io] final class AsyncDnsManager( case _ => None } - override def preStart(): Unit = { + override def preStart(): Unit = cacheCleanup.foreach { _ => val interval = Duration(resolverConfig.getDuration("cache-cleanup-interval", TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS) timers.startTimerWithFixedDelay(CacheCleanup, CacheCleanup, interval) } - } // still support deprecated DNS API @nowarn("msg=deprecated") diff --git a/actor/src/main/scala/org/apache/pekko/io/dns/internal/AsyncDnsResolver.scala b/actor/src/main/scala/org/apache/pekko/io/dns/internal/AsyncDnsResolver.scala index 853980be88c..27ad20b6126 100644 --- a/actor/src/main/scala/org/apache/pekko/io/dns/internal/AsyncDnsResolver.scala +++ b/actor/src/main/scala/org/apache/pekko/io/dns/internal/AsyncDnsResolver.scala @@ -152,7 +152,7 @@ private[io] final class AsyncDnsResolver( } } - private def sendQuestion(resolver: ActorRef, message: DnsQuestion): Future[Answer] = { + private def sendQuestion(resolver: ActorRef, message: DnsQuestion): Future[Answer] = (resolver ? message).transformWith { case Success(result: Answer) => Future.successful(result) @@ -166,12 +166,11 @@ private[io] final class AsyncDnsResolver( Future.failed( new IllegalArgumentException("Unexpected response " + a.toString + " of type " + a.getClass.toString)) } - } private def resolveWithSearch( name: String, requestType: RequestType, - resolver: ActorRef): Future[DnsProtocol.Resolved] = { + resolver: ActorRef): Future[DnsProtocol.Resolved] = if (settings.SearchDomains.nonEmpty) { val nameWithSearch = settings.SearchDomains.map(sd => name + "." + sd) // ndots is a heuristic used to try and work out whether the name passed in is a fully qualified domain name, @@ -191,12 +190,11 @@ private[io] final class AsyncDnsResolver( } else { resolve(name, requestType, resolver) } - } private def resolveFirst( searchNames: List[String], requestType: RequestType, - resolver: ActorRef): Future[DnsProtocol.Resolved] = { + resolver: ActorRef): Future[DnsProtocol.Resolved] = searchNames match { case searchName :: Nil => resolve(searchName, requestType, resolver) @@ -209,7 +207,6 @@ private[io] final class AsyncDnsResolver( // This can't happen Future.failed(new IllegalStateException("Failed to 'resolveFirst': 'searchNames' must not be empty")) } - } private def resolve(name: String, requestType: RequestType, resolver: ActorRef): Future[DnsProtocol.Resolved] = { log.debug("Attempting to resolve {} with {}", name, resolver) @@ -234,9 +231,9 @@ private[io] final class AsyncDnsResolver( } yield DnsProtocol.Resolved(name, ipv4.rrs ++ ipv6.rrs, ipv4.additionalRecs ++ ipv6.additionalRecs) case Srv => - sendQuestion(resolver, SrvQuestion(idGenerator.nextId(), caseFoldedName)).map(answer => { + sendQuestion(resolver, SrvQuestion(idGenerator.nextId(), caseFoldedName)).map { answer => DnsProtocol.Resolved(name, answer.rrs, answer.additionalRecs) - }) + } } } diff --git a/actor/src/main/scala/org/apache/pekko/io/dns/internal/DnsClient.scala b/actor/src/main/scala/org/apache/pekko/io/dns/internal/DnsClient.scala index 07566dff922..937ebbad35d 100644 --- a/actor/src/main/scala/org/apache/pekko/io/dns/internal/DnsClient.scala +++ b/actor/src/main/scala/org/apache/pekko/io/dns/internal/DnsClient.scala @@ -33,13 +33,12 @@ import pekko.pattern.{ BackoffOpts, BackoffSupervisor } sealed trait DnsQuestion { def id: Short def name: String - def withId(newId: Short): DnsQuestion = { + def withId(newId: Short): DnsQuestion = this match { case SrvQuestion(_, name) => SrvQuestion(newId, name) case Question4(_, name) => Question4(newId, name) case Question6(_, name) => Question6(newId, name) } - } } final case class SrvQuestion(id: Short, name: String) extends DnsQuestion final case class Question4(id: Short, name: String) extends DnsQuestion @@ -66,9 +65,8 @@ import pekko.pattern.{ BackoffOpts, BackoffSupervisor } lazy val tcpDnsClient: ActorRef = createTcpClient() - override def preStart() = { + override def preStart() = udp ! Udp.Bind(self, new InetSocketAddress(InetAddress.getByAddress(Array.ofDim(4)), 0)) - } def receive: Receive = { case Udp.Bound(local) => @@ -83,9 +81,8 @@ import pekko.pattern.{ BackoffOpts, BackoffSupervisor } stash() } - private def message(name: String, id: Short, recordType: RecordType): Message = { + private def message(name: String, id: Short, recordType: RecordType): Message = Message(id, MessageFlags(), im.Seq(Question(name, recordType, RecordClass.IN))) - } /** * Silent to allow map update syntax @@ -194,7 +191,7 @@ import pekko.pattern.{ BackoffOpts, BackoffSupervisor } case Udp.Unbound => context.stop(self) } - private def newInflightRequests(msg: Message, theSender: ActorRef)(func: => Unit): Unit = { + private def newInflightRequests(msg: Message, theSender: ActorRef)(func: => Unit): Unit = if (!inflightRequests.contains(msg.id)) { inflightRequests += (msg.id -> (theSender -> msg)) func @@ -202,22 +199,20 @@ import pekko.pattern.{ BackoffOpts, BackoffSupervisor } log.warning("Received duplicate message [{}] with id [{}]", msg, msg.id) theSender ! DuplicateId(msg.id) } - } private def isSameQuestion(q1s: Seq[Question], q2s: Seq[Question]): Boolean = { @tailrec - def impl(q1s: List[Question], q2s: List[Question]): Boolean = { + def impl(q1s: List[Question], q2s: List[Question]): Boolean = (q1s, q2s) match { case (Nil, Nil) => true case (h1 :: t1, h2 :: t2) => h1.isSame(h2) && impl(t1, t2) case _ => false } - } impl(q1s.sortBy(_.name).toList, q2s.sortBy(_.name).toList) } - def createTcpClient() = { + def createTcpClient() = context.actorOf( BackoffSupervisor.props( BackoffOpts.onFailure( @@ -227,5 +222,4 @@ import pekko.pattern.{ BackoffOpts, BackoffSupervisor } maxBackoff = 20.seconds, randomFactor = 0.1)), "tcpDnsClientSupervisor") - } } diff --git a/actor/src/main/scala/org/apache/pekko/io/dns/internal/DnsMessage.scala b/actor/src/main/scala/org/apache/pekko/io/dns/internal/DnsMessage.scala index 1e176f898ad..2698bee3dcc 100644 --- a/actor/src/main/scala/org/apache/pekko/io/dns/internal/DnsMessage.scala +++ b/actor/src/main/scala/org/apache/pekko/io/dns/internal/DnsMessage.scala @@ -66,9 +66,8 @@ private[internal] case class MessageFlags(flags: Short) extends AnyVal { def isRecursionAvailable: Boolean = (flags & (1 << 7)) != 0 - def responseCode: ResponseCode.Value = { + def responseCode: ResponseCode.Value = ResponseCode(flags & 0x0F) - } override def toString: String = { var ret = List[String]() @@ -95,7 +94,7 @@ private[internal] object MessageFlags { truncated: Boolean = false, recursionDesired: Boolean = true, recursionAvailable: Boolean = false, - responseCode: ResponseCode.Value = ResponseCode.SUCCESS): MessageFlags = { + responseCode: ResponseCode.Value = ResponseCode.SUCCESS): MessageFlags = new MessageFlags( ((if (answer) 0x8000 else 0) | (opCode.id << 11) | @@ -104,7 +103,6 @@ private[internal] object MessageFlags { (if (recursionDesired) 1 << 8 else 0) | (if (recursionAvailable) 1 << 7 else 0) | responseCode.id).toShort) - } } /** diff --git a/actor/src/main/scala/org/apache/pekko/io/dns/internal/DomainName.scala b/actor/src/main/scala/org/apache/pekko/io/dns/internal/DomainName.scala index e0e92d7c0ef..687e8966619 100644 --- a/actor/src/main/scala/org/apache/pekko/io/dns/internal/DomainName.scala +++ b/actor/src/main/scala/org/apache/pekko/io/dns/internal/DomainName.scala @@ -22,16 +22,14 @@ import pekko.util.{ ByteIterator, ByteString, ByteStringBuilder } */ @InternalApi private[pekko] object DomainName { - def length(name: String): Short = { + def length(name: String): Short = (name.length + 2).toShort - } def write(it: ByteStringBuilder, name: String): Unit = { for (label <- name.split('.')) { it.putByte(label.length.toByte) - for (c <- label) { + for (c <- label) it.putByte(c.toByte) - } } it.putByte(0) } diff --git a/actor/src/main/scala/org/apache/pekko/io/dns/internal/RecordClassSerializer.scala b/actor/src/main/scala/org/apache/pekko/io/dns/internal/RecordClassSerializer.scala index 54c07f4e827..3c164bf71c6 100644 --- a/actor/src/main/scala/org/apache/pekko/io/dns/internal/RecordClassSerializer.scala +++ b/actor/src/main/scala/org/apache/pekko/io/dns/internal/RecordClassSerializer.scala @@ -24,7 +24,7 @@ import pekko.util.{ ByteIterator, ByteStringBuilder } @InternalApi private[pekko] object RecordClassSerializer { - def parse(it: ByteIterator): RecordClass = { + def parse(it: ByteIterator): RecordClass = it.getShort match { case 1 => RecordClass.IN case 2 => RecordClass.CS @@ -32,9 +32,7 @@ private[pekko] object RecordClassSerializer { case 255 => RecordClass.WILDCARD case unknown => throw new RuntimeException(s"Unexpected record class $unknown") } - } - def write(out: ByteStringBuilder, c: RecordClass): Unit = { + def write(out: ByteStringBuilder, c: RecordClass): Unit = out.putShort(c.code) - } } diff --git a/actor/src/main/scala/org/apache/pekko/io/dns/internal/RecordTypeSerializer.scala b/actor/src/main/scala/org/apache/pekko/io/dns/internal/RecordTypeSerializer.scala index 5ece7fa85b8..ac25030426f 100644 --- a/actor/src/main/scala/org/apache/pekko/io/dns/internal/RecordTypeSerializer.scala +++ b/actor/src/main/scala/org/apache/pekko/io/dns/internal/RecordTypeSerializer.scala @@ -23,9 +23,8 @@ import pekko.util.{ ByteIterator, ByteStringBuilder, OptionVal } private[pekko] object RecordTypeSerializer { // TODO other type than ByteStringBuilder? (was used in pekko-dns) - def write(out: ByteStringBuilder, value: RecordType): Unit = { + def write(out: ByteStringBuilder, value: RecordType): Unit = out.putShort(value.code) - } def parse(it: ByteIterator): RecordType = { val id = it.getShort diff --git a/actor/src/main/scala/org/apache/pekko/io/dns/internal/ResolvConfParser.scala b/actor/src/main/scala/org/apache/pekko/io/dns/internal/ResolvConfParser.scala index 7595a09e9ff..13a9cf0c945 100644 --- a/actor/src/main/scala/org/apache/pekko/io/dns/internal/ResolvConfParser.scala +++ b/actor/src/main/scala/org/apache/pekko/io/dns/internal/ResolvConfParser.scala @@ -33,11 +33,10 @@ private[dns] object ResolvConfParser { /** * Does a partial parse according to https://linux.die.net/man/5/resolver. */ - def parseFile(file: File): Try[ResolvConf] = { + def parseFile(file: File): Try[ResolvConf] = Try { parseLines(Files.lines(file.toPath).iterator().asScala) } - } def parseLines(lines: Iterator[String]): ResolvConf = { // A few notes - according to the spec, search and domain are mutually exclusive, the domain is used as the diff --git a/actor/src/main/scala/org/apache/pekko/pattern/AskSupport.scala b/actor/src/main/scala/org/apache/pekko/pattern/AskSupport.scala index 18f1ccc7008..5007f7cc361 100644 --- a/actor/src/main/scala/org/apache/pekko/pattern/AskSupport.scala +++ b/actor/src/main/scala/org/apache/pekko/pattern/AskSupport.scala @@ -300,11 +300,10 @@ object AskableActorRef { @InternalApi private[pekko] def negativeTimeoutException( recipient: Any, message: Any, - sender: ActorRef): IllegalArgumentException = { + sender: ActorRef): IllegalArgumentException = new IllegalArgumentException( s"Timeout length must be positive, question not sent to [$recipient]. " + messagePartOfException(message, sender)) - } /** * INTERNAL API @@ -312,11 +311,10 @@ object AskableActorRef { @InternalApi private[pekko] def recipientTerminatedException( recipient: Any, message: Any, - sender: ActorRef): AskTimeoutException = { + sender: ActorRef): AskTimeoutException = new AskTimeoutException( s"Recipient [$recipient] had already been terminated. " + messagePartOfException(message, sender)) - } /** * INTERNAL API @@ -324,11 +322,10 @@ object AskableActorRef { @InternalApi private[pekko] def unsupportedRecipientType( recipient: Any, message: Any, - sender: ActorRef): IllegalArgumentException = { + sender: ActorRef): IllegalArgumentException = new IllegalArgumentException( s"Unsupported recipient type, question not sent to [$recipient]. " + messagePartOfException(message, sender)) - } } /* @@ -596,9 +593,8 @@ private[pekko] final class PromiseActorRef( p = provider.tempPath(refPathPrefix) provider.registerTempActor(this, p) p - } finally { + } finally setState(p) - } } else path case p: ActorPath => p case StoppedWithPath(p) => p diff --git a/actor/src/main/scala/org/apache/pekko/pattern/BackoffSupervisor.scala b/actor/src/main/scala/org/apache/pekko/pattern/BackoffSupervisor.scala index d8525ca9903..19199f2a639 100644 --- a/actor/src/main/scala/org/apache/pekko/pattern/BackoffSupervisor.scala +++ b/actor/src/main/scala/org/apache/pekko/pattern/BackoffSupervisor.scala @@ -50,7 +50,7 @@ object BackoffSupervisor { childName: String, minBackoff: FiniteDuration, maxBackoff: FiniteDuration, - randomFactor: Double): Props = { + randomFactor: Double): Props = propsWithSupervisorStrategy( childProps, childName, @@ -58,7 +58,6 @@ object BackoffSupervisor { maxBackoff, randomFactor, SupervisorStrategy.defaultStrategy) - } /** * Props for creating a `BackoffSupervisor` actor. @@ -118,9 +117,8 @@ object BackoffSupervisor { childName: String, minBackoff: java.time.Duration, maxBackoff: java.time.Duration, - randomFactor: Double): Props = { + randomFactor: Double): Props = props(childProps, childName, minBackoff.asScala, maxBackoff.asScala, randomFactor) - } /** * Props for creating a `BackoffSupervisor` actor. @@ -149,9 +147,8 @@ object BackoffSupervisor { minBackoff: java.time.Duration, maxBackoff: java.time.Duration, randomFactor: Double, - maxNrOfRetries: Int): Props = { + maxNrOfRetries: Int): Props = props(childProps, childName, minBackoff.asScala, maxBackoff.asScala, randomFactor, maxNrOfRetries) - } /** * Props for creating a `BackoffSupervisor` actor with a custom @@ -226,9 +223,8 @@ object BackoffSupervisor { minBackoff: java.time.Duration, maxBackoff: java.time.Duration, randomFactor: Double, - strategy: SupervisorStrategy): Props = { + strategy: SupervisorStrategy): Props = propsWithSupervisorStrategy(childProps, childName, minBackoff.asScala, maxBackoff.asScala, randomFactor, strategy) - } /** * Props for creating a `BackoffSupervisor` actor from [[BackoffOptions]]. diff --git a/actor/src/main/scala/org/apache/pekko/pattern/CircuitBreaker.scala b/actor/src/main/scala/org/apache/pekko/pattern/CircuitBreaker.scala index 38bf58f2739..10dbf910b1b 100644 --- a/actor/src/main/scala/org/apache/pekko/pattern/CircuitBreaker.scala +++ b/actor/src/main/scala/org/apache/pekko/pattern/CircuitBreaker.scala @@ -170,7 +170,7 @@ class CircuitBreaker( resetTimeout: FiniteDuration, maxResetTimeout: FiniteDuration, exponentialBackoffFactor: Double, - randomFactor: Double)(implicit executor: ExecutionContext) = { + randomFactor: Double)(implicit executor: ExecutionContext) = this( scheduler, maxFailures, @@ -181,7 +181,6 @@ class CircuitBreaker( randomFactor, Set.empty, CircuitBreakerNoopTelemetry)(executor) - } @deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "Akka 2.5.12") def this( @@ -189,7 +188,7 @@ class CircuitBreaker( scheduler: Scheduler, maxFailures: Int, callTimeout: FiniteDuration, - resetTimeout: FiniteDuration) = { + resetTimeout: FiniteDuration) = this( scheduler, maxFailures, @@ -198,14 +197,13 @@ class CircuitBreaker( maxResetTimeout = 36500.days, exponentialBackoffFactor = 1.0, randomFactor = 0.0)(executor) - } def this( executor: ExecutionContext, scheduler: Scheduler, maxFailures: Int, callTimeout: java.time.Duration, - resetTimeout: java.time.Duration) = { + resetTimeout: java.time.Duration) = this( scheduler, maxFailures, @@ -214,12 +212,11 @@ class CircuitBreaker( maxResetTimeout = 36500.days, exponentialBackoffFactor = 1.0, randomFactor = 0.0)(executor) - } // add the old constructor to make it binary compatible def this(scheduler: Scheduler, maxFailures: Int, callTimeout: FiniteDuration, resetTimeout: FiniteDuration)( implicit - executor: ExecutionContext) = { + executor: ExecutionContext) = this( scheduler, maxFailures, @@ -228,7 +225,6 @@ class CircuitBreaker( maxResetTimeout = 36500.days, exponentialBackoffFactor = 1.0, randomFactor = 0.0)(executor) - } // add the old constructor to make it binary compatible def this( @@ -239,9 +235,8 @@ class CircuitBreaker( maxResetTimeout: FiniteDuration, exponentialBackoffFactor: Double)( implicit - executor: ExecutionContext) = { + executor: ExecutionContext) = this(scheduler, maxFailures, callTimeout, resetTimeout, maxResetTimeout, exponentialBackoffFactor, 0.0)(executor) - } /** * The `resetTimeout` will be increased exponentially for each failed attempt to close the circuit. @@ -249,7 +244,7 @@ class CircuitBreaker( * * @param maxResetTimeout the upper bound of resetTimeout */ - def withExponentialBackoff(maxResetTimeout: FiniteDuration): CircuitBreaker = { + def withExponentialBackoff(maxResetTimeout: FiniteDuration): CircuitBreaker = new CircuitBreaker( scheduler, maxFailures, @@ -260,7 +255,6 @@ class CircuitBreaker( randomFactor, allowExceptions, telemetry)(executor) - } /** * The `resetTimeout` will be increased exponentially for each failed attempt to close the circuit. @@ -268,9 +262,8 @@ class CircuitBreaker( * * @param maxResetTimeout the upper bound of resetTimeout */ - def withExponentialBackoff(maxResetTimeout: java.time.Duration): CircuitBreaker = { + def withExponentialBackoff(maxResetTimeout: java.time.Duration): CircuitBreaker = withExponentialBackoff(maxResetTimeout.asScala) - } /** * Adds jitter to the delay. @@ -278,7 +271,7 @@ class CircuitBreaker( * factor is added, e.g. 0.2 adds up to 20% delay. In order to skip this * additional delay pass in 0. */ - def withRandomFactor(randomFactor: Double): CircuitBreaker = { + def withRandomFactor(randomFactor: Double): CircuitBreaker = new CircuitBreaker( scheduler, maxFailures, @@ -289,7 +282,6 @@ class CircuitBreaker( randomFactor, allowExceptions, telemetry)(executor) - } /** * Holds reference to current state of CircuitBreaker - *access only via helper methods* @@ -482,18 +474,16 @@ class CircuitBreaker( * caller Actor. In such a case, it is convenient to mark a successful call instead of using Future * via [[withCircuitBreaker]] */ - def succeed(): Unit = { + def succeed(): Unit = currentState.callSucceeds() - } /** * Mark a failed call through CircuitBreaker. Sometimes the callee of CircuitBreaker sends back a message to the * caller Actor. In such a case, it is convenient to mark a failed call instead of using Future * via [[withCircuitBreaker]] */ - def fail(): Unit = { + def fail(): Unit = currentState.callFails() - } /** * Return true if the internal state is Closed. WARNING: It is a "power API" call which you should use with care. @@ -501,9 +491,8 @@ class CircuitBreaker( * So, if you check the state by yourself, and make a remote call outside CircuitBreaker, you should * manage the state yourself. */ - def isClosed: Boolean = { + def isClosed: Boolean = currentState == Closed - } /** * Return true if the internal state is Open. WARNING: It is a "power API" call which you should use with care. @@ -511,9 +500,8 @@ class CircuitBreaker( * So, if you check the state by yourself, and make a remote call outside CircuitBreaker, you should * manage the state yourself. */ - def isOpen: Boolean = { + def isOpen: Boolean = currentState == Open - } /** * Return true if the internal state is HalfOpen. WARNING: It is a "power API" call which you should use with care. @@ -521,9 +509,8 @@ class CircuitBreaker( * So, if you check the state by yourself, and make a remote call outside CircuitBreaker, you should * manage the state yourself. */ - def isHalfOpen: Boolean = { + def isHalfOpen: Boolean = currentState == HalfOpen - } /** * Adds a callback to execute when circuit breaker opens @@ -694,11 +681,10 @@ class CircuitBreaker( * @param fromState State being transitioning from * @param toState State being transitioning from */ - private def transition(fromState: State, toState: State): Unit = { + private def transition(fromState: State, toState: State): Unit = if (swapState(fromState, toState)) toState.enter() - // else some other thread already swapped state - } + // else some other thread already swapped state /** * Trips breaker to an open state. This is valid from Closed or Half-Open states. @@ -833,7 +819,7 @@ class CircuitBreaker( * * @return Promise which executes listener in supplied [[scala.concurrent.ExecutionContext]] */ - protected def notifyTransitionListeners(): Unit = { + protected def notifyTransitionListeners(): Unit = if (hasListeners) { val iterator = listeners.iterator while (iterator.hasNext) { @@ -841,7 +827,6 @@ class CircuitBreaker( executor.execute(listener) } } - } /** * Shared implementation of call across all states. Thrown exception or execution of the call beyond the allowed diff --git a/actor/src/main/scala/org/apache/pekko/pattern/FutureTimeoutSupport.scala b/actor/src/main/scala/org/apache/pekko/pattern/FutureTimeoutSupport.scala index 2be1ad59b69..6288b2d75f5 100644 --- a/actor/src/main/scala/org/apache/pekko/pattern/FutureTimeoutSupport.scala +++ b/actor/src/main/scala/org/apache/pekko/pattern/FutureTimeoutSupport.scala @@ -31,9 +31,8 @@ trait FutureTimeoutSupport { * after the specified duration. */ def after[T](duration: FiniteDuration)(value: => Future[T])( - implicit system: ClassicActorSystemProvider): Future[T] = { + implicit system: ClassicActorSystemProvider): Future[T] = after(duration, using = system.classicSystem.scheduler)(value)(system.classicSystem.dispatcher) - } /** * Returns a [[java.util.concurrent.CompletionStage]] that will be completed with the success or failure of the provided value @@ -77,10 +76,10 @@ trait FutureTimeoutSupport { using.scheduleOnce(duration) { try { val future = value - future.handle[Unit]((t: T, ex: Throwable) => { + future.handle[Unit] { (t: T, ex: Throwable) => if (t != null) p.complete(t) if (ex != null) p.completeExceptionally(ex) - }) + } } catch { case NonFatal(ex) => p.completeExceptionally(ex) } diff --git a/actor/src/main/scala/org/apache/pekko/pattern/GracefulStopSupport.scala b/actor/src/main/scala/org/apache/pekko/pattern/GracefulStopSupport.scala index aa1e83931f1..ea55efcd967 100644 --- a/actor/src/main/scala/org/apache/pekko/pattern/GracefulStopSupport.scala +++ b/actor/src/main/scala/org/apache/pekko/pattern/GracefulStopSupport.scala @@ -64,7 +64,7 @@ trait GracefulStopSupport { target.tell(stopMessage, Actor.noSender) ref.result.future.transform({ case Terminated(t) if t.path == target.path => true - case _ => { internalTarget.sendSystemMessage(Unwatch(target, ref)); false } + case _ => internalTarget.sendSystemMessage(Unwatch(target, ref)); false }, t => { internalTarget.sendSystemMessage(Unwatch(target, ref)); t })(ExecutionContexts.parasitic) } } diff --git a/actor/src/main/scala/org/apache/pekko/pattern/PipeToSupport.scala b/actor/src/main/scala/org/apache/pekko/pattern/PipeToSupport.scala index 8a8dc5f1cb3..ec881a46992 100644 --- a/actor/src/main/scala/org/apache/pekko/pattern/PipeToSupport.scala +++ b/actor/src/main/scala/org/apache/pekko/pattern/PipeToSupport.scala @@ -28,18 +28,16 @@ import pekko.util.unused trait PipeToSupport { final class PipeableFuture[T](val future: Future[T])(implicit executionContext: ExecutionContext) { - def pipeTo(recipient: ActorRef)(implicit sender: ActorRef = Actor.noSender): Future[T] = { + def pipeTo(recipient: ActorRef)(implicit sender: ActorRef = Actor.noSender): Future[T] = future.andThen { case Success(r) => recipient ! r case Failure(f) => recipient ! Status.Failure(f) } - } - def pipeToSelection(recipient: ActorSelection)(implicit sender: ActorRef = Actor.noSender): Future[T] = { + def pipeToSelection(recipient: ActorSelection)(implicit sender: ActorRef = Actor.noSender): Future[T] = future.andThen { case Success(r) => recipient ! r case Failure(f) => recipient ! Status.Failure(f) } - } def to(recipient: ActorRef): PipeableFuture[T] = to(recipient, Actor.noSender) def to(recipient: ActorRef, sender: ActorRef): PipeableFuture[T] = { pipeTo(recipient)(sender) @@ -54,18 +52,16 @@ trait PipeToSupport { final class PipeableCompletionStage[T](val future: CompletionStage[T])( implicit @unused executionContext: ExecutionContext) { - def pipeTo(recipient: ActorRef)(implicit sender: ActorRef = Actor.noSender): CompletionStage[T] = { - future.whenComplete((t: T, ex: Throwable) => { + def pipeTo(recipient: ActorRef)(implicit sender: ActorRef = Actor.noSender): CompletionStage[T] = + future.whenComplete { (t: T, ex: Throwable) => if (t != null) recipient ! t if (ex != null) recipient ! Status.Failure(ex) - }) - } - def pipeToSelection(recipient: ActorSelection)(implicit sender: ActorRef = Actor.noSender): CompletionStage[T] = { - future.whenComplete((t: T, ex: Throwable) => { + } + def pipeToSelection(recipient: ActorSelection)(implicit sender: ActorRef = Actor.noSender): CompletionStage[T] = + future.whenComplete { (t: T, ex: Throwable) => if (t != null) recipient ! t if (ex != null) recipient ! Status.Failure(ex) - }) - } + } def to(recipient: ActorRef): PipeableCompletionStage[T] = to(recipient, Actor.noSender) def to(recipient: ActorRef, sender: ActorRef): PipeableCompletionStage[T] = { pipeTo(recipient)(sender) diff --git a/actor/src/main/scala/org/apache/pekko/pattern/PromiseRef.scala b/actor/src/main/scala/org/apache/pekko/pattern/PromiseRef.scala index db2b22238f4..3a1555bea83 100644 --- a/actor/src/main/scala/org/apache/pekko/pattern/PromiseRef.scala +++ b/actor/src/main/scala/org/apache/pekko/pattern/PromiseRef.scala @@ -68,9 +68,8 @@ object PromiseRef { /** * Wraps an ActorRef and a Promise into a PromiseRef. */ - private[pekko] def wrap[T](actorRef: ActorRef, promise: Promise[T]): PromiseRef[T] = { + private[pekko] def wrap[T](actorRef: ActorRef, promise: Promise[T]): PromiseRef[T] = new PromiseRefImpl(actorRef, promise) - } /** * Constructs a new PromiseRef which will be completed with the first message sent to it. @@ -102,9 +101,8 @@ object PromiseRef { * promiseRef.future.onComplete(println) // prints "message" * }}} */ - def apply(timeout: Timeout)(implicit system: ActorSystem): PromiseRef[Any] = { + def apply(timeout: Timeout)(implicit system: ActorSystem): PromiseRef[Any] = PromiseRef(system, timeout) - } } object FutureRef { @@ -112,9 +110,8 @@ object FutureRef { /** * Wraps an ActorRef and a Future into a FutureRef. */ - private[pekko] def wrap[T](actorRef: ActorRef, future: Future[T]): FutureRef[T] = { + private[pekko] def wrap[T](actorRef: ActorRef, future: Future[T]): FutureRef[T] = new FutureRefImpl(actorRef, future) - } /** * Constructs a new FutureRef which will be completed with the first message sent to it. @@ -128,9 +125,8 @@ object FutureRef { * futureRef.onComplete(println) // prints "message" * }}} */ - def apply(system: ActorSystem, timeout: Timeout): FutureRef[Any] = { + def apply(system: ActorSystem, timeout: Timeout): FutureRef[Any] = PromiseRef(system, timeout).toFutureRef - } /** * Constructs a new PromiseRef which will be completed with the first message sent to it. @@ -145,9 +141,8 @@ object FutureRef { * futureRef.onComplete(println) // prints "message" * }}} */ - def apply(timeout: Timeout)(implicit system: ActorSystem): FutureRef[Any] = { + def apply(timeout: Timeout)(implicit system: ActorSystem): FutureRef[Any] = FutureRef(system, timeout) - } } private[pekko] class PromiseRefImpl[T](val ref: ActorRef, val promise: Promise[T]) @@ -162,7 +157,7 @@ private[pekko] final class AskPromiseRef private (promiseActorRef: PromiseActorR extends PromiseRefImpl[Any](promiseActorRef, promiseActorRef.result) private[pekko] object AskPromiseRef { - def apply(provider: ActorRefProvider, timeout: Timeout): AskPromiseRef = { + def apply(provider: ActorRefProvider, timeout: Timeout): AskPromiseRef = if (timeout.duration.length > 0) { val promiseActorRef = PromiseActorRef(provider, timeout, "unknown", "unknown", "deadLetters", provider.deadLetters) @@ -170,5 +165,4 @@ private[pekko] object AskPromiseRef { } else { throw new IllegalArgumentException(s"Timeout length must not be negative, was: $timeout") } - } } diff --git a/actor/src/main/scala/org/apache/pekko/pattern/RetrySupport.scala b/actor/src/main/scala/org/apache/pekko/pattern/RetrySupport.scala index 2fccd0912e8..5543cf2e5c9 100644 --- a/actor/src/main/scala/org/apache/pekko/pattern/RetrySupport.scala +++ b/actor/src/main/scala/org/apache/pekko/pattern/RetrySupport.scala @@ -43,9 +43,8 @@ trait RetrySupport { * val withRetry: Future[Something] = retry(attempt = possiblyFailing, attempts = 10) * }}} */ - def retry[T](attempt: () => Future[T], attempts: Int)(implicit ec: ExecutionContext): Future[T] = { + def retry[T](attempt: () => Future[T], attempts: Int)(implicit ec: ExecutionContext): Future[T] = RetrySupport.retry(attempt, attempts, attempted = 0) - } /** * Given a function from Unit to Future, returns an internally retrying Future. @@ -77,9 +76,8 @@ trait RetrySupport { */ def retry[T](attempt: () => Future[T], shouldRetry: (T, Throwable) => Boolean, - attempts: Int)(implicit ec: ExecutionContext): Future[T] = { + attempts: Int)(implicit ec: ExecutionContext): Future[T] = RetrySupport.retry(attempt, shouldRetry, attempts, ConstantFun.scalaAnyToNone, attempted = 0)(ec, null) - } /** * Given a function from Unit to Future, returns an internally retrying Future. @@ -115,7 +113,7 @@ trait RetrySupport { attempts: Int, minBackoff: FiniteDuration, maxBackoff: FiniteDuration, - randomFactor: Double)(implicit ec: ExecutionContext, scheduler: Scheduler): Future[T] = { + randomFactor: Double)(implicit ec: ExecutionContext, scheduler: Scheduler): Future[T] = retry( attempt, RetrySupport.retryOnException, @@ -123,7 +121,6 @@ trait RetrySupport { minBackoff, maxBackoff, randomFactor) - } /** * Given a function from Unit to Future, returns an internally retrying Future. @@ -208,9 +205,8 @@ trait RetrySupport { */ def retry[T](attempt: () => Future[T], attempts: Int, delay: FiniteDuration)( implicit ec: ExecutionContext, - scheduler: Scheduler): Future[T] = { + scheduler: Scheduler): Future[T] = retry(attempt, attempts, _ => Some(delay)) - } /** * Given a function from Unit to Future, returns an internally retrying Future. @@ -252,9 +248,8 @@ trait RetrySupport { attempts: Int, delay: FiniteDuration)( implicit ec: ExecutionContext, - scheduler: Scheduler): Future[T] = { + scheduler: Scheduler): Future[T] = retry(attempt, shouldRetry, attempts, _ => Some(delay)) - } /** * Given a function from Unit to Future, returns an internally retrying Future. @@ -285,9 +280,8 @@ trait RetrySupport { def retry[T](attempt: () => Future[T], attempts: Int, delayFunction: Int => Option[FiniteDuration])( implicit ec: ExecutionContext, - scheduler: Scheduler): Future[T] = { + scheduler: Scheduler): Future[T] = RetrySupport.retry(attempt, RetrySupport.retryOnException, attempts, delayFunction, attempted = 0) - } /** * Given a function from Unit to Future, returns an internally retrying Future. @@ -332,9 +326,8 @@ trait RetrySupport { def retry[T](attempt: () => Future[T], shouldRetry: (T, Throwable) => Boolean, attempts: Int, - delayFunction: Int => Option[FiniteDuration])(implicit ec: ExecutionContext, scheduler: Scheduler): Future[T] = { + delayFunction: Int => Option[FiniteDuration])(implicit ec: ExecutionContext, scheduler: Scheduler): Future[T] = RetrySupport.retry(attempt, shouldRetry, attempts, delayFunction, attempted = 0) - } } object RetrySupport extends RetrySupport { @@ -350,13 +343,12 @@ object RetrySupport extends RetrySupport { maxAttempts: Int, delayFunction: Int => Option[FiniteDuration], attempted: Int)(implicit ec: ExecutionContext, scheduler: Scheduler): Future[T] = { - def tryAttempt(): Future[T] = { - try { + def tryAttempt(): Future[T] = + try attempt() - } catch { + catch { case NonFatal(exc) => Future.failed(exc) // in case the `attempt` function throws } - } def doRetry(nextAttempt: Int): Future[T] = delayFunction(nextAttempt) match { case Some(delay) => diff --git a/actor/src/main/scala/org/apache/pekko/pattern/internal/CircuitBreakerTelemetry.scala b/actor/src/main/scala/org/apache/pekko/pattern/internal/CircuitBreakerTelemetry.scala index b208e5332d7..3df6c3521b8 100644 --- a/actor/src/main/scala/org/apache/pekko/pattern/internal/CircuitBreakerTelemetry.scala +++ b/actor/src/main/scala/org/apache/pekko/pattern/internal/CircuitBreakerTelemetry.scala @@ -107,13 +107,12 @@ trait CircuitBreakerTelemetry { } } - def create(breakerId: String, system: ExtendedActorSystem, fqcn: String): CircuitBreakerTelemetry = { + def create(breakerId: String, system: ExtendedActorSystem, fqcn: String): CircuitBreakerTelemetry = system.dynamicAccess .createInstanceFor[CircuitBreakerTelemetry]( fqcn, List(classOf[String] -> breakerId, classOf[ExtendedActorSystem] -> system)) .get - } } /** diff --git a/actor/src/main/scala/org/apache/pekko/routing/ConsistentHash.scala b/actor/src/main/scala/org/apache/pekko/routing/ConsistentHash.scala index 83540ea2368..c0d82a13e36 100644 --- a/actor/src/main/scala/org/apache/pekko/routing/ConsistentHash.scala +++ b/actor/src/main/scala/org/apache/pekko/routing/ConsistentHash.scala @@ -81,14 +81,13 @@ class ConsistentHash[T: ClassTag] private (nodes: immutable.SortedMap[Int, T], v // converts the result of Arrays.binarySearch into a index in the nodeRing array // see documentation of Arrays.binarySearch for what it returns - private def idx(i: Int): Int = { + private def idx(i: Int): Int = if (i >= 0) i // exact match else { val j = math.abs(i + 1) if (j >= nodeHashRing.length) 0 // after last, use first else j // next node clockwise } - } /** * Get the node responsible for the data key. @@ -120,7 +119,7 @@ class ConsistentHash[T: ClassTag] private (nodes: immutable.SortedMap[Int, T], v } object ConsistentHash { - def apply[T: ClassTag](nodes: Iterable[T], virtualNodesFactor: Int): ConsistentHash[T] = { + def apply[T: ClassTag](nodes: Iterable[T], virtualNodesFactor: Int): ConsistentHash[T] = new ConsistentHash( immutable.SortedMap.empty[Int, T] ++ (for { @@ -129,7 +128,6 @@ object ConsistentHash { vnode <- 1 to virtualNodesFactor } yield concatenateNodeHash(nodeHash, vnode) -> node), virtualNodesFactor) - } /** * Java API: Factory method to create a ConsistentHash diff --git a/actor/src/main/scala/org/apache/pekko/routing/ConsistentHashing.scala b/actor/src/main/scala/org/apache/pekko/routing/ConsistentHashing.scala index 4079957814e..75009445ec8 100644 --- a/actor/src/main/scala/org/apache/pekko/routing/ConsistentHashing.scala +++ b/actor/src/main/scala/org/apache/pekko/routing/ConsistentHashing.scala @@ -448,10 +448,9 @@ private[pekko] final case class ConsistentRoutee(routee: Routee, selfAddress: Ad case other => other.toString } - private def toStringWithfullAddress(path: ActorPath): String = { + private def toStringWithfullAddress(path: ActorPath): String = path.address match { case Address(_, _, None, None) => path.toStringWithAddress(selfAddress) case _ => path.toString } - } } diff --git a/actor/src/main/scala/org/apache/pekko/routing/MurmurHash.scala b/actor/src/main/scala/org/apache/pekko/routing/MurmurHash.scala index 24183fa2f32..532a311cf8a 100644 --- a/actor/src/main/scala/org/apache/pekko/routing/MurmurHash.scala +++ b/actor/src/main/scala/org/apache/pekko/routing/MurmurHash.scala @@ -149,13 +149,13 @@ object MurmurHash { def symmetricHash[T](xs: IterableOnce[T], seed: Int): Int = { var a, b, n = 0 var c = 1 - xs.foreach(i => { + xs.foreach { i => val h = i.## a += h b ^= h if (h != 0) c *= h n += 1 - }) + } var h = startHash(seed * n) h = extendHash(h, a, storedMagicA(0), storedMagicB(0)) h = extendHash(h, b, storedMagicA(1), storedMagicB(1)) diff --git a/actor/src/main/scala/org/apache/pekko/routing/OptimalSizeExploringResizer.scala b/actor/src/main/scala/org/apache/pekko/routing/OptimalSizeExploringResizer.scala index 6d366122423..0390b216d98 100644 --- a/actor/src/main/scala/org/apache/pekko/routing/OptimalSizeExploringResizer.scala +++ b/actor/src/main/scala/org/apache/pekko/routing/OptimalSizeExploringResizer.scala @@ -197,9 +197,8 @@ case class DefaultOptimalSizeExploringResizer( private val actionInternalNanos = actionInterval.toNanos - def isTimeForResize(messageCounter: Long): Boolean = { + def isTimeForResize(messageCounter: Long): Boolean = System.nanoTime() > record.checkTime + actionInternalNanos - } def reportMessageCount(currentRoutees: immutable.IndexedSeq[Routee], messageCounter: Long): Unit = { val (newPerfLog, newRecord) = updatedStats(currentRoutees, messageCounter) diff --git a/actor/src/main/scala/org/apache/pekko/routing/Resizer.scala b/actor/src/main/scala/org/apache/pekko/routing/Resizer.scala index 9b1acf0682f..e8a510cdb17 100644 --- a/actor/src/main/scala/org/apache/pekko/routing/Resizer.scala +++ b/actor/src/main/scala/org/apache/pekko/routing/Resizer.scala @@ -203,7 +203,7 @@ case class DefaultResizer( * @param routees the current resizer of routees * @return number of busy routees, between 0 and routees.size */ - def pressure(routees: immutable.IndexedSeq[Routee]): Int = { + def pressure(routees: immutable.IndexedSeq[Routee]): Int = routees.count { case ActorRefRoutee(a: ActorRefWithCell) => a.underlying match { @@ -223,7 +223,6 @@ case class DefaultResizer( case _ => false } - } /** * This method can be used to smooth the capacity delta by considering @@ -276,12 +275,11 @@ private[pekko] final class ResizablePoolCell( private val resizeInProgress = new AtomicBoolean private val resizeCounter = new AtomicLong - override protected def preSuperStart(): Unit = { + override protected def preSuperStart(): Unit = // initial resize, before message send if (resizer.isTimeForResize(resizeCounter.getAndIncrement())) { resize(initial = true) } - } override def sendMessage(envelope: Envelope): Unit = { if (!routerConfig.isManagementMessage(envelope.message) && @@ -292,7 +290,7 @@ private[pekko] final class ResizablePoolCell( super.sendMessage(envelope) } - private[pekko] def resize(initial: Boolean): Unit = { + private[pekko] def resize(initial: Boolean): Unit = if (resizeInProgress.get || initial) try { tryReportMessageCount() @@ -306,17 +304,15 @@ private[pekko] final class ResizablePoolCell( removeRoutees(abandon, stopChild = true) } } finally resizeInProgress.set(false) - } /** * This approach is chosen for binary compatibility */ - private def tryReportMessageCount(): Unit = { + private def tryReportMessageCount(): Unit = resizer match { case r: OptimalSizeExploringResizer => r.reportMessageCount(router.routees, resizeCounter.get()) case _ => // ignore } - } } diff --git a/actor/src/main/scala/org/apache/pekko/routing/RoutedActorCell.scala b/actor/src/main/scala/org/apache/pekko/routing/RoutedActorCell.scala index 49d0f29d4ee..de6f686c8cf 100644 --- a/actor/src/main/scala/org/apache/pekko/routing/RoutedActorCell.scala +++ b/actor/src/main/scala/org/apache/pekko/routing/RoutedActorCell.scala @@ -144,12 +144,11 @@ private[pekko] class RoutedActorCell( /** * Route the message via the router to the selected destination. */ - override def sendMessage(envelope: Envelope): Unit = { + override def sendMessage(envelope: Envelope): Unit = if (routerConfig.isManagementMessage(envelope.message)) super.sendMessage(envelope) else router.route(envelope.message, envelope.sender) - } } diff --git a/actor/src/main/scala/org/apache/pekko/routing/Router.scala b/actor/src/main/scala/org/apache/pekko/routing/Router.scala index 8a8dc0fee92..06fa5bfb0fa 100644 --- a/actor/src/main/scala/org/apache/pekko/routing/Router.scala +++ b/actor/src/main/scala/org/apache/pekko/routing/Router.scala @@ -131,12 +131,11 @@ final case class Router(logic: RoutingLogic, routees: immutable.IndexedSeq[Route case msg => send(logic.select(msg, routees), message, sender) } - private def send(routee: Routee, msg: Any, sender: ActorRef): Unit = { + private def send(routee: Routee, msg: Any, sender: ActorRef): Unit = if (routee == NoRoutee && sender.isInstanceOf[InternalActorRef]) sender.asInstanceOf[InternalActorRef].provider.deadLetters.tell(unwrap(msg), sender) else routee.send(unwrap(msg), sender) - } private def unwrap(msg: Any): Any = msg match { case env: RouterEnvelope => env.message diff --git a/actor/src/main/scala/org/apache/pekko/routing/SmallestMailbox.scala b/actor/src/main/scala/org/apache/pekko/routing/SmallestMailbox.scala index a549d66bd5a..87ff558e3f4 100644 --- a/actor/src/main/scala/org/apache/pekko/routing/SmallestMailbox.scala +++ b/actor/src/main/scala/org/apache/pekko/routing/SmallestMailbox.scala @@ -66,7 +66,7 @@ class SmallestMailboxRoutingLogic extends RoutingLogic { proposedTarget: Routee = NoRoutee, currentScore: Long = Long.MaxValue, at: Int = 0, - deep: Boolean = false): Routee = { + deep: Boolean = false): Routee = if (targets.isEmpty) NoRoutee else if (at >= targets.size) { @@ -90,7 +90,6 @@ class SmallestMailboxRoutingLogic extends RoutingLogic { else if (newScore < 0 || newScore >= currentScore) selectNext(targets, proposedTarget, currentScore, at + 1, deep) else selectNext(targets, target, newScore, at + 1, deep) } - } // TODO should we rewrite this not to use isTerminated? @nowarn("msg=deprecated") diff --git a/actor/src/main/scala/org/apache/pekko/routing/TailChopping.scala b/actor/src/main/scala/org/apache/pekko/routing/TailChopping.scala index 5343bdd1768..94e72ac5165 100644 --- a/actor/src/main/scala/org/apache/pekko/routing/TailChopping.scala +++ b/actor/src/main/scala/org/apache/pekko/routing/TailChopping.scala @@ -63,10 +63,9 @@ final case class TailChoppingRoutingLogic( interval: FiniteDuration, context: ExecutionContext) extends RoutingLogic { - override def select(message: Any, routees: immutable.IndexedSeq[Routee]): Routee = { + override def select(message: Any, routees: immutable.IndexedSeq[Routee]): Routee = if (routees.isEmpty) NoRoutee else TailChoppingRoutees(scheduler, routees, within, interval)(context) - } } /** diff --git a/actor/src/main/scala/org/apache/pekko/serialization/PrimitiveSerializers.scala b/actor/src/main/scala/org/apache/pekko/serialization/PrimitiveSerializers.scala index e256893779e..f7adace197e 100644 --- a/actor/src/main/scala/org/apache/pekko/serialization/PrimitiveSerializers.scala +++ b/actor/src/main/scala/org/apache/pekko/serialization/PrimitiveSerializers.scala @@ -31,13 +31,11 @@ import pekko.util.ByteString override val identifier: Int = BaseSerializer.identifierFromConfig("primitive-long", system) - override def toBinary(o: AnyRef, buf: ByteBuffer): Unit = { + override def toBinary(o: AnyRef, buf: ByteBuffer): Unit = buf.putLong(Long.unbox(o)) - } - override def fromBinary(buf: ByteBuffer, manifest: String): AnyRef = { + override def fromBinary(buf: ByteBuffer, manifest: String): AnyRef = Long.box(buf.getLong) - } override def toBinary(o: AnyRef): Array[Byte] = { val result = new Array[Byte](8) @@ -154,9 +152,8 @@ import pekko.util.ByteString result } - override def fromBinary(bytes: Array[Byte], manifest: Option[Class[_]]): AnyRef = { + override def fromBinary(bytes: Array[Byte], manifest: Option[Class[_]]): AnyRef = ByteString(bytes) - } } @@ -185,13 +182,12 @@ import pekko.util.ByteString buf.put(flag) } - override def fromBinary(buf: ByteBuffer, manifest: String): AnyRef = { + override def fromBinary(buf: ByteBuffer, manifest: String): AnyRef = buf.get() match { case TrueB => TRUE case FalseB => FALSE case b => throw new IllegalArgumentException(s"Non boolean flag byte: $b") } - } override def toBinary(o: AnyRef): Array[Byte] = { val flag = o match { @@ -204,11 +200,10 @@ import pekko.util.ByteString result } - override def fromBinary(bytes: Array[Byte], manifest: Option[Class[_]]): AnyRef = { + override def fromBinary(bytes: Array[Byte], manifest: Option[Class[_]]): AnyRef = bytes(0) match { case TrueB => TRUE case FalseB => FALSE case b => throw new IllegalArgumentException(s"Non boolean flag byte: $b") } - } } diff --git a/actor/src/main/scala/org/apache/pekko/serialization/Serialization.scala b/actor/src/main/scala/org/apache/pekko/serialization/Serialization.scala index e1c45503723..77303904547 100644 --- a/actor/src/main/scala/org/apache/pekko/serialization/Serialization.scala +++ b/actor/src/main/scala/org/apache/pekko/serialization/Serialization.scala @@ -130,14 +130,13 @@ object Serialization { * * @throws java.lang.IllegalStateException if the information was not set */ - def getCurrentTransportInformation(): Information = { + def getCurrentTransportInformation(): Information = Serialization.currentTransportInformation.value match { case null => throw new IllegalStateException( "currentTransportInformation is not set, use Serialization.withTransportInformation") case t => t } - } } @@ -172,11 +171,10 @@ class Serialization(val system: ExtendedActorSystem) extends Extension { * Serializes the given AnyRef/java.lang.Object according to the Serialization configuration * to either an Array of Bytes or an Exception if one was thrown. */ - def serialize(o: AnyRef): Try[Array[Byte]] = { + def serialize(o: AnyRef): Try[Array[Byte]] = withTransportInformation { () => Try(findSerializerFor(o).toBinary(o)) } - } /** * Deserializes the given array of bytes using the specified serializer id, @@ -220,10 +218,9 @@ class Serialization(val system: ExtendedActorSystem) extends Extension { private def deserializeByteArray(bytes: Array[Byte], serializer: Serializer, manifest: String): AnyRef = { - @tailrec def updateCache(cache: Map[String, Option[Class[_]]], key: String, value: Option[Class[_]]): Boolean = { + @tailrec def updateCache(cache: Map[String, Option[Class[_]]], key: String, value: Option[Class[_]]): Boolean = manifestCache.compareAndSet(cache, cache.updated(key, value)) || updateCache(manifestCache.get, key, value) // recursive, try again - } withTransportInformation { () => serializer match { @@ -289,11 +286,10 @@ class Serialization(val system: ExtendedActorSystem) extends Extension { * Deserializes the given array of bytes using the specified type to look up what Serializer should be used. * Returns either the resulting object or an Exception if one was thrown. */ - def deserialize[T](bytes: Array[Byte], clazz: Class[T]): Try[T] = { + def deserialize[T](bytes: Array[Byte], clazz: Class[T]): Try[T] = withTransportInformation { () => Try(serializerFor(clazz).fromBinary(bytes, Some(clazz)).asInstanceOf[T]) } - } /** * Returns the Serializer configured for the given object, returns the NullSerializer if it's null. @@ -322,7 +318,7 @@ class Serialization(val system: ExtendedActorSystem) extends Extension { (possibilities.forall(_._1.isAssignableFrom(possibilities(0)._1))) || (possibilities.forall(_._2 == possibilities(0)._2)) - val ser = { + val ser = bindings.filter { case (c, _) => c.isAssignableFrom(clazz) } match { @@ -356,7 +352,6 @@ class Serialization(val system: ExtendedActorSystem) extends Extension { } } - } serializerMap.putIfAbsent(clazz, ser) match { case null => @@ -382,9 +377,8 @@ class Serialization(val system: ExtendedActorSystem) extends Extension { * Tries to load the specified Serializer by the fully-qualified name; the actual * loading is performed by the system’s [[pekko.actor.DynamicAccess]]. */ - def serializerOf(serializerFQN: String): Try[Serializer] = { + def serializerOf(serializerFQN: String): Try[Serializer] = serializerOf(bindingName = "", serializerFQN) // for backwards compatibility since it's a public method - } /** * Tries to load the specified Serializer by the fully-qualified name; the actual @@ -460,13 +454,12 @@ class Serialization(val system: ExtendedActorSystem) extends Extension { result } - private def ensureOnlyAllowedSerializers(iter: Iterator[Serializer]): Unit = { + private def ensureOnlyAllowedSerializers(iter: Iterator[Serializer]): Unit = if (!system.settings.AllowJavaSerialization) { require(iter.forall(!isDisallowedJavaSerializer(_)), "Disallowed JavaSerializer binding.") } - } - private def warnUnexpectedNonPekkoSerializer(clazz: Class[_], ser: Serializer): Boolean = { + private def warnUnexpectedNonPekkoSerializer(clazz: Class[_], ser: Serializer): Boolean = if (clazz.getName.startsWith("org.apache.pekko.") && !ser.getClass.getName.startsWith("org.apache.pekko.")) { log.warning( "Using serializer [{}] for message [{}]. Note that this serializer " + @@ -476,7 +469,6 @@ class Serialization(val system: ExtendedActorSystem) extends Extension { clazz.getName) true } else false - } // com.google.protobuf serialization binding is only used if the class can be loaded, // i.e. com.google.protobuf dependency has been added in the application project. @@ -543,7 +535,7 @@ class Serialization(val system: ExtendedActorSystem) extends Extension { /** * @throws java.util.NoSuchElementException if no serializer with given `id` */ - private def getSerializerById(id: Int): Serializer = { + private def getSerializerById(id: Int): Serializer = if (0 <= id && id < quickSerializerByIdentity.length) { quickSerializerByIdentity(id) match { case null => throw new NoSuchElementException(s"key not found: $id") @@ -551,26 +543,23 @@ class Serialization(val system: ExtendedActorSystem) extends Extension { } } else serializerByIdentity(id) - } private val isJavaSerializationWarningEnabled = settings.config.getBoolean("pekko.actor.warn-about-java-serializer-usage") private val isWarningOnNoVerificationEnabled = settings.config.getBoolean("pekko.actor.warn-on-no-serialization-verification") - private def isDisallowedJavaSerializer(serializer: Serializer): Boolean = { + private def isDisallowedJavaSerializer(serializer: Serializer): Boolean = serializer.isInstanceOf[JavaSerializer] && !system.settings.AllowJavaSerialization - } /** * INTERNAL API */ @InternalApi private[pekko] def shouldWarnAboutJavaSerializer(serializedClass: Class[_], serializer: Serializer) = { - def suppressWarningOnNonSerializationVerification(serializedClass: Class[_]) = { + def suppressWarningOnNonSerializationVerification(serializedClass: Class[_]) = // suppressed, only when warn-on-no-serialization-verification = off, and extending NoSerializationVerificationNeeded !isWarningOnNoVerificationEnabled && classOf[NoSerializationVerificationNeeded].isAssignableFrom(serializedClass) - } isJavaSerializationWarningEnabled && (serializer.isInstanceOf[JavaSerializer] || serializer.isInstanceOf[DisabledJavaSerializer]) && diff --git a/actor/src/main/scala/org/apache/pekko/serialization/SerializationSetup.scala b/actor/src/main/scala/org/apache/pekko/serialization/SerializationSetup.scala index 1057f4758e8..1f53d296690 100644 --- a/actor/src/main/scala/org/apache/pekko/serialization/SerializationSetup.scala +++ b/actor/src/main/scala/org/apache/pekko/serialization/SerializationSetup.scala @@ -26,9 +26,8 @@ object SerializationSetup { * Scala API: Programmatic definition of serializers * @param createSerializers create pairs of serializer and the set of classes it should be used for */ - def apply(createSerializers: ExtendedActorSystem => immutable.Seq[SerializerDetails]): SerializationSetup = { + def apply(createSerializers: ExtendedActorSystem => immutable.Seq[SerializerDetails]): SerializationSetup = new SerializationSetup(createSerializers) - } /** * Java API: Programmatic definition of serializers diff --git a/actor/src/main/scala/org/apache/pekko/serialization/Serializer.scala b/actor/src/main/scala/org/apache/pekko/serialization/Serializer.scala index de8fc3943f4..41b8adbef15 100644 --- a/actor/src/main/scala/org/apache/pekko/serialization/Serializer.scala +++ b/actor/src/main/scala/org/apache/pekko/serialization/Serializer.scala @@ -347,7 +347,7 @@ class JavaSerializer(val system: ExtendedActorSystem) extends BaseSerializer { def toBinary(o: AnyRef): Array[Byte] = { val bos = new ByteArrayOutputStream val out = new ObjectOutputStream(bos) - JavaSerializer.currentSystem.withValue(system) { out.writeObject(o) } + JavaSerializer.currentSystem.withValue(system)(out.writeObject(o)) out.close() bos.toByteArray } @@ -355,7 +355,7 @@ class JavaSerializer(val system: ExtendedActorSystem) extends BaseSerializer { @throws(classOf[NotSerializableException]) def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]]): AnyRef = { val in = new ClassLoaderObjectInputStream(system.dynamicAccess.classLoader, new ByteArrayInputStream(bytes)) - val obj = JavaSerializer.currentSystem.withValue(system) { in.readObject } + val obj = JavaSerializer.currentSystem.withValue(system)(in.readObject) in.close() obj } diff --git a/actor/src/main/scala/org/apache/pekko/util/BoundedBlockingQueue.scala b/actor/src/main/scala/org/apache/pekko/util/BoundedBlockingQueue.scala index dc16c346e6d..54ebe841d57 100644 --- a/actor/src/main/scala/org/apache/pekko/util/BoundedBlockingQueue.scala +++ b/actor/src/main/scala/org/apache/pekko/util/BoundedBlockingQueue.scala @@ -52,7 +52,7 @@ class BoundedBlockingQueue[E <: AnyRef](val maxCapacity: Int, private val backin lock.lockInterruptibly() try { - @tailrec def putElement(): Unit = { + @tailrec def putElement(): Unit = if (backing.size() < maxCapacity) { require(backing.offer(e)) notEmpty.signal() @@ -60,7 +60,6 @@ class BoundedBlockingQueue[E <: AnyRef](val maxCapacity: Int, private val backin notFull.await() putElement() } - } putElement() } finally lock.unlock() } @@ -68,7 +67,7 @@ class BoundedBlockingQueue[E <: AnyRef](val maxCapacity: Int, private val backin def take(): E = { // Blocks until not empty lock.lockInterruptibly() try { - @tailrec def takeElement(): E = { + @tailrec def takeElement(): E = if (!backing.isEmpty()) { val e = backing.poll() require(e ne null) @@ -78,7 +77,6 @@ class BoundedBlockingQueue[E <: AnyRef](val maxCapacity: Int, private val backin notEmpty.await() takeElement() } - } takeElement() } finally lock.unlock() } @@ -86,28 +84,27 @@ class BoundedBlockingQueue[E <: AnyRef](val maxCapacity: Int, private val backin def offer(e: E): Boolean = { // Tries to do it immediately, if fail return false if (e eq null) throw new NullPointerException lock.lock() - try { + try if (backing.size() == maxCapacity) false else { require(backing.offer(e)) // Should never fail notEmpty.signal() true } - } finally lock.unlock() + finally lock.unlock() } def offer(e: E, timeout: Long, unit: TimeUnit): Boolean = { // Tries to do it within the timeout, return false if fail if (e eq null) throw new NullPointerException lock.lockInterruptibly() try { - @tailrec def offerElement(remainingNanos: Long): Boolean = { + @tailrec def offerElement(remainingNanos: Long): Boolean = if (backing.size() < maxCapacity) { require(backing.offer(e)) // Should never fail notEmpty.signal() true } else if (remainingNanos <= 0) false else offerElement(notFull.awaitNanos(remainingNanos)) - } offerElement(unit.toNanos(timeout)) } finally lock.unlock() } @@ -115,41 +112,39 @@ class BoundedBlockingQueue[E <: AnyRef](val maxCapacity: Int, private val backin def poll(timeout: Long, unit: TimeUnit): E = { // Tries to do it within the timeout, returns null if fail lock.lockInterruptibly() try { - @tailrec def pollElement(remainingNanos: Long): E = { + @tailrec def pollElement(remainingNanos: Long): E = backing.poll() match { case null if remainingNanos <= 0 => null.asInstanceOf[E] case null => pollElement(notEmpty.awaitNanos(remainingNanos)) - case e => { + case e => notFull.signal() e - } } - } pollElement(unit.toNanos(timeout)) } finally lock.unlock() } def poll(): E = { // Tries to remove the head of the queue immediately, if fail, return null lock.lock() - try { + try backing.poll() match { case null => null.asInstanceOf[E] case e => notFull.signal() e } - } finally lock.unlock() + finally lock.unlock() } override def remove(e: AnyRef): Boolean = { // Tries to do it immediately, if fail, return false if (e eq null) throw new NullPointerException lock.lock() - try { + try if (backing.remove(e)) { notFull.signal() true } else false - } finally lock.unlock() + finally lock.unlock() } override def contains(e: AnyRef): Boolean = { @@ -169,9 +164,9 @@ class BoundedBlockingQueue[E <: AnyRef](val maxCapacity: Int, private val backin def remainingCapacity(): Int = { lock.lock() - try { + try maxCapacity - backing.size() - } finally lock.unlock() + finally lock.unlock() } def size(): Int = { @@ -196,14 +191,13 @@ class BoundedBlockingQueue[E <: AnyRef](val maxCapacity: Int, private val backin else { lock.lock() try { - @tailrec def drainOne(n: Int = 0): Int = { + @tailrec def drainOne(n: Int = 0): Int = if (n < maxElements) { backing.poll() match { case null => n case e => c.add(e); drainOne(n + 1) } } else n - } val n = drainOne() if (n > 0) notFull.signalAll() n @@ -219,26 +213,26 @@ class BoundedBlockingQueue[E <: AnyRef](val maxCapacity: Int, private val backin override def removeAll(c: Collection[_]): Boolean = { lock.lock() - try { + try if (backing.removeAll(c)) { val sz = backing.size() if (sz < maxCapacity) notFull.signal() if (sz > 0) notEmpty.signal() true } else false - } finally lock.unlock() + finally lock.unlock() } override def retainAll(c: Collection[_]): Boolean = { lock.lock() - try { + try if (backing.retainAll(c)) { val sz = backing.size() if (sz < maxCapacity) notFull.signal() if (sz > 0) notEmpty.signal() true } else false - } finally lock.unlock() + finally lock.unlock() } def iterator(): Iterator[E] = { diff --git a/actor/src/main/scala/org/apache/pekko/util/Collections.scala b/actor/src/main/scala/org/apache/pekko/util/Collections.scala index 1fa5003da15..118dc255114 100644 --- a/actor/src/main/scala/org/apache/pekko/util/Collections.scala +++ b/actor/src/main/scala/org/apache/pekko/util/Collections.scala @@ -38,7 +38,7 @@ private[pekko] object Collections { private[this] var _hasNext = false override final def hasNext: Boolean = { - @tailrec def tailrecHasNext(): Boolean = { + @tailrec def tailrecHasNext(): Boolean = if (!_hasNext && superIterator.hasNext) { // If we need and are able to look for the next value val potentiallyNext = superIterator.next() if (isDefinedAt(potentiallyNext)) { @@ -47,7 +47,6 @@ private[pekko] object Collections { true } else tailrecHasNext() // Attempt to find the next } else _hasNext // Return if we found one - } tailrecHasNext() } diff --git a/actor/src/main/scala/org/apache/pekko/util/DoubleLinkedList.scala b/actor/src/main/scala/org/apache/pekko/util/DoubleLinkedList.scala index 7ada6789a1c..ad603b203f9 100644 --- a/actor/src/main/scala/org/apache/pekko/util/DoubleLinkedList.scala +++ b/actor/src/main/scala/org/apache/pekko/util/DoubleLinkedList.scala @@ -48,23 +48,21 @@ private[pekko] final class DoubleLinkedList[Node]( setPrevious(node, OptionVal.none) } - def moveToFront(node: Node): Node = { + def moveToFront(node: Node): Node = if (first.contains(node)) { node } else { unlink(node) prepend(node) } - } - def moveToBack(node: Node): Node = { + def moveToBack(node: Node): Node = if (last.contains(node)) { node } else { unlink(node) append(node) } - } def getFirstOrElsePrepend(check: Node => Boolean, newNode: => Node): Node = first match { case OptionVal.Some(first) if check(first) => first diff --git a/actor/src/main/scala/org/apache/pekko/util/FrequencySketch.scala b/actor/src/main/scala/org/apache/pekko/util/FrequencySketch.scala index e54cf1a0b59..5d898aca030 100644 --- a/actor/src/main/scala/org/apache/pekko/util/FrequencySketch.scala +++ b/actor/src/main/scala/org/apache/pekko/util/FrequencySketch.scala @@ -403,7 +403,7 @@ private[pekko] object FrequencySketchUtil { builder ++= s" %${counterDigits}d ".format(slot) } builder ++= "║\n" - for (row <- matrix.indices) { + for (row <- matrix.indices) for (column <- matrix(0).indices) { builder ++= (if (column == 0) divider("╠", "═", "╬", "╪", "╣") else divider("╟", "─", "╫", "┼", "╢")) @@ -417,7 +417,6 @@ private[pekko] object FrequencySketchUtil { } builder ++= "║\n" } - } builder ++= divider("╚", "═", "╩", "╧", "╝") builder.result() } diff --git a/actor/src/main/scala/org/apache/pekko/util/Helpers.scala b/actor/src/main/scala/org/apache/pekko/util/Helpers.scala index 8b93060302d..878147f53c3 100644 --- a/actor/src/main/scala/org/apache/pekko/util/Helpers.scala +++ b/actor/src/main/scala/org/apache/pekko/util/Helpers.scala @@ -108,9 +108,8 @@ object Helpers { private val formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss.SSS") private val timeZone = ZoneId.systemDefault() - def timestamp(time: Long): String = { + def timestamp(time: Long): String = formatter.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(time), timeZone)) - } final val base64chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+~" diff --git a/actor/src/main/scala/org/apache/pekko/util/Index.scala b/actor/src/main/scala/org/apache/pekko/util/Index.scala index 784f523f8b7..0a37a11cb8d 100644 --- a/actor/src/main/scala/org/apache/pekko/util/Index.scala +++ b/actor/src/main/scala/org/apache/pekko/util/Index.scala @@ -93,12 +93,11 @@ class Index[K, V](val mapSize: Int, val valueComparator: Comparator[V]) { /** * Returns an Iterator of V containing the values for the supplied key, or an empty iterator if the key doesn't exist */ - def valueIterator(key: K): scala.Iterator[V] = { + def valueIterator(key: K): scala.Iterator[V] = container.get(key) match { case null => Iterator.empty case some => some.iterator.asScala } - } /** * Applies the supplied function to all keys and their values diff --git a/actor/src/main/scala/org/apache/pekko/util/LineNumbers.scala b/actor/src/main/scala/org/apache/pekko/util/LineNumbers.scala index 648d790ed9a..fa8d2802051 100644 --- a/actor/src/main/scala/org/apache/pekko/util/LineNumbers.scala +++ b/actor/src/main/scala/org/apache/pekko/util/LineNumbers.scala @@ -187,13 +187,12 @@ object LineNumbers { } catch { case NonFatal(ex) => UnknownSourceFormat(s"parse error: ${ex.getMessage}") - } finally { + } finally try dis.close() catch { case ex: InterruptedException => throw ex case NonFatal(_) => // ignore } - } } private def getStreamForClass(c: Class[_]): Option[(InputStream, None.type)] = { diff --git a/actor/src/main/scala/org/apache/pekko/util/LockUtil.scala b/actor/src/main/scala/org/apache/pekko/util/LockUtil.scala index 5c8c834a9a2..c2dabce4a81 100644 --- a/actor/src/main/scala/org/apache/pekko/util/LockUtil.scala +++ b/actor/src/main/scala/org/apache/pekko/util/LockUtil.scala @@ -60,12 +60,12 @@ class Switch(startAsOn: Boolean = false) { /** * Switches the switch off (if on), uses locking */ - def switchOff: Boolean = synchronized { switch.compareAndSet(true, false) } + def switchOff: Boolean = synchronized(switch.compareAndSet(true, false)) /** * Switches the switch on (if off), uses locking */ - def switchOn: Boolean = synchronized { switch.compareAndSet(false, true) } + def switchOn: Boolean = synchronized(switch.compareAndSet(false, true)) /** * Executes the provided action and returns its value if the switch is IMMEDIATELY on (i.e. no lock involved) @@ -80,34 +80,32 @@ class Switch(startAsOn: Boolean = false) { /** * Executes the provided action and returns if the action was executed or not, if the switch is IMMEDIATELY on (i.e. no lock involved) */ - def ifOn(action: => Unit): Boolean = { + def ifOn(action: => Unit): Boolean = if (switch.get) { action true } else false - } /** * Executes the provided action and returns if the action was executed or not, if the switch is IMMEDIATELY off (i.e. no lock involved) */ - def ifOff(action: => Unit): Boolean = { + def ifOff(action: => Unit): Boolean = if (!switch.get) { action true } else false - } /** * Executes the provided action and returns its value if the switch is on, waiting for any pending changes to happen before (locking) * Be careful of longrunning or blocking within the provided action as it can lead to deadlocks or bad performance */ - def whileOnYield[T](action: => T): Option[T] = synchronized { if (switch.get) Some(action) else None } + def whileOnYield[T](action: => T): Option[T] = synchronized(if (switch.get) Some(action) else None) /** * Executes the provided action and returns its value if the switch is off, waiting for any pending changes to happen before (locking) * Be careful of longrunning or blocking within the provided action as it can lead to deadlocks or bad performance */ - def whileOffYield[T](action: => T): Option[T] = synchronized { if (!switch.get) Some(action) else None } + def whileOffYield[T](action: => T): Option[T] = synchronized(if (!switch.get) Some(action) else None) /** * Executes the provided action and returns if the action was executed or not, if the switch is on, waiting for any pending changes to happen before (locking) @@ -135,12 +133,12 @@ class Switch(startAsOn: Boolean = false) { * Executes the provided callbacks depending on if the switch is either on or off waiting for any pending changes to happen before (locking) * Be careful of longrunning or blocking within the provided action as it can lead to deadlocks or bad performance */ - def fold[T](on: => T)(off: => T): T = synchronized { if (switch.get) on else off } + def fold[T](on: => T)(off: => T): T = synchronized(if (switch.get) on else off) /** * Executes the given code while holding this switch’s lock, i.e. protected from concurrent modification of the switch status. */ - def locked[T](code: => T): T = synchronized { code } + def locked[T](code: => T): T = synchronized(code) /** * Returns whether the switch is IMMEDIATELY on (no locking) diff --git a/actor/src/main/scala/org/apache/pekko/util/ManifestInfo.scala b/actor/src/main/scala/org/apache/pekko/util/ManifestInfo.scala index b77b46bfade..dfa69714ea4 100644 --- a/actor/src/main/scala/org/apache/pekko/util/ManifestInfo.scala +++ b/actor/src/main/scala/org/apache/pekko/util/ManifestInfo.scala @@ -143,9 +143,8 @@ final class ManifestInfo(val system: ExtendedActorSystem) extends Extension { && knownVendors(vendor)) { manifests = manifests.updated(title, new Version(version)) } - } finally { + } finally ios.close() - } } } catch { case ioe: IOException => @@ -162,9 +161,8 @@ final class ManifestInfo(val system: ExtendedActorSystem) extends Extension { * * @return `true` if versions are the same */ - def checkSameVersion(productName: String, dependencies: immutable.Seq[String], logWarning: Boolean): Boolean = { + def checkSameVersion(productName: String, dependencies: immutable.Seq[String], logWarning: Boolean): Boolean = checkSameVersion(productName, dependencies, logWarning, throwException = system.settings.FailMixedVersions) - } /** * Verify that the version is the same for all given artifacts. @@ -178,7 +176,7 @@ final class ManifestInfo(val system: ExtendedActorSystem) extends Extension { productName: String, dependencies: immutable.Seq[String], logWarning: Boolean, - throwException: Boolean): Boolean = { + throwException: Boolean): Boolean = ManifestInfo.checkSameVersion(productName, dependencies, versions) match { case Some(message) => if (logWarning) @@ -190,5 +188,4 @@ final class ManifestInfo(val system: ExtendedActorSystem) extends Extension { false case None => true } - } } diff --git a/actor/src/main/scala/org/apache/pekko/util/MessageBuffer.scala b/actor/src/main/scala/org/apache/pekko/util/MessageBuffer.scala index b718a52d1ff..53085d2e724 100644 --- a/actor/src/main/scala/org/apache/pekko/util/MessageBuffer.scala +++ b/actor/src/main/scala/org/apache/pekko/util/MessageBuffer.scala @@ -160,9 +160,8 @@ final class MessageBuffer private (private var _head: MessageBuffer.Node, privat object MessageBuffer { private final class Node(var next: Node, val message: Any, val ref: ActorRef) { - def apply(f: (Any, ActorRef) => Unit): Unit = { + def apply(f: (Any, ActorRef) => Unit): Unit = f(message, ref) - } override def toString: String = s"Node($message,$ref)" } @@ -214,9 +213,8 @@ final class MessageBufferMap[I] { def totalSize: Int = { var s: Int = 0 val values = bufferMap.values().iterator() - while (values.hasNext) { + while (values.hasNext) s += values.next().size - } s } @@ -232,9 +230,8 @@ final class MessageBufferMap[I] { /** * Add an id to the buffer map */ - def add(id: I): Unit = { + def add(id: I): Unit = getOrAddBuffer(id) - } /** * Append an element to the buffer for an id. @@ -253,9 +250,8 @@ final class MessageBufferMap[I] { * * @param id the id to remove the buffer for */ - def remove(id: I): Unit = { + def remove(id: I): Unit = bufferMap.remove(id) - } /** * Remove the buffer for an id, but publish a [[pekko.actor.Dropped]] for each dropped buffered message @@ -276,9 +272,8 @@ final class MessageBufferMap[I] { * @param id the id to check for * @return if the buffer contains the given id */ - def contains(id: I): Boolean = { + def contains(id: I): Boolean = bufferMap.containsKey(id) - } /** * Get the message buffer for an id, or an empty buffer if the id doesn't exist in the map. diff --git a/actor/src/main/scala/org/apache/pekko/util/Reflect.scala b/actor/src/main/scala/org/apache/pekko/util/Reflect.scala index 2450e895cdd..2cb6d848cd4 100644 --- a/actor/src/main/scala/org/apache/pekko/util/Reflect.scala +++ b/actor/src/main/scala/org/apache/pekko/util/Reflect.scala @@ -40,7 +40,7 @@ private[pekko] object Reflect { * * Hint: when comparing to Thread.currentThread().getStackTrace, add two levels. */ - val getCallerClass: Option[Int => Class[_]] = { + val getCallerClass: Option[Int => Class[_]] = try { val c = Class.forName("sun.reflect.Reflection") val m = c.getMethod("getCallerClass", Array(classOf[Int]): _*) @@ -48,7 +48,6 @@ private[pekko] object Reflect { } catch { case NonFatal(_) => None } - } /** * INTERNAL API @@ -69,9 +68,8 @@ private[pekko] object Reflect { * INTERNAL API * Calls findConstructor and invokes it with the given arguments. */ - private[pekko] def instantiate[T](clazz: Class[T], args: immutable.Seq[Any]): T = { + private[pekko] def instantiate[T](clazz: Class[T], args: immutable.Seq[Any]): T = instantiate(findConstructor(clazz, args), args) - } /** * INTERNAL API @@ -99,7 +97,7 @@ private[pekko] object Reflect { } val constructor: Constructor[T] = - if (args.isEmpty) Try { clazz.getDeclaredConstructor() }.getOrElse(null) + if (args.isEmpty) Try(clazz.getDeclaredConstructor()).getOrElse(null) else { val length = args.length val candidates = @@ -134,7 +132,7 @@ private[pekko] object Reflect { private[pekko] def instantiator[T](clazz: Class[T]): () => T = () => instantiate(clazz) def findMarker(root: Class[_], marker: Class[_]): Type = { - @tailrec def rec(curr: Class[_]): Type = { + @tailrec def rec(curr: Class[_]): Type = if (curr.getSuperclass != null && marker.isAssignableFrom(curr.getSuperclass)) rec(curr.getSuperclass) else curr.getGenericInterfaces.collectFirst { @@ -146,7 +144,6 @@ private[pekko] object Reflect { case Some(t: ParameterizedType) => if (t.getRawType == marker) t else rec(t.getRawType.asInstanceOf[Class[_]]) case _ => ??? // cannot happen due to collectFirst } - } rec(root) } diff --git a/actor/src/main/scala/org/apache/pekko/util/SegmentedRecencyList.scala b/actor/src/main/scala/org/apache/pekko/util/SegmentedRecencyList.scala index c3fc143d013..5ec0a484f71 100644 --- a/actor/src/main/scala/org/apache/pekko/util/SegmentedRecencyList.scala +++ b/actor/src/main/scala/org/apache/pekko/util/SegmentedRecencyList.scala @@ -105,14 +105,13 @@ private[pekko] final class SegmentedRecencyList[A]( def leastToMostRecentOf(level: Int): Iterator[A] = segments(level).forwardIterator.map(_.value) - def removeLeastRecentOverLimit(): immutable.Seq[A] = { + def removeLeastRecentOverLimit(): immutable.Seq[A] = if (size > totalLimit) { adjustProtectedLevels() val excess = size - totalLimit if (excess == 1) removeLeastRecent() // optimised removal of just 1 node else segments(lowest).forwardIterator.take(excess).map(removeNode).toList } else Nil - } def removeLeastRecent(): immutable.Seq[A] = segments(lowest).getFirst match { case OptionVal.Some(first) => List(removeNode(first)) diff --git a/actor/src/main/scala/org/apache/pekko/util/SubclassifiedIndex.scala b/actor/src/main/scala/org/apache/pekko/util/SubclassifiedIndex.scala index d8540591331..638c1b6868b 100644 --- a/actor/src/main/scala/org/apache/pekko/util/SubclassifiedIndex.scala +++ b/actor/src/main/scala/org/apache/pekko/util/SubclassifiedIndex.scala @@ -39,10 +39,9 @@ private[pekko] object SubclassifiedIndex { implicit sc: Subclassification[K]) extends SubclassifiedIndex[K, V](_values) { - override def innerAddValue(key: K, value: V): Changes = { + override def innerAddValue(key: K, value: V): Changes = // break the recursion on super when key is found and transition to recursive add-to-set if (sc.isEqual(key, this.key)) addValue(value) else super.innerAddValue(key, value) - } private def addValue(value: V): Changes = { val kids = subkeys.flatMap(_.addValue(value)) @@ -53,10 +52,9 @@ private[pekko] object SubclassifiedIndex { } // this will return the keys and values to be removed from the cache - override def innerRemoveValue(key: K, value: V): Changes = { + override def innerRemoveValue(key: K, value: V): Changes = // break the recursion on super when key is found and transition to recursive remove-from-set if (sc.isEqual(key, this.key)) removeValue(value) else super.innerRemoveValue(key, value) - } override def removeValue(value: V): Changes = { val kids = subkeys.flatMap(_.removeValue(value)) diff --git a/actor/src/main/scala/org/apache/pekko/util/TypedMultiMap.scala b/actor/src/main/scala/org/apache/pekko/util/TypedMultiMap.scala index c22e603ab29..7e4a7efcdae 100644 --- a/actor/src/main/scala/org/apache/pekko/util/TypedMultiMap.scala +++ b/actor/src/main/scala/org/apache/pekko/util/TypedMultiMap.scala @@ -84,7 +84,7 @@ class TypedMultiMap[T <: AnyRef, K[_ <: T]] private (private val map: Map[T, Set /** * Return a map that has the given mapping from the given key removed. */ - def removed(key: T)(value: K[key.type]): TypedMultiMap[T, K] = { + def removed(key: T)(value: K[key.type]): TypedMultiMap[T, K] = map.get(key) match { case None => this case Some(set) => @@ -94,7 +94,6 @@ class TypedMultiMap[T <: AnyRef, K[_ <: T]] private (private val map: Map[T, Set new TypedMultiMap[T, K](newmap) } else this } - } def setAll(key: T)(values: Set[K[key.type]]): TypedMultiMap[T, K] = new TypedMultiMap[T, K](map.updated(key, values.asInstanceOf[Set[Any]])) diff --git a/actor/src/main/scala/org/apache/pekko/util/Version.scala b/actor/src/main/scala/org/apache/pekko/util/Version.scala index 1e44e4e67bf..9300673f83b 100644 --- a/actor/src/main/scala/org/apache/pekko/util/Version.scala +++ b/actor/src/main/scala/org/apache/pekko/util/Version.scala @@ -53,7 +53,7 @@ final class Version(val version: String) extends Comparable[Version] { * INTERNAL API */ @InternalApi private[pekko] def parse(): Version = { - def parseLastPart(s: String): (Int, String) = { + def parseLastPart(s: String): (Int, String) = // for example 2, 2-SNAPSHOT or dynver 2+10-1234abcd if (s.length == 0) { Undefined -> s @@ -69,9 +69,8 @@ final class Version(val version: String) extends Comparable[Version] { else s.substring(0, k).toInt -> s.substring(k + 1) } - } - def parseDynverPart(s: String): (Int, String) = { + def parseDynverPart(s: String): (Int, String) = // for example SNAPSHOT or dynver 10-1234abcd if (s.isEmpty || !s.charAt(0).isDigit) { Undefined -> s @@ -80,15 +79,14 @@ final class Version(val version: String) extends Comparable[Version] { case -1 => Undefined -> s case i => - try { + try s.substring(0, i).toInt -> s.substring(i + 1) - } catch { + catch { case _: NumberFormatException => Undefined -> s } } } - } def parseLastParts(s: String): (Int, Int, String) = { // for example 2, 2-SNAPSHOT or dynver 2+10-1234abcd @@ -152,7 +150,7 @@ final class Version(val version: String) extends Comparable[Version] { this } - override def compareTo(other: Version): Int = { + override def compareTo(other: Version): Int = if (version == other.version) // String equals without requiring parse 0 else { @@ -179,7 +177,6 @@ final class Version(val version: String) extends Comparable[Version] { } diff } - } override def equals(o: Any): Boolean = o match { case v: Version => compareTo(v) == 0 diff --git a/actor/src/main/scala/org/apache/pekko/util/WallClock.scala b/actor/src/main/scala/org/apache/pekko/util/WallClock.scala index ec1ff6a1f71..38cc98acc9a 100644 --- a/actor/src/main/scala/org/apache/pekko/util/WallClock.scala +++ b/actor/src/main/scala/org/apache/pekko/util/WallClock.scala @@ -47,10 +47,9 @@ private[pekko] final class AlwaysIncreasingClock() extends AtomicLong with WallC val currentSystemTime = System.currentTimeMillis() updateAndGet { new LongUnaryOperator { - override def applyAsLong(time: Long): Long = { + override def applyAsLong(time: Long): Long = if (currentSystemTime <= time) time + 1 else currentSystemTime - } } } } diff --git a/actor/src/main/scala/org/apache/pekko/util/WildcardIndex.scala b/actor/src/main/scala/org/apache/pekko/util/WildcardIndex.scala index 344220344f3..373bb5a7143 100644 --- a/actor/src/main/scala/org/apache/pekko/util/WildcardIndex.scala +++ b/actor/src/main/scala/org/apache/pekko/util/WildcardIndex.scala @@ -97,7 +97,7 @@ private[pekko] final case class WildcardTree[T]( @tailrec def findWithTerminalDoubleWildcard( elems: Iterator[String], - alt: WildcardTree[T] = WildcardTree[T]()): WildcardTree[T] = { + alt: WildcardTree[T] = WildcardTree[T]()): WildcardTree[T] = if (!elems.hasNext) this else { val newAlt = children.getOrElse("**", alt) @@ -110,5 +110,4 @@ private[pekko] final case class WildcardTree[T]( } } } - } } diff --git a/bench-jmh/src/main/scala/org/apache/pekko/actor/BenchmarkActors.scala b/bench-jmh/src/main/scala/org/apache/pekko/actor/BenchmarkActors.scala index 340319ef4ba..189883e1a63 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/actor/BenchmarkActors.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/actor/BenchmarkActors.scala @@ -73,7 +73,7 @@ object BenchmarkActors { } } - private def sendBatch(): Boolean = { + private def sendBatch(): Boolean = if (left > 0) { var i = 0 while (i < batchSize) { @@ -85,7 +85,6 @@ object BenchmarkActors { true } else false - } } class Pipe(next: Option[ActorRef]) extends Actor { @@ -116,14 +115,12 @@ object BenchmarkActors { (actors, latch) } - private def initiatePingPongForPairs(refs: Vector[(ActorRef, ActorRef)], inFlight: Int): Unit = { + private def initiatePingPongForPairs(refs: Vector[(ActorRef, ActorRef)], inFlight: Int): Unit = for { (ping, pong) <- refs _ <- 1 to inFlight - } { - ping.tell(Message, pong) } - } + ping.tell(Message, pong) private def startEchoActorPairs(messagesPerPair: Int, numPairs: Int, dispatcher: String, batchSize: Int)( implicit system: ActorSystem): (Vector[ActorRef], CountDownLatch) = { @@ -136,9 +133,8 @@ object BenchmarkActors { (actors, latch) } - private def initiateEchoPairs(refs: Vector[ActorRef]): Unit = { + private def initiateEchoPairs(refs: Vector[ActorRef]): Unit = refs.foreach(_ ! Message) - } def printProgress(totalMessages: Long, numActors: Int, startNanoTime: Long): Unit = { val durationMicros = (System.nanoTime() - startNanoTime) / 1000 diff --git a/bench-jmh/src/main/scala/org/apache/pekko/actor/DirectByteBufferPoolBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/actor/DirectByteBufferPoolBenchmark.scala index 4e373bd01a6..f0b91e18325 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/actor/DirectByteBufferPoolBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/actor/DirectByteBufferPoolBenchmark.scala @@ -36,9 +36,8 @@ class DirectByteBufferPoolBenchmark { private[pekko] var arteryPool: DirectByteBufferPool = _ @Setup(Level.Trial) - def setup(): Unit = { + def setup(): Unit = arteryPool = new DirectByteBufferPool(size, MAX_LIVE_BUFFERS) - } @TearDown(Level.Trial) def tearDown(): Unit = { diff --git a/bench-jmh/src/main/scala/org/apache/pekko/actor/RequestResponseActors.scala b/bench-jmh/src/main/scala/org/apache/pekko/actor/RequestResponseActors.scala index 5a40dbdca02..273b43fec34 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/actor/RequestResponseActors.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/actor/RequestResponseActors.scala @@ -30,7 +30,7 @@ object RequestResponseActors { private val randGenerator = new Random() override def receive: Receive = { - case u: User => { + case u: User => receivedUsers.put(u.userId, u) if (left == 0) { latch.countDown() @@ -39,14 +39,12 @@ object RequestResponseActors { sender() ! Request(randGenerator.nextInt(numUsersInDB)) } left -= 1 - } } } object UserQueryActor { - def props(latch: CountDownLatch, numQueries: Int, numUsersInDB: Int) = { + def props(latch: CountDownLatch, numQueries: Int, numUsersInDB: Int) = Props(new UserQueryActor(latch, numQueries, numUsersInDB)) - } } class UserServiceActor(userDb: Map[Int, User], latch: CountDownLatch, numQueries: Int) extends Actor { @@ -94,13 +92,11 @@ object RequestResponseActors { (actorsPairs, latch) } - def initiateQuerySimulation(requestResponseActorPairs: Seq[(ActorRef, ActorRef)], inFlight: Int) = { + def initiateQuerySimulation(requestResponseActorPairs: Seq[(ActorRef, ActorRef)], inFlight: Int) = for { (queryActor, serviceActor) <- requestResponseActorPairs i <- 1 to inFlight - } { - serviceActor.tell(Request(i), queryActor) } - } + serviceActor.tell(Request(i), queryActor) } diff --git a/bench-jmh/src/main/scala/org/apache/pekko/actor/TellOnlyBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/actor/TellOnlyBenchmark.scala index 80052e1e8f3..44eda68a223 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/actor/TellOnlyBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/actor/TellOnlyBenchmark.scala @@ -38,7 +38,7 @@ class TellOnlyBenchmark { implicit var system: ActorSystem = _ @Setup(Level.Trial) - def setup(): Unit = { + def setup(): Unit = system = ActorSystem( "TellOnlyBenchmark", ConfigFactory.parseString(s"""| pekko { @@ -61,7 +61,6 @@ class TellOnlyBenchmark { | mailbox-type = "org.apache.pekko.actor.TellOnlyBenchmark$$UnboundedDroppingMailbox" | } | """.stripMargin)) - } @TearDown(Level.Trial) def shutdown(): Unit = { @@ -96,9 +95,8 @@ class TellOnlyBenchmark { @Benchmark @OutputTimeUnit(TimeUnit.MICROSECONDS) - def tell(): Unit = { + def tell(): Unit = probe.send(actor, message) - } } object TellOnlyBenchmark { @@ -119,10 +117,9 @@ object TellOnlyBenchmark { class DroppingMessageQueue extends UnboundedMailbox.MessageQueue { @volatile var dropping = false - override def enqueue(receiver: ActorRef, handle: Envelope): Unit = { + override def enqueue(receiver: ActorRef, handle: Envelope): Unit = if (handle.message == flipDrop) dropping = !dropping else if (!dropping) super.enqueue(receiver, handle) - } } case class UnboundedDroppingMailbox() extends MailboxType with ProducesMessageQueue[DroppingMessageQueue] { diff --git a/bench-jmh/src/main/scala/org/apache/pekko/actor/typed/TypedActorBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/actor/typed/TypedActorBenchmark.scala index 56049bc876d..0947e84f142 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/actor/typed/TypedActorBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/actor/typed/TypedActorBenchmark.scala @@ -106,8 +106,7 @@ class TypedActorBenchmark { @Benchmark @OperationsPerInvocation(totalMessages) - def echo(): Unit = { + def echo(): Unit = Await.result(system.ask(Start(_)), timeout) - } } diff --git a/bench-jmh/src/main/scala/org/apache/pekko/actor/typed/TypedBenchmarkActors.scala b/bench-jmh/src/main/scala/org/apache/pekko/actor/typed/TypedBenchmarkActors.scala index 1d0eaf9fa2b..df9420af076 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/actor/typed/TypedBenchmarkActors.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/actor/typed/TypedBenchmarkActors.scala @@ -43,7 +43,7 @@ object TypedBenchmarkActors { var left = messagesPerPair / 2 var batch = 0 - def sendBatch(): Boolean = { + def sendBatch(): Boolean = if (left > 0) { var i = 0 while (i < batchSize) { @@ -55,7 +55,6 @@ object TypedBenchmarkActors { true } else false - } Behaviors.receiveMessage { _ => batch -= 1 @@ -133,7 +132,7 @@ object TypedBenchmarkActors { extends PingPongCommand case class PingPongStarted(completedLatch: CountDownLatch, startNanoTime: Long, totalNumMessages: Int) case object Stop extends PingPongCommand - def benchmarkPingPongSupervisor(): Behavior[PingPongCommand] = { + def benchmarkPingPongSupervisor(): Behavior[PingPongCommand] = Behaviors.setup { ctx => Behaviors.receiveMessage { case StartPingPong(numMessagesPerActorPair, numActors, dispatcher, throughput, _, replyTo) => @@ -150,15 +149,13 @@ object TypedBenchmarkActors { Behaviors.same } } - } - private def initiatePingPongForPairs(refs: Vector[(ActorRef[Message], ActorRef[Message])], inFlight: Int): Unit = { + private def initiatePingPongForPairs(refs: Vector[(ActorRef[Message], ActorRef[Message])], inFlight: Int): Unit = for { (ping, pong) <- refs message = Message(pong) // just allocate once _ <- 1 to inFlight } ping ! message - } private def startPingPongActorPairs( ctx: ActorContext[_], diff --git a/bench-jmh/src/main/scala/org/apache/pekko/actor/typed/delivery/ReliableDeliveryBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/actor/typed/delivery/ReliableDeliveryBenchmark.scala index 0651949efb0..302c04c7818 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/actor/typed/delivery/ReliableDeliveryBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/actor/typed/delivery/ReliableDeliveryBenchmark.scala @@ -46,7 +46,7 @@ object Producer { def apply( numberOfMessages: Int, useAsk: Boolean, - producerController: ActorRef[ProducerController.Command[Consumer.Command]]): Behavior[Command] = { + producerController: ActorRef[ProducerController.Command[Consumer.Command]]): Behavior[Command] = Behaviors.setup { context => val requestNextAdapter = context.messageAdapter[ProducerController.RequestNext[Consumer.Command]](WrappedRequestNext(_)) @@ -78,7 +78,6 @@ object Producer { Behaviors.same } } - } } object Consumer { @@ -91,7 +90,7 @@ object Consumer { def serviceKey(testName: String): ServiceKey[ConsumerController.Command[Command]] = ServiceKey[ConsumerController.Command[Consumer.Command]](testName) - def apply(consumerController: ActorRef[ConsumerController.Command[Command]]): Behavior[Command] = { + def apply(consumerController: ActorRef[ConsumerController.Command[Command]]): Behavior[Command] = Behaviors.setup { context => val traceEnabled = context.log.isTraceEnabled val deliveryAdapter = @@ -106,7 +105,6 @@ object Consumer { Behaviors.same } } - } } object WorkPullingProducer { @@ -117,7 +115,7 @@ object WorkPullingProducer { def apply( numberOfMessages: Int, - producerController: ActorRef[WorkPullingProducerController.Command[Consumer.Command]]): Behavior[Command] = { + producerController: ActorRef[WorkPullingProducerController.Command[Consumer.Command]]): Behavior[Command] = Behaviors.setup { context => val requestNextAdapter = context.messageAdapter[WorkPullingProducerController.RequestNext[Consumer.Command]](WrappedRequestNext(_)) @@ -141,7 +139,6 @@ object WorkPullingProducer { Behaviors.same } } - } } object Guardian { @@ -154,7 +151,7 @@ object Guardian { final case class ProducerTerminated(consumers: List[ActorRef[Consumer.Command]], replyTo: ActorRef[Done]) extends Command - def apply(): Behavior[Command] = { + def apply(): Behavior[Command] = Behaviors.setup { context => Behaviors.receiveMessage { case RunPointToPoint(id, numberOfMessages, useAsk, replyTo) => @@ -198,7 +195,6 @@ object Guardian { throw new RuntimeException(s"Unexpected message $msg") } } - } } object ReliableDeliveryBenchmark { @@ -223,7 +219,7 @@ class ReliableDeliveryBenchmark { implicit val askTimeout: pekko.util.Timeout = pekko.util.Timeout(timeout) @Setup(Level.Trial) - def setup(): Unit = { + def setup(): Unit = system = ActorSystem( Guardian(), "ReliableDeliveryBenchmark", @@ -233,7 +229,6 @@ class ReliableDeliveryBenchmark { consumer-controller.flow-control-window = $window } """)) - } @TearDown(Level.Trial) def shutdown(): Unit = { @@ -243,36 +238,32 @@ class ReliableDeliveryBenchmark { @Benchmark @OperationsPerInvocation(messagesPerOperation) - def pointToPoint(): Unit = { + def pointToPoint(): Unit = Await.result( system.ask( Guardian.RunPointToPoint(s"point-to-point-${UUID.randomUUID()}", messagesPerOperation, useAsk = false, _)), timeout) - } @Benchmark @OperationsPerInvocation(messagesPerOperation) - def pointToPointAsk(): Unit = { + def pointToPointAsk(): Unit = Await.result( system.ask( Guardian.RunPointToPoint(s"point-to-point-${UUID.randomUUID()}", messagesPerOperation, useAsk = true, _)), timeout) - } @Benchmark @OperationsPerInvocation(messagesPerOperation) - def workPulling1(): Unit = { + def workPulling1(): Unit = Await.result( system.ask(Guardian.RunWorkPulling(s"work-pulling-${UUID.randomUUID()}", messagesPerOperation, workers = 1, _)), timeout) - } @Benchmark @OperationsPerInvocation(messagesPerOperation) - def workPulling2(): Unit = { + def workPulling2(): Unit = Await.result( system.ask(Guardian.RunWorkPulling(s"work-pulling-${UUID.randomUUID()}", messagesPerOperation, workers = 2, _)), timeout) - } } diff --git a/bench-jmh/src/main/scala/org/apache/pekko/persistence/LevelDbBatchingBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/persistence/LevelDbBatchingBenchmark.scala index 551d9ea6607..e1f392686a8 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/persistence/LevelDbBatchingBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/persistence/LevelDbBatchingBenchmark.scala @@ -52,10 +52,10 @@ class LevelDbBatchingBenchmark { var probe: TestProbe = _ var store: ActorRef = _ - val batch_1 = List.fill(1) { AtomicWrite(PersistentRepr("data", 12, "pa")) } - val batch_10 = List.fill(10) { AtomicWrite(PersistentRepr("data", 12, "pa")) } - val batch_100 = List.fill(100) { AtomicWrite(PersistentRepr("data", 12, "pa")) } - val batch_200 = List.fill(200) { AtomicWrite(PersistentRepr("data", 12, "pa")) } + val batch_1 = List.fill(1)(AtomicWrite(PersistentRepr("data", 12, "pa"))) + val batch_10 = List.fill(10)(AtomicWrite(PersistentRepr("data", 12, "pa"))) + val batch_100 = List.fill(100)(AtomicWrite(PersistentRepr("data", 12, "pa"))) + val batch_200 = List.fill(200)(AtomicWrite(PersistentRepr("data", 12, "pa"))) @Setup(Level.Trial) @nowarn("msg=deprecated") diff --git a/bench-jmh/src/main/scala/org/apache/pekko/remote/artery/CodecBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/remote/artery/CodecBenchmark.scala index a1cb3a85619..bb2639d7377 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/remote/artery/CodecBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/remote/artery/CodecBenchmark.scala @@ -202,9 +202,8 @@ class CodecBenchmark { } @Setup(Level.Iteration) - def setupIteration(): Unit = { + def setupIteration(): Unit = System.gc() - } @TearDown(Level.Iteration) def tearDownIteration(): Unit = {} @@ -321,11 +320,10 @@ object CodecBenchmark { val length = Metadata.length val metaLength = buffer.getInt @tailrec - def compare(pos: Int): Boolean = { + def compare(pos: Int): Boolean = if (pos == length) true else if (Metadata(pos) == buffer.get()) compare(pos + 1) else false - } if (metaLength != length || !compare(0)) throw new IOException(s"DummyInstrument deserialization error. Expected ${Metadata.toString}") } diff --git a/bench-jmh/src/main/scala/org/apache/pekko/remote/artery/SendQueueBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/remote/artery/SendQueueBenchmark.scala index 9bf95b8350a..25148002948 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/remote/artery/SendQueueBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/remote/artery/SendQueueBenchmark.scala @@ -45,15 +45,13 @@ class SendQueueBenchmark { implicit val system: ActorSystem = ActorSystem("SendQueueBenchmark", config) @Setup - def setup(): Unit = { + def setup(): Unit = // eager init of materializer SystemMaterializer(system).materializer - } @TearDown - def shutdown(): Unit = { + def shutdown(): Unit = Await.result(system.terminate(), 5.seconds) - } @Benchmark @OperationsPerInvocation(100000) diff --git a/bench-jmh/src/main/scala/org/apache/pekko/remote/artery/compress/SerializationFormatCacheBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/remote/artery/compress/SerializationFormatCacheBenchmark.scala index 15ce77c23a9..0e83c8dc2ac 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/remote/artery/compress/SerializationFormatCacheBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/remote/artery/compress/SerializationFormatCacheBenchmark.scala @@ -86,18 +86,16 @@ class SerializationFormatCacheBenchmark { // new empty cache instance each iteration to have more control over cached contents @Setup(Level.Iteration) - def perRunSetup(): Unit = { + def perRunSetup(): Unit = cache = new SerializationFormatCache - } @TearDown - def shutdown(): Unit = { + def shutdown(): Unit = system.terminate() - } @Benchmark @OperationsPerInvocation(2000) - def useCache(blackhole: Blackhole): Unit = { + def useCache(blackhole: Blackhole): Unit = // serialization requires this Serialization.withTransportInformation(system.asInstanceOf[ExtendedActorSystem]) { () => var i: Int = 0 @@ -109,6 +107,5 @@ class SerializationFormatCacheBenchmark { i += 1 } } - } } diff --git a/bench-jmh/src/main/scala/org/apache/pekko/serialization/jackson/JacksonSerializationBench.scala b/bench-jmh/src/main/scala/org/apache/pekko/serialization/jackson/JacksonSerializationBench.scala index 939cbad12c3..34cb7fbe340 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/serialization/jackson/JacksonSerializationBench.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/serialization/jackson/JacksonSerializationBench.scala @@ -232,13 +232,12 @@ class JacksonSerializationBench { } @TearDown(Level.Trial) - def tearDownTrial(): Unit = { + def tearDownTrial(): Unit = Await.result(system.terminate(), 5.seconds) - } private var size = 0L - private def serializeDeserialize[T <: AnyRef](msg: T): T = { + private def serializeDeserialize[T <: AnyRef](msg: T): T = serialization.findSerializerFor(msg) match { case serializer: SerializerWithStringManifest => val blob = serializer.toBinary(msg) @@ -257,41 +256,32 @@ class JacksonSerializationBench { serializer.fromBinary(blob, None).asInstanceOf[T] } - } - @Benchmark - def small(): Small = { + def small(): Small = serializeDeserialize(smallMsg1) - } @Benchmark - def medium(): Medium = { + def medium(): Medium = serializeDeserialize(mediumMsg1) - } @Benchmark - def large(): Large = { + def large(): Large = serializeDeserialize(largeMsg) - } @Benchmark - def jSmall(): JSmall = { + def jSmall(): JSmall = serializeDeserialize(jSmallMsg1) - } @Benchmark - def jMedium(): JMedium = { + def jMedium(): JMedium = serializeDeserialize(jMediumMsg1) - } @Benchmark - def jLarge(): JLarge = { + def jLarge(): JLarge = serializeDeserialize(jLargeMsg) - } @Benchmark - def timeMessage(): TimeMessage = { + def timeMessage(): TimeMessage = serializeDeserialize(timeMsg) - } } diff --git a/bench-jmh/src/main/scala/org/apache/pekko/stream/AskBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/stream/AskBenchmark.scala index 0b007953238..53c0107133e 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/stream/AskBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/stream/AskBenchmark.scala @@ -81,9 +81,8 @@ class AskBenchmark { } @TearDown - def shutdown(): Unit = { + def shutdown(): Unit = Await.result(system.terminate(), 5.seconds) - } @Benchmark @OperationsPerInvocation(OperationsPerInvocation) @@ -95,11 +94,10 @@ class AskBenchmark { awaitLatch(latch) } - private def awaitLatch(latch: CountDownLatch): Unit = { + private def awaitLatch(latch: CountDownLatch): Unit = if (!latch.await(30, TimeUnit.SECONDS)) { StreamTestKit.printDebugDump(SystemMaterializer(system).materializer.supervisor) throw new RuntimeException("Latch didn't complete in time") } - } } diff --git a/bench-jmh/src/main/scala/org/apache/pekko/stream/CollectBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/stream/CollectBenchmark.scala index 4cc2113b64a..d789a69364d 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/stream/CollectBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/stream/CollectBenchmark.scala @@ -54,9 +54,8 @@ class CollectBenchmark { private implicit val system: ActorSystem = ActorSystem("CollectBenchmark", config) @TearDown - def shutdown(): Unit = { + def shutdown(): Unit = Await.result(system.terminate(), 5.seconds) - } private val newCollect = Source .repeat(1) @@ -85,13 +84,13 @@ class CollectBenchmark { @nowarn("msg=Any") override def onPush(): Unit = - try { + try pf.applyOrElse(grab(in), NotApplied) match { case NotApplied => pull(in) case result: Out @unchecked => push(out, result) case _ => throw new RuntimeException() } - } catch { + catch { case NonFatal(ex) => decider(ex) match { case Supervision.Stop => failStage(ex) diff --git a/bench-jmh/src/main/scala/org/apache/pekko/stream/EmptySourceBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/stream/EmptySourceBenchmark.scala index 4de17fbf734..922b868305f 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/stream/EmptySourceBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/stream/EmptySourceBenchmark.scala @@ -31,9 +31,8 @@ class EmptySourceBenchmark { implicit val system: ActorSystem = ActorSystem("EmptySourceBenchmark") @TearDown - def shutdown(): Unit = { + def shutdown(): Unit = Await.result(system.terminate(), 5.seconds) - } val setup = Source.empty[String].toMat(Sink.ignore)(Keep.right) diff --git a/bench-jmh/src/main/scala/org/apache/pekko/stream/FlatMapConcatBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/stream/FlatMapConcatBenchmark.scala index a1f22186b3f..b5f72aace3a 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/stream/FlatMapConcatBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/stream/FlatMapConcatBenchmark.scala @@ -62,9 +62,8 @@ class FlatMapConcatBenchmark { } @TearDown - def shutdown(): Unit = { + def shutdown(): Unit = Await.result(system.terminate(), 5.seconds) - } @Benchmark @OperationsPerInvocation(OperationsPerInvocation) @@ -108,12 +107,11 @@ class FlatMapConcatBenchmark { awaitLatch(latch) } - private def awaitLatch(latch: CountDownLatch): Unit = { + private def awaitLatch(latch: CountDownLatch): Unit = if (!latch.await(30, TimeUnit.SECONDS)) { implicit val ec = system.dispatcher StreamTestKit.printDebugDump(SystemMaterializer(system).materializer.supervisor) throw new RuntimeException("Latch didn't complete in time") } - } } diff --git a/bench-jmh/src/main/scala/org/apache/pekko/stream/FlatMapMergeBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/stream/FlatMapMergeBenchmark.scala index 074bad5a02b..1e9f50d7ca0 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/stream/FlatMapMergeBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/stream/FlatMapMergeBenchmark.scala @@ -58,13 +58,11 @@ class FlatMapMergeBenchmark { } @TearDown - def shutdown(): Unit = { + def shutdown(): Unit = Await.result(system.terminate(), 5.seconds) - } @Benchmark @OperationsPerInvocation(100000) // Note: needs to match NumberOfElements. - def flat_map_merge_100k_elements(): Unit = { + def flat_map_merge_100k_elements(): Unit = Await.result(graph.run(), Duration.Inf) - } } diff --git a/bench-jmh/src/main/scala/org/apache/pekko/stream/FlowMapBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/stream/FlowMapBenchmark.scala index 5ab9a14c9f8..3d8ac58fc07 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/stream/FlowMapBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/stream/FlowMapBenchmark.scala @@ -91,9 +91,8 @@ class FlowMapBenchmark { } @TearDown - def shutdown(): Unit = { + def shutdown(): Unit = Await.result(system.terminate(), 5.seconds) - } @Benchmark @OperationsPerInvocation(100000) diff --git a/bench-jmh/src/main/scala/org/apache/pekko/stream/FramingBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/stream/FramingBenchmark.scala index 269b120dbec..9e5f47c6434 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/stream/FramingBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/stream/FramingBenchmark.scala @@ -86,9 +86,8 @@ class FramingBenchmark { } @TearDown - def shutdown(): Unit = { + def shutdown(): Unit = Await.result(system.terminate(), 5.seconds) - } @Benchmark @OperationsPerInvocation(100000) diff --git a/bench-jmh/src/main/scala/org/apache/pekko/stream/FusedGraphsBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/stream/FusedGraphsBenchmark.scala index 1b0dd9d0bd7..28141fa6844 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/stream/FusedGraphsBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/stream/FusedGraphsBenchmark.scala @@ -47,12 +47,11 @@ class TestSource(elems: Array[MutableElement]) extends GraphStage[SourceShape[Mu new GraphStageLogic(shape) with OutHandler { private[this] var left = FusedGraphsBenchmark.ElementCount - 1 - override def onPull(): Unit = { + override def onPull(): Unit = if (left >= 0) { push(out, elems(left)) left -= 1 } else completeStage() - } setHandler(out, this) } @@ -135,9 +134,8 @@ class FusedGraphsBenchmark { val testSource = Source.fromGraph(new TestSource(testElements)) val testSink = Sink.fromGraph(new JitSafeCompletionLatch) - def fuse(r: RunnableGraph[CountDownLatch]): RunnableGraph[CountDownLatch] = { + def fuse(r: RunnableGraph[CountDownLatch]): RunnableGraph[CountDownLatch] = RunnableGraph.fromGraph(r) - } val identityStage = new IdentityStage @@ -179,7 +177,7 @@ class FusedGraphsBenchmark { .take(ElementCount) .map(addFunc) .map(addFunc) - .fold(new MutableElement(0))((acc, x) => { acc.value += x.value; acc }) + .fold(new MutableElement(0)) { (acc, x) => acc.value += x.value; acc } .toMat(testSink)(Keep.right)) singleBuffer = fuse(testSource.buffer(10, OverflowStrategy.backpressure).toMat(testSink)(Keep.right)) @@ -302,8 +300,7 @@ class FusedGraphsBenchmark { } @TearDown - def shutdown(): Unit = { + def shutdown(): Unit = Await.result(system.terminate(), 5.seconds) - } } diff --git a/bench-jmh/src/main/scala/org/apache/pekko/stream/InterpreterBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/stream/InterpreterBenchmark.scala index 2f66fcd84ba..857cbe4f0b2 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/stream/InterpreterBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/stream/InterpreterBenchmark.scala @@ -38,7 +38,7 @@ class InterpreterBenchmark { @Benchmark @OperationsPerInvocation(100000) - def graph_interpreter_100k_elements(): Unit = { + def graph_interpreter_100k_elements(): Unit = new GraphInterpreterSpecKit { new TestSetup { val identities = Vector.fill(numberOfIds)(GraphStages.identity[Int]) @@ -48,16 +48,14 @@ class InterpreterBenchmark { val b = builder(identities: _*).connect(source, identities.head.in).connect(identities.last.out, sink) // FIXME: This should not be here, this is pure setup overhead - for (i <- 0 until identities.size - 1) { + for (i <- 0 until identities.size - 1) b.connect(identities(i).out, identities(i + 1).in) - } b.init() sink.requestOne() interpreter.execute(Int.MaxValue) } } - } } object InterpreterBenchmark { @@ -70,14 +68,13 @@ object InterpreterBenchmark { setHandler( out, new OutHandler { - override def onPull(): Unit = { + override def onPull(): Unit = if (idx < data.size) { push(out, data(idx)) idx += 1 } else { completeStage() } - } override def onDownstreamFinish(cause: Throwable): Unit = cancelStage(cause) }) } diff --git a/bench-jmh/src/main/scala/org/apache/pekko/stream/InvokeWithFeedbackBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/stream/InvokeWithFeedbackBenchmark.scala index 17c30e5f948..843721af623 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/stream/InvokeWithFeedbackBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/stream/InvokeWithFeedbackBenchmark.scala @@ -51,13 +51,12 @@ class InvokeWithFeedbackBenchmark { @OperationsPerInvocation(100000) @Benchmark - def pass_through_100k_elements(): Unit = { + def pass_through_100k_elements(): Unit = (0 to 100000).foreach { n => val f = sinkQueue.pull() Await.result(sourceQueue.offer(n), waitForResult) Await.result(f, waitForResult) } - } @TearDown def tearDown(): Unit = { diff --git a/bench-jmh/src/main/scala/org/apache/pekko/stream/LazyFutureSourceBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/stream/LazyFutureSourceBenchmark.scala index 390dfa3bca5..672939d8048 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/stream/LazyFutureSourceBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/stream/LazyFutureSourceBenchmark.scala @@ -53,9 +53,8 @@ class LazyFutureSourceBenchmark { implicit val system: ActorSystem = ActorSystem("LazyFutureSourceBenchmark", config) @TearDown - def shutdown(): Unit = { + def shutdown(): Unit = Await.result(system.terminate(), 5.seconds) - } private val newLazyFutureSource = Source.lazyFuture(() => Future.successful("")).toMat(Sink.ignore)(Keep.right) diff --git a/bench-jmh/src/main/scala/org/apache/pekko/stream/MapAsyncBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/stream/MapAsyncBenchmark.scala index 88f59d606d6..aaa344ead7f 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/stream/MapAsyncBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/stream/MapAsyncBenchmark.scala @@ -69,9 +69,8 @@ class MapAsyncBenchmark { } @TearDown - def shutdown(): Unit = { + def shutdown(): Unit = Await.result(system.terminate(), 5.seconds) - } @Benchmark @OperationsPerInvocation(OperationsPerInvocation) @@ -97,11 +96,10 @@ class MapAsyncBenchmark { awaitLatch(latch) } - private def awaitLatch(latch: CountDownLatch): Unit = { + private def awaitLatch(latch: CountDownLatch): Unit = if (!latch.await(30, TimeUnit.SECONDS)) { StreamTestKit.printDebugDump(SystemMaterializer(system).materializer.supervisor) throw new RuntimeException("Latch didn't complete in time") } - } } diff --git a/bench-jmh/src/main/scala/org/apache/pekko/stream/MaterializationBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/stream/MaterializationBenchmark.scala index c1fd4307104..bf2a42dd3fb 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/stream/MaterializationBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/stream/MaterializationBenchmark.scala @@ -31,9 +31,8 @@ object MaterializationBenchmark { val flowWithMapBuilder = (numOfOperators: Int) => { var source = Source.single(()) - for (_ <- 1 to numOfOperators) { + for (_ <- 1 to numOfOperators) source = source.map(identity) - } source.to(Sink.ignore) } @@ -61,9 +60,8 @@ object MaterializationBenchmark { val broadcast = b.add(Broadcast[Unit](numOfJunctions)) val merge = b.add(Merge[Unit](numOfJunctions)) - for (_ <- 0 until numOfJunctions) { + for (_ <- 0 until numOfJunctions) broadcast ~> merge - } Source.single(()) ~> broadcast merge ~> Sink.ignore @@ -90,9 +88,8 @@ object MaterializationBenchmark { val subFlow = { var flow = Flow[Unit] - for (_ <- 1 to numOfOperators) { + for (_ <- 1 to numOfOperators) flow = flow.map(identity) - } flow } @@ -128,9 +125,8 @@ class MaterializationBenchmark { } @TearDown - def shutdown(): Unit = { + def shutdown(): Unit = Await.result(system.terminate(), 5.seconds) - } @Benchmark def flow_with_map(): NotUsed = flowWithMap.run() diff --git a/bench-jmh/src/main/scala/org/apache/pekko/stream/PartitionHubBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/stream/PartitionHubBenchmark.scala index 40d25b51cc4..b51aab91485 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/stream/PartitionHubBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/stream/PartitionHubBenchmark.scala @@ -69,9 +69,8 @@ class PartitionHubBenchmark { } @TearDown - def shutdown(): Unit = { + def shutdown(): Unit = Await.result(system.terminate(), 5.seconds) - } @Benchmark @OperationsPerInvocation(OperationsPerInvocation) diff --git a/bench-jmh/src/main/scala/org/apache/pekko/stream/SourceRefBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/stream/SourceRefBenchmark.scala index 87d69bce58c..afbf4129ad7 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/stream/SourceRefBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/stream/SourceRefBenchmark.scala @@ -56,14 +56,12 @@ class SourceRefBenchmark { // var initialInputBufferSize = 0 @Setup(Level.Invocation) - def setup(): Unit = { + def setup(): Unit = sourceRef = Source.fromGraph(new BenchTestSource(100000)).runWith(StreamRefs.sourceRef()) - } @TearDown - def shutdown(): Unit = { + def shutdown(): Unit = Await.result(system.terminate(), 5.seconds) - } @Benchmark @OperationsPerInvocation(100000) diff --git a/bench-jmh/src/main/scala/org/apache/pekko/stream/ZipWithIndexBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/stream/ZipWithIndexBenchmark.scala index 061c9759983..e19c370ae9b 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/stream/ZipWithIndexBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/stream/ZipWithIndexBenchmark.scala @@ -55,9 +55,8 @@ class ZipWithIndexBenchmark { private implicit val system: ActorSystem = ActorSystem("ZipWithIndexBenchmark", config) @TearDown - def shutdown(): Unit = { + def shutdown(): Unit = Await.result(system.terminate(), 5.seconds) - } private val newZipWithIndex = Source.repeat(1) .take(OperationsPerInvocation) diff --git a/bench-jmh/src/main/scala/org/apache/pekko/stream/impl/OutputStreamSourceStageBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/stream/impl/OutputStreamSourceStageBenchmark.scala index 4b06c731d79..b1d5efad1b9 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/stream/impl/OutputStreamSourceStageBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/stream/impl/OutputStreamSourceStageBenchmark.scala @@ -57,8 +57,7 @@ class OutputStreamSourceStageBenchmark { } @TearDown - def shutdown(): Unit = { + def shutdown(): Unit = Await.result(system.terminate(), 5.seconds) - } } diff --git a/bench-jmh/src/main/scala/org/apache/pekko/stream/io/FileSourcesBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/stream/io/FileSourcesBenchmark.scala index 3f558f044c7..6ea925fc01f 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/stream/io/FileSourcesBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/stream/io/FileSourcesBenchmark.scala @@ -74,14 +74,12 @@ class FileSourcesBenchmark { } @TearDown - def teardown(): Unit = { + def teardown(): Unit = Files.delete(file) - } @TearDown - def shutdown(): Unit = { + def shutdown(): Unit = Await.result(system.terminate(), Duration.Inf) - } @Benchmark def fileChannel(): Unit = { diff --git a/bench-jmh/src/main/scala/org/apache/pekko/stream/io/FileSourcesScaleBenchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/stream/io/FileSourcesScaleBenchmark.scala index e007ed22b49..3552a77d9e2 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/stream/io/FileSourcesScaleBenchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/stream/io/FileSourcesScaleBenchmark.scala @@ -50,7 +50,7 @@ class FileSourcesScaleBenchmark { val FILES_NUMBER = 40 val files: Seq[Path] = { val line = ByteString("x" * 2048 + "\n") - (1 to FILES_NUMBER).map(i => { + (1 to FILES_NUMBER).map { i => val f = Files.createTempFile(getClass.getName, s"$i.bench.tmp") val ft = Source @@ -59,7 +59,7 @@ class FileSourcesScaleBenchmark { .runWith(FileIO.toPath(f)) Await.result(ft, 300.seconds) f - }) + } } @Param(Array("2048")) @@ -68,19 +68,16 @@ class FileSourcesScaleBenchmark { var fileChannelSource: Seq[Source[ByteString, Future[IOResult]]] = _ @Setup - def setup(): Unit = { + def setup(): Unit = fileChannelSource = files.map(FileIO.fromPath(_, bufSize)) - } @TearDown - def teardown(): Unit = { + def teardown(): Unit = files.foreach(Files.delete) - } @TearDown - def shutdown(): Unit = { + def shutdown(): Unit = Await.result(system.terminate(), Duration.Inf) - } @Benchmark def flatMapMerge(): Unit = { diff --git a/bench-jmh/src/main/scala/org/apache/pekko/util/ArrayCopyOf_Benchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/util/ArrayCopyOf_Benchmark.scala index af2467a588c..626bcc5cbf9 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/util/ArrayCopyOf_Benchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/util/ArrayCopyOf_Benchmark.scala @@ -35,9 +35,8 @@ class ArrayCopyOf_Benchmark { */ @Setup - def setup(): Unit = { + def setup(): Unit = bs = Array.fill[Byte](1024 * kb)(1) - } @Benchmark def systemArrayCopy(): Unit = { diff --git a/bench-jmh/src/main/scala/org/apache/pekko/util/ByteString_asInputStream_Benchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/util/ByteString_asInputStream_Benchmark.scala index 36fb2b9e2d5..bdf84b39db3 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/util/ByteString_asInputStream_Benchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/util/ByteString_asInputStream_Benchmark.scala @@ -60,30 +60,25 @@ class ByteString_asInputStream_Benchmark { val bytes = Array.ofDim[Byte](1024 * kb) bs = ByteString(bytes) composed = ByteString.empty - for (_ <- 0 to 100) { + for (_ <- 0 to 100) composed = composed ++ bs - } } @Benchmark - def single_bs_bytes_to_input_stream(blackhole: Blackhole): Unit = { + def single_bs_bytes_to_input_stream(blackhole: Blackhole): Unit = blackhole.consume(countBytes(new ByteArrayInputStream(bs.toArray))) - } @Benchmark - def composed_bs_bytes_to_input_stream(blackhole: Blackhole): Unit = { + def composed_bs_bytes_to_input_stream(blackhole: Blackhole): Unit = blackhole.consume(countBytes(new ByteArrayInputStream(composed.toArray))) - } @Benchmark - def single_bs_as_input_stream(blackhole: Blackhole): Unit = { + def single_bs_as_input_stream(blackhole: Blackhole): Unit = blackhole.consume(countBytes(bs.asInputStream)) - } @Benchmark - def composed_bs_as_input_stream(blackhole: Blackhole): Unit = { + def composed_bs_as_input_stream(blackhole: Blackhole): Unit = blackhole.consume(countBytes(composed.asInputStream)) - } private def countBytes(stream: InputStream): Int = { val buffer = new Array[Byte](1024) diff --git a/bench-jmh/src/main/scala/org/apache/pekko/util/ByteString_grouped_Benchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/util/ByteString_grouped_Benchmark.scala index 75f64e635e0..418d0a58ef7 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/util/ByteString_grouped_Benchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/util/ByteString_grouped_Benchmark.scala @@ -34,7 +34,6 @@ class ByteString_grouped_Benchmark { */ @Benchmark - def grouped(bh: Blackhole): Unit = { + def grouped(bh: Blackhole): Unit = bh.consume(bsLarge.grouped(1000).foreach(bh.consume)) - } } diff --git a/bench-jmh/src/main/scala/org/apache/pekko/util/ByteString_take_Benchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/util/ByteString_take_Benchmark.scala index 31603c603ef..d9477388e30 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/util/ByteString_take_Benchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/util/ByteString_take_Benchmark.scala @@ -60,27 +60,22 @@ class ByteString_take_Benchmark { */ @Benchmark - def bss_negative(): ByteString = { + def bss_negative(): ByteString = bss.take(n_neg) - } @Benchmark - def bss_greater_or_eq_to_len(): ByteString = { + def bss_greater_or_eq_to_len(): ByteString = bss.take(n_greater_or_eq_to_len) - } @Benchmark - def bss_avg(): ByteString = { + def bss_avg(): ByteString = bss.take(n_avg) - } @Benchmark - def bss_best(): ByteString = { + def bss_best(): ByteString = bss.take(n_best) - } @Benchmark - def bss_worst(): ByteString = { + def bss_worst(): ByteString = bss.take(n_worst) - } } diff --git a/bench-jmh/src/main/scala/org/apache/pekko/util/ByteString_toArray_Benchmark.scala b/bench-jmh/src/main/scala/org/apache/pekko/util/ByteString_toArray_Benchmark.scala index 83c93078611..8cb9d4d4ff4 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/util/ByteString_toArray_Benchmark.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/util/ByteString_toArray_Benchmark.scala @@ -64,19 +64,16 @@ class ByteString_toArray_Benchmark { val bytes = Array.ofDim[Byte](1024 * kb) bs = ByteString(bytes) composed = ByteString.empty - for (_ <- 0 to 100) { + for (_ <- 0 to 100) composed = composed ++ bs - } } @Benchmark - def single_bs_to_array(blackhole: Blackhole): Unit = { + def single_bs_to_array(blackhole: Blackhole): Unit = blackhole.consume(bs.toArray[Byte]) - } @Benchmark - def composed_bs_to_array(blackhole: Blackhole): Unit = { + def composed_bs_to_array(blackhole: Blackhole): Unit = blackhole.consume(composed.toArray[Byte]) - } } diff --git a/bench-jmh/src/main/scala/org/apache/pekko/util/ImmutableIntMapBench.scala b/bench-jmh/src/main/scala/org/apache/pekko/util/ImmutableIntMapBench.scala index 6e385202fe3..2e5f3be3bfd 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/util/ImmutableIntMapBench.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/util/ImmutableIntMapBench.scala @@ -53,12 +53,11 @@ class ImmutableIntMapBench { if (n <= to) updateIfAbsent(n + by, by, to, in.updateIfAbsent(n, n)) else in - @tailrec private[this] final def getKey(iterations: Int, key: Int, from: ImmutableIntMap): ImmutableIntMap = { + @tailrec private[this] final def getKey(iterations: Int, key: Int, from: ImmutableIntMap): ImmutableIntMap = if (iterations > 0 && key != Int.MinValue) { val k = from.get(key) getKey(iterations - 1, k, from) } else from - } val odd1000 = (0 to 1000).iterator.filter(_ % 2 == 1).foldLeft(ImmutableIntMap.empty)((l, i) => l.updated(i, i)) diff --git a/bench-jmh/src/main/scala/org/apache/pekko/util/LruBoundedCacheBench.scala b/bench-jmh/src/main/scala/org/apache/pekko/util/LruBoundedCacheBench.scala index 8b5f339b30f..b209d994da6 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/util/LruBoundedCacheBench.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/util/LruBoundedCacheBench.scala @@ -70,9 +70,8 @@ class LruBoundedCacheBench { } @Benchmark - def addOne_lruCache(): String = { + def addOne_lruCache(): String = lruCache.getOrCompute(toAdd) - } @Benchmark def addOne_hashMap(): String = { diff --git a/bench-jmh/src/main/scala/org/apache/pekko/util/StackBench.scala b/bench-jmh/src/main/scala/org/apache/pekko/util/StackBench.scala index 3120124ac5d..e67d43e3a3b 100644 --- a/bench-jmh/src/main/scala/org/apache/pekko/util/StackBench.scala +++ b/bench-jmh/src/main/scala/org/apache/pekko/util/StackBench.scala @@ -27,13 +27,11 @@ class StackBench { } @Benchmark - def currentThread(): Array[StackTraceElement] = { + def currentThread(): Array[StackTraceElement] = Thread.currentThread().getStackTrace - } @Benchmark - def securityManager(): Array[Class[_]] = { + def securityManager(): Array[Class[_]] = (new CustomSecurtyManager).getTrace - } } diff --git a/build.sbt b/build.sbt index d93f55ee67c..4389e6890b2 100644 --- a/build.sbt +++ b/build.sbt @@ -376,7 +376,7 @@ lazy val protobufV3 = pekkoModule("protobuf-v3") val uberJar = (Compile / assembly).value ReproducibleBuildsPlugin.postProcessJar(uberJar) } - } else Def.task { file } + } else Def.task(file) } tracker(() => uberJarLocation) }.value, diff --git a/cluster-metrics/src/main/scala/org/apache/pekko/cluster/metrics/ClusterMetricsCollector.scala b/cluster-metrics/src/main/scala/org/apache/pekko/cluster/metrics/ClusterMetricsCollector.scala index 3a98e9d0566..ac80e6bc8a5 100644 --- a/cluster-metrics/src/main/scala/org/apache/pekko/cluster/metrics/ClusterMetricsCollector.scala +++ b/cluster-metrics/src/main/scala/org/apache/pekko/cluster/metrics/ClusterMetricsCollector.scala @@ -71,14 +71,13 @@ private[metrics] class ClusterMetricsSupervisor extends Actor with ActorLogging def collectorName = s"collector-$collectorInstance" - override def preStart() = { + override def preStart() = if (CollectorEnabled) { self ! CollectionStartMessage } else { log.warning( s"Metrics collection is disabled in configuration. Use subtypes of ${classOf[CollectionControlMessage].getName} to manage collection at runtime.") } - } override def receive = { case CollectionStartMessage => diff --git a/cluster-metrics/src/main/scala/org/apache/pekko/cluster/metrics/ClusterMetricsExtension.scala b/cluster-metrics/src/main/scala/org/apache/pekko/cluster/metrics/ClusterMetricsExtension.scala index 785266d0bae..8849005d863 100644 --- a/cluster-metrics/src/main/scala/org/apache/pekko/cluster/metrics/ClusterMetricsExtension.scala +++ b/cluster-metrics/src/main/scala/org/apache/pekko/cluster/metrics/ClusterMetricsExtension.scala @@ -80,17 +80,15 @@ class ClusterMetricsExtension(system: ExtendedActorSystem) extends Extension { * Subscribe user metrics listener actor unto [[ClusterMetricsEvent]] * events published by extension on the system event bus. */ - def subscribe(metricsListener: ActorRef): Unit = { + def subscribe(metricsListener: ActorRef): Unit = system.eventStream.subscribe(metricsListener, classOf[ClusterMetricsEvent]) - } /** * Unsubscribe user metrics listener actor from [[ClusterMetricsEvent]] * events published by extension on the system event bus. */ - def unsubscribe(metricsListenter: ActorRef): Unit = { + def unsubscribe(metricsListenter: ActorRef): Unit = system.eventStream.unsubscribe(metricsListenter, classOf[ClusterMetricsEvent]) - } } diff --git a/cluster-metrics/src/main/scala/org/apache/pekko/cluster/metrics/ClusterMetricsRouting.scala b/cluster-metrics/src/main/scala/org/apache/pekko/cluster/metrics/ClusterMetricsRouting.scala index d40b9871db0..477328c781f 100644 --- a/cluster-metrics/src/main/scala/org/apache/pekko/cluster/metrics/ClusterMetricsRouting.scala +++ b/cluster-metrics/src/main/scala/org/apache/pekko/cluster/metrics/ClusterMetricsRouting.scala @@ -275,7 +275,7 @@ case object HeapMetricsSelector extends CapacityMetricsSelector { */ def getInstance = this - override def capacity(nodeMetrics: Set[NodeMetrics]): Map[Address, Double] = { + override def capacity(nodeMetrics: Set[NodeMetrics]): Map[Address, Double] = nodeMetrics.collect { case HeapMemory(address, _, used, committed, max) => val capacity = max match { @@ -284,7 +284,6 @@ case object HeapMetricsSelector extends CapacityMetricsSelector { } (address, capacity) }.toMap - } } /** @@ -316,7 +315,7 @@ case object CpuMetricsSelector extends CapacityMetricsSelector { val factor = 0.3 require(0.0 <= factor, s"factor must be non negative: $factor") - override def capacity(nodeMetrics: Set[NodeMetrics]): Map[Address, Double] = { + override def capacity(nodeMetrics: Set[NodeMetrics]): Map[Address, Double] = nodeMetrics.collect { case Cpu(address, _, _, Some(cpuCombined), Some(cpuStolen), _) => // Arbitrary load rating function which skews in favor of stolen time. @@ -324,7 +323,6 @@ case object CpuMetricsSelector extends CapacityMetricsSelector { val capacity = if (load >= 1.0) 0.0 else 1.0 - load (address, capacity) }.toMap - } } /** @@ -343,13 +341,12 @@ case object SystemLoadAverageMetricsSelector extends CapacityMetricsSelector { */ def getInstance = this - override def capacity(nodeMetrics: Set[NodeMetrics]): Map[Address, Double] = { + override def capacity(nodeMetrics: Set[NodeMetrics]): Map[Address, Double] = nodeMetrics.collect { case Cpu(address, _, Some(systemLoadAverage), _, _, processors) => val capacity = 1.0 - math.min(1.0, systemLoadAverage / processors) (address, capacity) }.toMap - } } /** @@ -462,7 +459,7 @@ abstract class CapacityMetricsSelector extends MetricsSelector { * nodes gets weights proportional to their capacity compared to * the node with lowest capacity. */ - def weights(capacity: Map[Address, Double]): Map[Address, Int] = { + def weights(capacity: Map[Address, Double]): Map[Address, Int] = if (capacity.isEmpty) Map.empty[Address, Int] else { val (_, min) = capacity.minBy { case (_, c) => c } @@ -470,7 +467,6 @@ abstract class CapacityMetricsSelector extends MetricsSelector { val divisor = math.max(0.01, min) capacity.map { case (address, c) => address -> math.round(c / divisor).toInt } } - } /** * The weights per address, based on the capacity produced by @@ -538,7 +534,7 @@ private[metrics] class WeightedRoutees( * Converts the result of Arrays.binarySearch into a index in the buckets array * see documentation of Arrays.binarySearch for what it returns */ - private def idx(i: Int): Int = { + private def idx(i: Int): Int = if (i >= 0) i // exact match else { val j = math.abs(i + 1) @@ -546,7 +542,6 @@ private[metrics] class WeightedRoutees( throw new IndexOutOfBoundsException("Requested index [%s] is > max index [%s]".format(i, buckets.length)) else j } - } } /** diff --git a/cluster-metrics/src/main/scala/org/apache/pekko/cluster/metrics/ClusterMetricsSettings.scala b/cluster-metrics/src/main/scala/org/apache/pekko/cluster/metrics/ClusterMetricsSettings.scala index 53fbd8f1906..4521d93e67c 100644 --- a/cluster-metrics/src/main/scala/org/apache/pekko/cluster/metrics/ClusterMetricsSettings.scala +++ b/cluster-metrics/src/main/scala/org/apache/pekko/cluster/metrics/ClusterMetricsSettings.scala @@ -43,14 +43,14 @@ case class ClusterMetricsSettings(config: Config) { val CollectorEnabled: Boolean = cc.getBoolean("collector.enabled") val CollectorProvider: String = cc.getString("collector.provider") val CollectorFallback: Boolean = cc.getBoolean("collector.fallback") - val CollectorSampleInterval: FiniteDuration = { + val CollectorSampleInterval: FiniteDuration = cc.getMillisDuration("collector.sample-interval") - }.requiring(_ > Duration.Zero, "collector.sample-interval must be > 0") - val CollectorGossipInterval: FiniteDuration = { + .requiring(_ > Duration.Zero, "collector.sample-interval must be > 0") + val CollectorGossipInterval: FiniteDuration = cc.getMillisDuration("collector.gossip-interval") - }.requiring(_ > Duration.Zero, "collector.gossip-interval must be > 0") - val CollectorMovingAverageHalfLife: FiniteDuration = { + .requiring(_ > Duration.Zero, "collector.gossip-interval must be > 0") + val CollectorMovingAverageHalfLife: FiniteDuration = cc.getMillisDuration("collector.moving-average-half-life") - }.requiring(_ > Duration.Zero, "collector.moving-average-half-life must be > 0") + .requiring(_ > Duration.Zero, "collector.moving-average-half-life must be > 0") } diff --git a/cluster-metrics/src/main/scala/org/apache/pekko/cluster/metrics/Metric.scala b/cluster-metrics/src/main/scala/org/apache/pekko/cluster/metrics/Metric.scala index cc4846cef46..900c51a9b34 100644 --- a/cluster-metrics/src/main/scala/org/apache/pekko/cluster/metrics/Metric.scala +++ b/cluster-metrics/src/main/scala/org/apache/pekko/cluster/metrics/Metric.scala @@ -139,7 +139,7 @@ object StandardMetrics { * necessary heap metrics. * @return if possible a tuple matching the HeapMemory constructor parameters */ - def unapply(nodeMetrics: NodeMetrics): Option[(Address, Long, Long, Long, Option[Long])] = { + def unapply(nodeMetrics: NodeMetrics): Option[(Address, Long, Long, Long, Option[Long])] = for { used <- nodeMetrics.metric(HeapMemoryUsed) committed <- nodeMetrics.metric(HeapMemoryCommitted) @@ -149,7 +149,6 @@ object StandardMetrics { used.smoothValue.longValue, committed.smoothValue.longValue, nodeMetrics.metric(HeapMemoryMax).map(_.smoothValue.longValue)) - } } @@ -191,7 +190,7 @@ object StandardMetrics { * @return if possible a tuple matching the Cpu constructor parameters */ def unapply( - nodeMetrics: NodeMetrics): Option[(Address, Long, Option[Double], Option[Double], Option[Double], Int)] = { + nodeMetrics: NodeMetrics): Option[(Address, Long, Option[Double], Option[Double], Option[Double], Int)] = for { processors <- nodeMetrics.metric(Processors) } yield ( @@ -201,7 +200,6 @@ object StandardMetrics { nodeMetrics.metric(CpuCombined).map(_.smoothValue), nodeMetrics.metric(CpuStolen).map(_.smoothValue), processors.value.intValue) - } } @@ -320,9 +318,7 @@ final case class NodeMetrics(address: Address, timestamp: Long, metrics: Set[Met latest <- latestNode.metrics current <- currentNode.metrics if latest.sameAs(current) - } yield { - current :+ latest - } + } yield current :+ latest // Append metrics missing from either latest or current. // Equality is based on the [[Metric.name]] val merged = @@ -376,7 +372,7 @@ private[metrics] final case class MetricsGossip(nodes: Set[NodeMetrics]) { * Only the nodes that are in the `includeNodes` Set. */ def filter(includeNodes: Set[Address]): MetricsGossip = - copy(nodes = nodes.filter { includeNodes contains _.address }) + copy(nodes = nodes.filter(includeNodes contains _.address)) /** * Adds new remote [[NodeMetrics]] and merges existing from a remote gossip. diff --git a/cluster-metrics/src/main/scala/org/apache/pekko/cluster/metrics/Provision.scala b/cluster-metrics/src/main/scala/org/apache/pekko/cluster/metrics/Provision.scala index 7af138a738f..402032d9e85 100644 --- a/cluster-metrics/src/main/scala/org/apache/pekko/cluster/metrics/Provision.scala +++ b/cluster-metrics/src/main/scala/org/apache/pekko/cluster/metrics/Provision.scala @@ -63,16 +63,15 @@ trait SigarProvider { } /** Extract and load sigar native library. */ - def provisionSigarLibrary(): Unit = { + def provisionSigarLibrary(): Unit = SigarProvisioner.provision(new File(extractFolder)) - } /** * Create sigar instance with 2-phase sigar library loading. * 1) Assume that library is already provisioned. * 2) Attempt to provision library via sigar-loader. */ - def createSigarInstance: SigarProxy = { + def createSigarInstance: SigarProxy = TryNative { verifiedSigarInstance }.orElse(TryNative { @@ -82,7 +81,6 @@ trait SigarProvider { .recover { case e: Throwable => throw new RuntimeException("Failed to load sigar:", e) } get - } } @@ -93,9 +91,8 @@ object SigarProvider { * * Note: `SigarProxy` is not `Sigar` during tests. */ - def close(sigar: SigarProxy) = { + def close(sigar: SigarProxy) = if (sigar.isInstanceOf[Sigar]) sigar.asInstanceOf[Sigar].close() - } } /** diff --git a/cluster-metrics/src/multi-jvm/scala/org/apache/pekko/cluster/metrics/ClusterMetricsRoutingSpec.scala b/cluster-metrics/src/multi-jvm/scala/org/apache/pekko/cluster/metrics/ClusterMetricsRoutingSpec.scala index 62da2a0f6dd..d69d4e172ab 100644 --- a/cluster-metrics/src/multi-jvm/scala/org/apache/pekko/cluster/metrics/ClusterMetricsRoutingSpec.scala +++ b/cluster-metrics/src/multi-jvm/scala/org/apache/pekko/cluster/metrics/ClusterMetricsRoutingSpec.scala @@ -166,7 +166,7 @@ abstract class AdaptiveLoadBalancingRouterSpec .props(Props[Echo]()), name) // it may take some time until router receives cluster member events - awaitAssert { currentRoutees(router).size should ===(roles.size) } + awaitAssert(currentRoutees(router).size should ===(roles.size)) val routees = currentRoutees(router) routees.collect { case ActorRefRoutee(ref) => fullAddress(ref) }.toSet should ===(roles.map(address).toSet) router @@ -247,7 +247,7 @@ abstract class AdaptiveLoadBalancingRouterSpec runOn(node1) { val router3 = system.actorOf(FromConfig.props(Props[Memory]()), "router3") // it may take some time until router receives cluster member events - awaitAssert { currentRoutees(router3).size should ===(9) } + awaitAssert(currentRoutees(router3).size should ===(9)) val routees = currentRoutees(router3) routees.collect { case ActorRefRoutee(ref) => fullAddress(ref) }.toSet should ===(Set(address(node1))) } @@ -259,7 +259,7 @@ abstract class AdaptiveLoadBalancingRouterSpec runOn(node1) { val router4 = system.actorOf(FromConfig.props(Props[Memory]()), "router4") // it may take some time until router receives cluster member events - awaitAssert { currentRoutees(router4).size should ===(6) } + awaitAssert(currentRoutees(router4).size should ===(6)) val routees = currentRoutees(router4) routees.collect { case ActorRefRoutee(ref) => fullAddress(ref) }.toSet should ===( Set(address(node1), address(node2), address(node3))) diff --git a/cluster-metrics/src/test/scala/org/apache/pekko/cluster/metrics/ClusterMetricsExtensionSpec.scala b/cluster-metrics/src/test/scala/org/apache/pekko/cluster/metrics/ClusterMetricsExtensionSpec.scala index f9532a2e7a7..8e94d275edd 100644 --- a/cluster-metrics/src/test/scala/org/apache/pekko/cluster/metrics/ClusterMetricsExtensionSpec.scala +++ b/cluster-metrics/src/test/scala/org/apache/pekko/cluster/metrics/ClusterMetricsExtensionSpec.scala @@ -67,7 +67,7 @@ class ClusterMetricsExtensionSpec "verify sigar mock data matches expected ewma data" in { - val history = metricsView.metricsHistory.reverse.map { _.head } + val history = metricsView.metricsHistory.reverse.map(_.head) val expected = List( (0.700, 0.000, 0.000), (0.700, 0.018, 0.007), (0.700, 0.051, 0.020), (0.700, 0.096, 0.038), diff --git a/cluster-metrics/src/test/scala/org/apache/pekko/cluster/metrics/MetricSpec.scala b/cluster-metrics/src/test/scala/org/apache/pekko/cluster/metrics/MetricSpec.scala index d0ddc108ef3..1d643fecb2d 100644 --- a/cluster-metrics/src/test/scala/org/apache/pekko/cluster/metrics/MetricSpec.scala +++ b/cluster-metrics/src/test/scala/org/apache/pekko/cluster/metrics/MetricSpec.scala @@ -155,10 +155,9 @@ class MetricsGossipSpec * sometimes Sigar will not be able to return a valid value (NaN and such) so must ensure they * have the same Metric types */ - def newSample(previousSample: Set[Metric]): Set[Metric] = { + def newSample(previousSample: Set[Metric]): Set[Metric] = // Metric.equals is based on name equality collector.sample().metrics.filter(previousSample.contains) ++ previousSample - } "A MetricsGossip" must { "add new NodeMetrics" in { @@ -257,7 +256,7 @@ class MetricValuesSpec extends PekkoSpec(MetricsConfig.defaultEnabled) with Metr val node1 = NodeMetrics(Address("pekko", "sys", "a", 7357), 1, collector.sample().metrics) val node2 = NodeMetrics(Address("pekko", "sys", "a", 7358), 1, collector.sample().metrics) - val nodes: Seq[NodeMetrics] = { + val nodes: Seq[NodeMetrics] = (1 to 100).foldLeft(List(node1, node2)) { (nodes, _) => nodes.map { n => n.copy( @@ -270,7 +269,6 @@ class MetricValuesSpec extends PekkoSpec(MetricsConfig.defaultEnabled) with Metr })) } } - } "NodeMetrics.MetricValues" must { "extract expected metrics for load balancing" in { diff --git a/cluster-metrics/src/test/scala/org/apache/pekko/cluster/metrics/TestUtil.scala b/cluster-metrics/src/test/scala/org/apache/pekko/cluster/metrics/TestUtil.scala index 8b195040662..eefa64dec41 100644 --- a/cluster-metrics/src/test/scala/org/apache/pekko/cluster/metrics/TestUtil.scala +++ b/cluster-metrics/src/test/scala/org/apache/pekko/cluster/metrics/TestUtil.scala @@ -80,7 +80,7 @@ case class MockitoSigarProvider( /** Generate monotonic array from 0 to value. */ def increase(value: Double): Array[Double] = { val delta = value / steps - (0 to steps).map { _ * delta } toArray + (0 to steps).map(_ * delta) toArray } /** Sigar mock instance. */ @@ -115,10 +115,10 @@ trait MetricsCollectorFactory { this: PekkoSpec => def selfAddress = extendedActorSystem.provider.rootPath.address def createMetricsCollector: MetricsCollector = - try { + try new SigarMetricsCollector(selfAddress, defaultDecayFactor, new Sigar()) - // new SigarMetricsCollector(selfAddress, defaultDecayFactor, SimpleSigarProvider().createSigarInstance) - } catch { + // new SigarMetricsCollector(selfAddress, defaultDecayFactor, SimpleSigarProvider().createSigarInstance) + catch { case e: Throwable => log.warning("Sigar failed to load. Using JMX. Reason: " + e.toString) new JmxMetricsCollector(selfAddress, defaultDecayFactor) @@ -218,7 +218,7 @@ class ClusterMetricsView(system: ExtendedActorSystem) extends Closeable { private var collectedMetricsList: List[Set[NodeMetrics]] = List.empty /** Create actor that subscribes to the cluster eventBus to update current read view state. */ - private val eventBusListener: ActorRef = { + private val eventBusListener: ActorRef = system.systemActorOf( Props(new Actor with ActorLogging with RequiresMessageQueue[UnboundedMessageQueueSemantics] { override def preStart(): Unit = extension.subscribe(self) @@ -232,7 +232,6 @@ class ClusterMetricsView(system: ExtendedActorSystem) extends Closeable { } }).withDispatcher(Dispatchers.DefaultDispatcherId).withDeploy(Deploy.local), name = "metrics-event-bus-listener") - } /** Current cluster metrics. */ def clusterMetrics: Set[NodeMetrics] = currentMetricsSet diff --git a/cluster-metrics/src/test/scala/org/apache/pekko/cluster/metrics/WeightedRouteesSpec.scala b/cluster-metrics/src/test/scala/org/apache/pekko/cluster/metrics/WeightedRouteesSpec.scala index 9f3d37071e8..6a9d70bdc9c 100644 --- a/cluster-metrics/src/test/scala/org/apache/pekko/cluster/metrics/WeightedRouteesSpec.scala +++ b/cluster-metrics/src/test/scala/org/apache/pekko/cluster/metrics/WeightedRouteesSpec.scala @@ -53,8 +53,8 @@ class WeightedRouteesSpec extends PekkoSpec(ConfigFactory.parseString(""" val weighted = new WeightedRoutees(routees, a1, weights) weighted(1) should ===(routeeA) - (2 to 4).foreach { weighted(_) should ===(routeeB) } - (5 to 14).foreach { weighted(_) should ===(routeeC) } + (2 to 4).foreach(weighted(_) should ===(routeeB)) + (5 to 14).foreach(weighted(_) should ===(routeeC)) weighted.total should ===(14) } @@ -89,9 +89,9 @@ class WeightedRouteesSpec extends PekkoSpec(ConfigFactory.parseString(""" val weighted = new WeightedRoutees(routees, a1, weights) weighted(1) should ===(routeeA) - (2 to 8).foreach { weighted(_) should ===(routeeB) } + (2 to 8).foreach(weighted(_) should ===(routeeB)) // undefined, uses the mean of the weights, i.e. 4 - (9 to 12).foreach { weighted(_) should ===(routeeC) } + (9 to 12).foreach(weighted(_) should ===(routeeC)) weighted.total should ===(12) } @@ -100,15 +100,15 @@ class WeightedRouteesSpec extends PekkoSpec(ConfigFactory.parseString(""" val routees2 = Vector(testActorRoutee, routeeB, routeeC) val weighted = new WeightedRoutees(routees2, a1, weights) - (1 to 2).foreach { weighted(_) should ===(testActorRoutee) } - (3 to weighted.total).foreach { weighted(_) should not be testActorRoutee } + (1 to 2).foreach(weighted(_) should ===(testActorRoutee)) + (3 to weighted.total).foreach(weighted(_) should not be testActorRoutee) } "not allocate ref with weight zero" in { val weights = Map(a1 -> 0, b1 -> 2, c1 -> 10) val weighted = new WeightedRoutees(routees, a1, weights) - (1 to weighted.total).foreach { weighted(_) should not be routeeA } + (1 to weighted.total).foreach(weighted(_) should not be routeeA) } } diff --git a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/ClusterShardingSettings.scala b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/ClusterShardingSettings.scala index 5b8d0b08406..8b6bb0fb193 100644 --- a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/ClusterShardingSettings.scala +++ b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/ClusterShardingSettings.scala @@ -50,7 +50,7 @@ object ClusterShardingSettings { /** INTERNAL API: Intended only for internal use, it is not recommended to keep converting between the setting types */ private[pekko] def fromClassicSettings( numberOfShards: Int, - classicSettings: ClassicShardingSettings): ClusterShardingSettings = { + classicSettings: ClassicShardingSettings): ClusterShardingSettings = new ClusterShardingSettings( numberOfShards, role = classicSettings.role, @@ -71,10 +71,9 @@ object ClusterShardingSettings { classicSettings.coordinatorSingletonSettings.handOverRetryInterval, classicSettings.coordinatorSingletonSettings.leaseSettings), leaseSettings = classicSettings.leaseSettings) - } /** INTERNAL API: Intended only for internal use, it is not recommended to keep converting between the setting types */ - private[pekko] def toClassicSettings(settings: ClusterShardingSettings): ClassicShardingSettings = { + private[pekko] def toClassicSettings(settings: ClusterShardingSettings): ClassicShardingSettings = new ClassicShardingSettings( role = settings.role, rememberEntities = settings.rememberEntities, @@ -118,8 +117,6 @@ object ClusterShardingSettings { settings.coordinatorSingletonSettings.leaseSettings), leaseSettings = settings.leaseSettings) - } - private def option(role: String): Option[String] = if (role == "" || role == null) None else Option(role) diff --git a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/ReplicatedEntityProvider.scala b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/ReplicatedEntityProvider.scala index cf99fc3ce7d..c54bfc1af6a 100644 --- a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/ReplicatedEntityProvider.scala +++ b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/ReplicatedEntityProvider.scala @@ -60,7 +60,7 @@ object ReplicatedEntityProvider { * @tparam M The type of messages the replicated entity accepts */ def apply[M: ClassTag](typeName: String, allReplicaIds: Set[ReplicaId])( - settingsPerReplicaFactory: (EntityTypeKey[M], ReplicaId) => ReplicatedEntity[M]): ReplicatedEntityProvider[M] = { + settingsPerReplicaFactory: (EntityTypeKey[M], ReplicaId) => ReplicatedEntity[M]): ReplicatedEntityProvider[M] = new ReplicatedEntityProvider( allReplicaIds.map { replicaId => if (typeName.contains(Separator)) @@ -70,7 +70,6 @@ object ReplicatedEntityProvider { val typeKey = EntityTypeKey[M](s"$typeName$Separator${replicaId.id}") (settingsPerReplicaFactory(typeKey, replicaId), typeName) }.toVector, directReplication = true) - } /** * Scala API @@ -79,14 +78,13 @@ object ReplicatedEntityProvider { * ClusterSharding. A replica will be run per data center. */ def perDataCenter[M: ClassTag, E](typeName: String, allReplicaIds: Set[ReplicaId])( - create: ReplicationId => Behavior[M]): ReplicatedEntityProvider[M] = { + create: ReplicationId => Behavior[M]): ReplicatedEntityProvider[M] = apply(typeName, allReplicaIds) { (typeKey, replicaId) => ReplicatedEntity(replicaId, Entity(typeKey) { entityContext => create(ReplicationId.fromString(entityContext.entityId)) }.withDataCenter(replicaId.id)) } - } /** * Scala API @@ -96,14 +94,13 @@ object ReplicatedEntityProvider { * entity will run on each role. */ def perRole[M: ClassTag, E](typeName: String, allReplicaIds: Set[ReplicaId])( - create: ReplicationId => Behavior[M]): ReplicatedEntityProvider[M] = { + create: ReplicationId => Behavior[M]): ReplicatedEntityProvider[M] = apply(typeName, allReplicaIds) { (typeKey, replicaId) => ReplicatedEntity(replicaId, Entity(typeKey) { entityContext => create(ReplicationId.fromString(entityContext.entityId)) }.withRole(replicaId.id)) } - } /** * Java API diff --git a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/ShardedDaemonProcessSettings.scala b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/ShardedDaemonProcessSettings.scala index 40f97680bbf..fa40ae60057 100644 --- a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/ShardedDaemonProcessSettings.scala +++ b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/ShardedDaemonProcessSettings.scala @@ -27,9 +27,8 @@ import pekko.util.JavaDurationConverters._ object ShardedDaemonProcessSettings { /** Scala API: Create default settings for system */ - def apply(system: ActorSystem[_]): ShardedDaemonProcessSettings = { + def apply(system: ActorSystem[_]): ShardedDaemonProcessSettings = fromConfig(system.settings.config.getConfig("pekko.cluster.sharded-daemon-process")) - } /** Java API: Create default settings for system */ def create(system: ActorSystem[_]): ShardedDaemonProcessSettings = diff --git a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/delivery/ShardingConsumerController.scala b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/delivery/ShardingConsumerController.scala index 1e58675bc00..1e04f7ad407 100644 --- a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/delivery/ShardingConsumerController.scala +++ b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/delivery/ShardingConsumerController.scala @@ -62,9 +62,8 @@ object ShardingConsumerController { * Scala API: Factory method from Config corresponding to * `pekko.reliable-delivery.sharding.consumer-controller`. */ - def apply(config: Config): Settings = { + def apply(config: Config): Settings = new Settings(bufferSize = config.getInt("buffer-size"), ConsumerController.Settings(config)) - } /** * Java API: Factory method from config `pekko.reliable-delivery.sharding.consumer-controller` @@ -106,21 +105,19 @@ object ShardingConsumerController { * the lifecycle and message delivery to the destination consumer actor. */ def apply[A, B](consumerBehavior: ActorRef[ConsumerController.Start[A]] => Behavior[B]) - : Behavior[ConsumerController.SequencedMessage[A]] = { + : Behavior[ConsumerController.SequencedMessage[A]] = Behaviors.setup { context => ShardingConsumerControllerImpl(consumerBehavior, Settings(context.system)) } - } /** * The `Behavior` of the entity that is to be initialized in `ClusterSharding`. It will manage * the lifecycle and message delivery to the destination consumer actor. */ def withSettings[A, B](settings: Settings)(consumerBehavior: ActorRef[ConsumerController.Start[A]] => Behavior[B]) - : Behavior[ConsumerController.SequencedMessage[A]] = { + : Behavior[ConsumerController.SequencedMessage[A]] = // can't overload apply, loosing type inference ShardingConsumerControllerImpl(consumerBehavior, settings) - } /** * Java API: The `Behavior` of the entity that is to be initialized in `ClusterSharding`. It will manage diff --git a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/delivery/ShardingProducerController.scala b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/delivery/ShardingProducerController.scala index b38d954277d..916d7c8c52b 100644 --- a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/delivery/ShardingProducerController.scala +++ b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/delivery/ShardingProducerController.scala @@ -182,14 +182,13 @@ object ShardingProducerController { * Scala API: Factory method from Config corresponding to * `pekko.reliable-delivery.sharding.producer-controller`. */ - def apply(config: Config): Settings = { + def apply(config: Config): Settings = new Settings( bufferSize = config.getInt("buffer-size"), config.getDuration("internal-ask-timeout").asScala, config.getDuration("cleanup-unused-after").asScala, config.getDuration("resend-first-unconfirmed-idle-timeout").asScala, ProducerController.Settings(config)) - } /** * Java API: Factory method from config `pekko.reliable-delivery.sharding.producer-controller` @@ -274,19 +273,17 @@ object ShardingProducerController { def apply[A: ClassTag]( producerId: String, region: ActorRef[ShardingEnvelope[ConsumerController.SequencedMessage[A]]], - durableQueueBehavior: Option[Behavior[DurableProducerQueue.Command[A]]]): Behavior[Command[A]] = { + durableQueueBehavior: Option[Behavior[DurableProducerQueue.Command[A]]]): Behavior[Command[A]] = Behaviors.setup { context => ShardingProducerControllerImpl(producerId, region, durableQueueBehavior, Settings(context.system)) } - } def apply[A: ClassTag]( producerId: String, region: ActorRef[ShardingEnvelope[ConsumerController.SequencedMessage[A]]], durableQueueBehavior: Option[Behavior[DurableProducerQueue.Command[A]]], - settings: Settings): Behavior[Command[A]] = { + settings: Settings): Behavior[Command[A]] = ShardingProducerControllerImpl(producerId, region, durableQueueBehavior, settings) - } /** * Java API @@ -295,9 +292,8 @@ object ShardingProducerController { messageClass: Class[A], producerId: String, region: ActorRef[ShardingEnvelope[ConsumerController.SequencedMessage[A]]], - durableQueueBehavior: Optional[Behavior[DurableProducerQueue.Command[A]]]): Behavior[Command[A]] = { + durableQueueBehavior: Optional[Behavior[DurableProducerQueue.Command[A]]]): Behavior[Command[A]] = apply(producerId, region, durableQueueBehavior.toScala)(ClassTag(messageClass)) - } /** * Java API @@ -307,9 +303,8 @@ object ShardingProducerController { producerId: String, region: ActorRef[ShardingEnvelope[ConsumerController.SequencedMessage[A]]], durableQueueBehavior: Optional[Behavior[DurableProducerQueue.Command[A]]], - settings: Settings): Behavior[Command[A]] = { + settings: Settings): Behavior[Command[A]] = apply(producerId, region, durableQueueBehavior.toScala, settings)(ClassTag(messageClass)) - } // TODO maybe there is a need for variant taking message extractor instead of ShardingEnvelope } diff --git a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/delivery/internal/ShardingConsumerControllerImpl.scala b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/delivery/internal/ShardingConsumerControllerImpl.scala index adf156f918a..fdda130aed3 100644 --- a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/delivery/internal/ShardingConsumerControllerImpl.scala +++ b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/delivery/internal/ShardingConsumerControllerImpl.scala @@ -32,7 +32,7 @@ import pekko.cluster.sharding.typed.delivery.ShardingConsumerController @InternalApi private[pekko] object ShardingConsumerControllerImpl { def apply[A, B]( consumerBehavior: ActorRef[ConsumerController.Start[A]] => Behavior[B], - settings: ShardingConsumerController.Settings): Behavior[ConsumerController.SequencedMessage[A]] = { + settings: ShardingConsumerController.Settings): Behavior[ConsumerController.SequencedMessage[A]] = Behaviors .setup[ConsumerController.Command[A]] { context => context.setLoggerName("org.apache.pekko.cluster.sharding.typed.delivery.ShardingConsumerController") @@ -41,12 +41,11 @@ import pekko.cluster.sharding.typed.delivery.ShardingConsumerController waitForStart(context, settings, consumer) } .narrow - } private def waitForStart[A]( context: ActorContext[ConsumerController.Command[A]], settings: ShardingConsumerController.Settings, - consumer: ActorRef[_]): Behavior[ConsumerController.Command[A]] = { + consumer: ActorRef[_]): Behavior[ConsumerController.Command[A]] = Behaviors.withStash(settings.bufferSize) { stashBuffer => Behaviors .receiveMessage[ConsumerController.Command[A]] { @@ -66,7 +65,6 @@ import pekko.cluster.sharding.typed.delivery.ShardingConsumerController Behaviors.stopped } } - } } @@ -80,12 +78,11 @@ private class ShardingConsumerControllerImpl[A]( producerControllers: Map[ActorRef[ProducerControllerImpl.InternalCommand], String], // producerId -> ConsumerController consumerControllers: Map[String, ActorRef[ConsumerController.Command[A]]]) - : Behavior[ConsumerController.Command[A]] = { - + : Behavior[ConsumerController.Command[A]] = Behaviors .receiveMessagePartial[ConsumerController.Command[A]] { case seqMsg: ConsumerController.SequencedMessage[A @unchecked] => - def updatedProducerControllers(): Map[ActorRef[ProducerControllerImpl.InternalCommand], String] = { + def updatedProducerControllers(): Map[ActorRef[ProducerControllerImpl.InternalCommand], String] = producerControllers.get(seqMsg.producerController) match { case Some(_) => producerControllers @@ -93,7 +90,6 @@ private class ShardingConsumerControllerImpl[A]( context.watch(seqMsg.producerController) producerControllers.updated(seqMsg.producerController, seqMsg.producerId) } - } consumerControllers.get(seqMsg.producerId) match { case Some(c) => @@ -138,6 +134,4 @@ private class ShardingConsumerControllerImpl[A]( } } - } - } diff --git a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/delivery/internal/ShardingProducerControllerImpl.scala b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/delivery/internal/ShardingProducerControllerImpl.scala index d30b1df016d..73237113ff3 100644 --- a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/delivery/internal/ShardingProducerControllerImpl.scala +++ b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/delivery/internal/ShardingProducerControllerImpl.scala @@ -102,16 +102,15 @@ import pekko.util.Timeout // replyAfterStore is used when durableQueue is enabled, otherwise they are tracked in OutState replyAfterStore: Map[TotalSeqNr, ActorRef[Done]]) { - def bufferSize: Long = { + def bufferSize: Long = out.valuesIterator.foldLeft(0L) { case (acc, outState) => acc + outState.buffered.size } - } } def apply[A: ClassTag]( producerId: String, region: ActorRef[ShardingEnvelope[ConsumerController.SequencedMessage[A]]], durableQueueBehavior: Option[Behavior[DurableProducerQueue.Command[A]]], - settings: ShardingProducerController.Settings): Behavior[Command[A]] = { + settings: ShardingProducerController.Settings): Behavior[Command[A]] = Behaviors .withStash[InternalCommand](settings.bufferSize) { stashBuffer => Behaviors.setup[InternalCommand] { context => @@ -133,11 +132,9 @@ import pekko.util.Timeout } } .narrow - } - private def createInitialState[A](hasDurableQueue: Boolean) = { + private def createInitialState[A](hasDurableQueue: Boolean) = if (hasDurableQueue) None else Some(DurableProducerQueue.State.empty[A]) - } private def waitingForStart[A: ClassTag]( producerId: String, @@ -149,7 +146,7 @@ import pekko.util.Timeout initialState: Option[DurableProducerQueue.State[A]], settings: ShardingProducerController.Settings): Behavior[InternalCommand] = { - def becomeActive(p: ActorRef[RequestNext[A]], s: DurableProducerQueue.State[A]): Behavior[InternalCommand] = { + def becomeActive(p: ActorRef[RequestNext[A]], s: DurableProducerQueue.State[A]): Behavior[InternalCommand] = Behaviors.withTimers { timers => timers.startTimerWithFixedDelay(CleanupUnused, settings.cleanupUnusedAfter / 2) timers.startTimerWithFixedDelay(ResendFirstUnconfirmed, settings.resendFirstUnconfirmedIdleTimeout / 2) @@ -173,7 +170,6 @@ import pekko.util.Timeout } } } - } Behaviors.receiveMessage { case start: Start[A] @unchecked => @@ -236,23 +232,20 @@ import pekko.util.Timeout } } - private def checkStashFull[A](stashBuffer: StashBuffer[InternalCommand]): Unit = { + private def checkStashFull[A](stashBuffer: StashBuffer[InternalCommand]): Unit = if (stashBuffer.isFull) throw new IllegalArgumentException(s"Buffer is full, size [${stashBuffer.size}].") - } private def askLoadState[A]( context: ActorContext[InternalCommand], durableQueueBehavior: Option[Behavior[DurableProducerQueue.Command[A]]], - settings: ShardingProducerController.Settings): Option[ActorRef[DurableProducerQueue.Command[A]]] = { - + settings: ShardingProducerController.Settings): Option[ActorRef[DurableProducerQueue.Command[A]]] = durableQueueBehavior.map { b => val ref = context.spawn(b, "durable", DispatcherSelector.sameAsParent()) context.watchWith(ref, DurableQueueTerminated) askLoadState(context, Some(ref), settings, attempt = 1) ref } - } private def askLoadState[A]( context: ActorContext[InternalCommand], @@ -399,7 +392,7 @@ private class ShardingProducerControllerImpl[A: ClassTag]( onMessage(entityId, msg, replyTo = None, seqNr, newReplyAfterStore) } - def receiveStoreMessageSentFailed(f: StoreMessageSentFailed[A]): Behavior[InternalCommand] = { + def receiveStoreMessageSentFailed(f: StoreMessageSentFailed[A]): Behavior[InternalCommand] = if (f.attempt >= producerControllerSettings.durableQueueRetryAttempts) { val errorMessage = s"StoreMessageSentFailed seqNr [${f.messageSent.seqNr}] failed after [${f.attempt}] attempts, giving up." @@ -411,9 +404,8 @@ private class ShardingProducerControllerImpl[A: ClassTag]( storeMessageSent(f.messageSent, attempt = f.attempt + 1) Behaviors.same } - } - def receiveAck(ack: Ack): Behavior[InternalCommand] = { + def receiveAck(ack: Ack): Behavior[InternalCommand] = s.out.get(ack.outKey) match { case Some(outState) => if (traceEnabled) @@ -428,7 +420,6 @@ private class ShardingProducerControllerImpl[A: ClassTag]( // obsolete Ack, ConsumerController already deregistered Behaviors.unhandled } - } def receiveWrappedRequestNext(w: WrappedRequestNext[A]): Behavior[InternalCommand] = { val next = w.next diff --git a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/internal/ClusterShardingImpl.scala b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/internal/ClusterShardingImpl.scala index 026611912c7..879b5c2e10d 100644 --- a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/internal/ClusterShardingImpl.scala +++ b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/internal/ClusterShardingImpl.scala @@ -60,17 +60,16 @@ import pekko.util.JavaDurationConverters._ */ @InternalApi private[pekko] class ExtractorAdapter[E, M](delegate: ShardingMessageExtractor[E, M]) extends ShardingMessageExtractor[Any, M] { - override def entityId(message: Any): String = { + override def entityId(message: Any): String = message match { case ShardingEnvelope(entityId, _) => entityId // also covers ClassicStartEntity in ShardingEnvelope case ClassicStartEntity(entityId) => entityId case msg => delegate.entityId(msg.asInstanceOf[E]) } - } override def shardId(entityId: String): String = delegate.shardId(entityId) - override def unwrapMessage(message: Any): M = { + override def unwrapMessage(message: Any): M = message match { case ShardingEnvelope(_, msg: M @unchecked) => // also covers ClassicStartEntity in ShardingEnvelope @@ -81,7 +80,6 @@ import pekko.util.JavaDurationConverters._ case msg => delegate.unwrapMessage(msg.asInstanceOf[E]) } - } override def toString: String = delegate.toString } @@ -192,19 +190,17 @@ import pekko.util.JavaDurationConverters._ shardCommandActors.computeIfAbsent( typeKey.name, new java.util.function.Function[String, ActorRef[scaladsl.ClusterSharding.ShardCommand]] { - override def apply(t: String): ActorRef[scaladsl.ClusterSharding.ShardCommand] = { + override def apply(t: String): ActorRef[scaladsl.ClusterSharding.ShardCommand] = system.systemActorOf( ShardCommandActor.behavior(stopMessage.getOrElse(PoisonPill)), URLEncoder.encode(typeKey.name, ByteString.UTF_8) + "ShardCommandDelegator") - } }) - def poisonPillInterceptor(behv: Behavior[M]): Behavior[M] = { + def poisonPillInterceptor(behv: Behavior[M]): Behavior[M] = stopMessage match { case Some(_) => behv case None => Behaviors.intercept(() => new PoisonPillInterceptor[M])(behv) } - } val classicEntityPropsFactory: String => pekko.actor.Props = { entityId => val behv = behavior(new EntityContext(typeKey, entityId, shardCommandDelegator)) @@ -247,17 +243,16 @@ import pekko.util.JavaDurationConverters._ ActorRefAdapter(ref) } - override def entityRefFor[M](typeKey: scaladsl.EntityTypeKey[M], entityId: String): scaladsl.EntityRef[M] = { + override def entityRefFor[M](typeKey: scaladsl.EntityTypeKey[M], entityId: String): scaladsl.EntityRef[M] = new EntityRefImpl[M]( classicSharding.shardRegion(typeKey.name), entityId, typeKey.asInstanceOf[EntityTypeKeyImpl[M]]) - } override def entityRefFor[M]( typeKey: scaladsl.EntityTypeKey[M], entityId: String, - dataCenter: DataCenter): scaladsl.EntityRef[M] = { + dataCenter: DataCenter): scaladsl.EntityRef[M] = if (dataCenter == cluster.selfMember.dataCenter) entityRefFor(typeKey, entityId).asInstanceOf[EntityRefImpl[M]].withDataCenter(Some(dataCenter)) else @@ -266,19 +261,17 @@ import pekko.util.JavaDurationConverters._ entityId, typeKey.asInstanceOf[EntityTypeKeyImpl[M]], Some(dataCenter)) - } - override def entityRefFor[M](typeKey: javadsl.EntityTypeKey[M], entityId: String): javadsl.EntityRef[M] = { + override def entityRefFor[M](typeKey: javadsl.EntityTypeKey[M], entityId: String): javadsl.EntityRef[M] = new EntityRefImpl[M]( classicSharding.shardRegion(typeKey.name), entityId, typeKey.asInstanceOf[EntityTypeKeyImpl[M]]) - } override def entityRefFor[M]( typeKey: javadsl.EntityTypeKey[M], entityId: String, - dataCenter: String): javadsl.EntityRef[M] = { + dataCenter: String): javadsl.EntityRef[M] = if (dataCenter == cluster.selfMember.dataCenter) entityRefFor(typeKey, entityId).asInstanceOf[EntityRefImpl[M]].withDataCenter(Some(dataCenter)) else @@ -287,9 +280,8 @@ import pekko.util.JavaDurationConverters._ entityId, typeKey.asInstanceOf[EntityTypeKeyImpl[M]], Some(dataCenter)) - } - override def defaultShardAllocationStrategy(settings: ClusterShardingSettings): ShardAllocationStrategy = { + override def defaultShardAllocationStrategy(settings: ClusterShardingSettings): ShardAllocationStrategy = if (settings.tuningParameters.leastShardAllocationAbsoluteLimit > 0) { // new algorithm val absoluteLimit = settings.tuningParameters.leastShardAllocationAbsoluteLimit @@ -301,7 +293,6 @@ import pekko.util.JavaDurationConverters._ val maxSimultaneousRebalance = settings.tuningParameters.leastShardAllocationMaxSimultaneousRebalance new ShardCoordinator.LeastShardAllocationStrategy(threshold, maxSimultaneousRebalance) } - } override lazy val shardState: ActorRef[ClusterShardingQuery] = system.systemActorOf(ShardingState.behavior(classicSharding), "typedShardState") diff --git a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/internal/JoinConfigCompatCheckerClusterSharding.scala b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/internal/JoinConfigCompatCheckerClusterSharding.scala index 0037bee6abd..aa0c7823698 100644 --- a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/internal/JoinConfigCompatCheckerClusterSharding.scala +++ b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/internal/JoinConfigCompatCheckerClusterSharding.scala @@ -30,10 +30,9 @@ private[pekko] final class JoinConfigCompatCheckerClusterSharding extends JoinCo override def requiredKeys: im.Seq[String] = im.Seq("pekko.cluster.sharding.number-of-shards") - override def check(toCheck: Config, actualConfig: Config): ConfigValidation = { + override def check(toCheck: Config, actualConfig: Config): ConfigValidation = if (toCheck.hasPath(requiredKeys.head)) JoinConfigCompatChecker.fullMatch(requiredKeys, toCheck, actualConfig) else Valid // support for rolling update, property doesn't exist in previous versions - } } diff --git a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/internal/ShardedDaemonProcessImpl.scala b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/internal/ShardedDaemonProcessImpl.scala index 9107e1eede0..e82a84c5c1f 100644 --- a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/internal/ShardedDaemonProcessImpl.scala +++ b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/internal/ShardedDaemonProcessImpl.scala @@ -64,9 +64,8 @@ private[pekko] object ShardedDaemonProcessImpl { context.messageAdapter[SelfUp](_ => StartTick), classOf[SelfUp]) Behaviors.withTimers { timers => - def triggerStartAll(): Unit = { + def triggerStartAll(): Unit = identities.foreach(id => shardingRef ! StartEntity(id)) - } Behaviors.receiveMessage { case StartTick => triggerStartAll() diff --git a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/internal/ShardingState.scala b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/internal/ShardingState.scala index 55df61668fa..68f37007133 100644 --- a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/internal/ShardingState.scala +++ b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/internal/ShardingState.scala @@ -31,16 +31,16 @@ import pekko.cluster.sharding.typed.GetShardRegionState */ @InternalApi private[pekko] object ShardingState { - def behavior(classicSharding: ClusterSharding): Behavior[ClusterShardingQuery] = { + def behavior(classicSharding: ClusterSharding): Behavior[ClusterShardingQuery] = Behaviors .supervise[ClusterShardingQuery] { Behaviors.setup { context => Behaviors.receiveMessage { case GetShardRegionState(key, replyTo) => if (classicSharding.getShardTypeNames.contains(key.name)) { - try { + try classicSharding.shardRegion(key.name).tell(ShardRegion.GetShardRegionState, replyTo.toClassic) - } catch { + catch { case e: IllegalStateException => // classicSharding.shardRegion may throw if not initialized context.log.warn(e.getMessage) @@ -53,11 +53,11 @@ import pekko.cluster.sharding.typed.GetShardRegionState case GetClusterShardingStats(key, timeout, replyTo) => if (classicSharding.getShardTypeNames.contains(key.name)) { - try { + try classicSharding .shardRegion(key.name) .tell(ShardRegion.GetClusterShardingStats(timeout), replyTo.toClassic) - } catch { + catch { case e: IllegalStateException => // classicSharding.shardRegion may throw if not initialized context.log.warn(e.getMessage) @@ -71,6 +71,5 @@ import pekko.cluster.sharding.typed.GetShardRegionState } } .onFailure(SupervisorStrategy.restart) - } } diff --git a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/internal/testkit/TestEntityRefImpl.scala b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/internal/testkit/TestEntityRefImpl.scala index 06d4b36fbaf..a0ae4a9c093 100644 --- a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/internal/testkit/TestEntityRefImpl.scala +++ b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/internal/testkit/TestEntityRefImpl.scala @@ -66,14 +66,12 @@ import pekko.util.Timeout StatusReply.flattenStatusFuture(ask(f)) // impl InternalRecipientRef - override def provider: ActorRefProvider = { + override def provider: ActorRefProvider = probe.asInstanceOf[InternalRecipientRef[_]].provider - } // impl InternalRecipientRef - def isTerminated: Boolean = { + def isTerminated: Boolean = probe.asInstanceOf[InternalRecipientRef[_]].isTerminated - } override def toString: String = s"TestEntityRef($entityId)" diff --git a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/javadsl/ClusterSharding.scala b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/javadsl/ClusterSharding.scala index 450a075e580..55434189e54 100644 --- a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/javadsl/ClusterSharding.scala +++ b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/javadsl/ClusterSharding.scala @@ -240,7 +240,7 @@ object Entity { */ def of[M]( typeKey: EntityTypeKey[M], - createBehavior: JFunction[EntityContext[M], Behavior[M]]): Entity[M, ShardingEnvelope[M]] = { + createBehavior: JFunction[EntityContext[M], Behavior[M]]): Entity[M, ShardingEnvelope[M]] = new Entity( createBehavior, typeKey, @@ -251,7 +251,6 @@ object Entity { Optional.empty(), Optional.empty(), Optional.empty()) - } } @@ -338,7 +337,7 @@ final class Entity[M, E] private ( settings: Optional[ClusterShardingSettings] = settings, allocationStrategy: Optional[ShardAllocationStrategy] = allocationStrategy, role: Optional[String] = role, - dataCenter: Optional[String] = dataCenter): Entity[M, E] = { + dataCenter: Optional[String] = dataCenter): Entity[M, E] = new Entity( createBehavior, typeKey, @@ -349,7 +348,6 @@ final class Entity[M, E] private ( allocationStrategy, role, dataCenter) - } /** * INTERNAL API diff --git a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/scaladsl/ClusterSharding.scala b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/scaladsl/ClusterSharding.scala index ed1908bd7e0..91b29aa4fc1 100644 --- a/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/scaladsl/ClusterSharding.scala +++ b/cluster-sharding-typed/src/main/scala/org/apache/pekko/cluster/sharding/typed/scaladsl/ClusterSharding.scala @@ -331,7 +331,7 @@ final class Entity[M, E] private[pekko] ( settings: Option[ClusterShardingSettings] = settings, allocationStrategy: Option[ShardAllocationStrategy] = allocationStrategy, role: Option[String] = role, - dataCenter: Option[DataCenter] = dataCenter): Entity[M, E] = { + dataCenter: Option[DataCenter] = dataCenter): Entity[M, E] = new Entity( createBehavior, typeKey, @@ -342,7 +342,6 @@ final class Entity[M, E] private[pekko] ( allocationStrategy, role, dataCenter) - } } @@ -382,10 +381,9 @@ object StartEntity { * Returns [[ShardingEnvelope]] which can be sent via Cluster Sharding in order to wake up the * specified (by `entityId`) Sharded Entity, ''without'' delivering a real message to it. */ - def apply[M](entityId: String): ShardingEnvelope[M] = { + def apply[M](entityId: String): ShardingEnvelope[M] = // StartEntity isn't really of type M, but erased and StartEntity is only handled internally, not delivered to the entity new ShardingEnvelope[M](entityId, ClassicStartEntity(entityId).asInstanceOf[M]) - } } /** diff --git a/cluster-sharding-typed/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingRememberEntitiesPerfSpec.scala b/cluster-sharding-typed/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingRememberEntitiesPerfSpec.scala index a3f91af3b8b..620f7b94e68 100644 --- a/cluster-sharding-typed/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingRememberEntitiesPerfSpec.scala +++ b/cluster-sharding-typed/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingRememberEntitiesPerfSpec.scala @@ -106,7 +106,7 @@ abstract class ClusterShardingRememberEntitiesPerfSpec import ClusterShardingRememberEntitiesPerfSpec._ import ClusterShardingRememberEntitiesPerfSpecConfig._ - def startSharding(): Unit = { + def startSharding(): Unit = (1 to NrRegions).foreach { n => startSharding( system, @@ -116,8 +116,6 @@ abstract class ClusterShardingRememberEntitiesPerfSpec extractShardId = LatencyEntity.extractShardId) } - } - var latencyRegions = Vector.empty[ActorRef] val latencyCount = new AtomicInteger(0) @@ -193,9 +191,8 @@ abstract class ClusterShardingRememberEntitiesPerfSpec (1 to numberOfMessages).foreach { n => region ! In(iteration * 100000 + n) } - for (_ <- 1 to numberOfMessages) { + for (_ <- 1 to numberOfMessages) histogram.recordValue(expectMsgType[Out].latency) - } numberOfMessages } } @@ -203,12 +200,10 @@ abstract class ClusterShardingRememberEntitiesPerfSpec "test latency when starting new entity and sending a few messages" in { val numberOfMessages = 800 * NrOfMessagesFactor runBench("start, few messages") { (iteration, region, histogram) => - for (n <- 1 to numberOfMessages / 5; _ <- 1 to 5) { + for (n <- 1 to numberOfMessages / 5; _ <- 1 to 5) region ! In(iteration * 100000 + n) - } - for (_ <- 1 to numberOfMessages) { + for (_ <- 1 to numberOfMessages) histogram.recordValue(expectMsgType[Out].latency) - } numberOfMessages } } @@ -225,15 +220,14 @@ abstract class ClusterShardingRememberEntitiesPerfSpec region ! Stop(id) } } - for (_ <- 1 to numberOfMessages) { - try { + for (_ <- 1 to numberOfMessages) + try histogram.recordValue(expectMsgType[Out].latency) - } catch { + catch { case e: AssertionError => log.error(s"Received ${histogram.getTotalCount} out of $numberOfMessages") throw e } - } awaitAssert({ val probe = TestProbe() @@ -257,15 +251,14 @@ abstract class ClusterShardingRememberEntitiesPerfSpec region ! Stop(id) } } - for (_ <- 1 to numberOfMessages) { - try { + for (_ <- 1 to numberOfMessages) + try histogram.recordValue(expectMsgType[Out].latency) - } catch { + catch { case e: AssertionError => log.error(s"Received ${histogram.getTotalCount} out of $numberOfMessages") throw e } - } numberOfMessages } } @@ -282,14 +275,12 @@ abstract class ClusterShardingRememberEntitiesPerfSpec region ! In(msg) if (n == 10) { - for (_ <- 1 to 10) { + for (_ <- 1 to 10) histogram.recordValue(expectMsgType[Out].latency) - } } } - for (_ <- 1 to numberOfMessages - 10) { + for (_ <- 1 to numberOfMessages - 10) histogram.recordValue(expectMsgType[Out].latency) - } numberOfMessages } } @@ -301,14 +292,12 @@ abstract class ClusterShardingRememberEntitiesPerfSpec region ! In(iteration * 100000 + (n % 10)) // these will go to same 10 started entities if (n == 10) { - for (_ <- 1 to 10) { + for (_ <- 1 to 10) histogram.recordValue(expectMsgType[Out].latency) - } } } - for (_ <- 1 to numberOfMessages - 10) { + for (_ <- 1 to numberOfMessages - 10) histogram.recordValue(expectMsgType[Out].latency) - } numberOfMessages } } diff --git a/cluster-sharding-typed/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/typed/ClusterShardingPreparingForShutdownSpec.scala b/cluster-sharding-typed/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/typed/ClusterShardingPreparingForShutdownSpec.scala index 8cac517f49d..48fef02d1b6 100644 --- a/cluster-sharding-typed/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/typed/ClusterShardingPreparingForShutdownSpec.scala +++ b/cluster-sharding-typed/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/typed/ClusterShardingPreparingForShutdownSpec.scala @@ -100,11 +100,10 @@ class ClusterShardingPreparingForShutdownSpec runOn(second) { cluster.manager ! PrepareForFullClusterShutdown } - awaitAssert({ - withClue("members: " + cluster.state.members) { - cluster.selfMember.status shouldEqual MemberStatus.ReadyForShutdown - cluster.state.members.unsorted.map(_.status) shouldEqual Set(MemberStatus.ReadyForShutdown) - } + awaitAssert( + withClue("members: " + cluster.state.members) { + cluster.selfMember.status shouldEqual MemberStatus.ReadyForShutdown + cluster.state.members.unsorted.map(_.status) shouldEqual Set(MemberStatus.ReadyForShutdown) }, 10.seconds) enterBarrier("preparation-complete") @@ -142,10 +141,9 @@ class ClusterShardingPreparingForShutdownSpec cluster.manager ! Leave(address(first)) cluster.manager ! Leave(address(third)) } - awaitAssert({ - withClue("self member: " + cluster.selfMember) { - cluster.selfMember.status shouldEqual Removed - } + awaitAssert( + withClue("self member: " + cluster.selfMember) { + cluster.selfMember.status shouldEqual Removed }, 15.seconds) enterBarrier("done") } diff --git a/cluster-sharding-typed/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/typed/ClusterShardingStatsSpec.scala b/cluster-sharding-typed/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/typed/ClusterShardingStatsSpec.scala index 28980233f58..87bc5423a0c 100644 --- a/cluster-sharding-typed/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/typed/ClusterShardingStatsSpec.scala +++ b/cluster-sharding-typed/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/typed/ClusterShardingStatsSpec.scala @@ -54,13 +54,12 @@ object Pinger { case class Ping(id: Int, ref: ActorRef[Pong]) extends Command case class Pong(id: Int) extends CborSerializable - def apply(): Behavior[Command] = { + def apply(): Behavior[Command] = Behaviors.receiveMessage[Command] { case Ping(id: Int, ref) => ref ! Pong(id) Behaviors.same } - } } diff --git a/cluster-sharding-typed/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/typed/ReplicatedShardingSpec.scala b/cluster-sharding-typed/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/typed/ReplicatedShardingSpec.scala index 0a670b05aa3..16beb70eeeb 100644 --- a/cluster-sharding-typed/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/typed/ReplicatedShardingSpec.scala +++ b/cluster-sharding-typed/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/typed/ReplicatedShardingSpec.scala @@ -78,7 +78,7 @@ object ReplicatedShardingSpec extends MultiNodeConfig { case class State(all: List[String]) extends CborSerializable - def apply(id: ReplicationId, ctx: ActorContext[Command]): EventSourcedBehavior[Command, String, State] = { + def apply(id: ReplicationId, ctx: ActorContext[Command]): EventSourcedBehavior[Command, String, State] = // Relies on direct replication as there is no proxy query journal ReplicatedEventSourcing.commonJournalConfig(id, AllReplicas, PersistenceTestKitReadJournal.Identifier) { replicationContext => @@ -104,9 +104,8 @@ object ReplicatedShardingSpec extends MultiNodeConfig { state.copy(all = event :: state.all) }).withEventPublishing(true) } - } - def provider(): ReplicatedEntityProvider[Command] = { + def provider(): ReplicatedEntityProvider[Command] = ReplicatedEntityProvider[Command]("TestRES", AllReplicas) { (entityTypeKey, replicaId) => ReplicatedEntity(replicaId, Entity(entityTypeKey) { entityContext => @@ -115,7 +114,6 @@ object ReplicatedShardingSpec extends MultiNodeConfig { } }) }.withDirectReplication(true) // this is required as we don't have a shared read journal - } } } diff --git a/cluster-sharding-typed/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/typed/delivery/DeliveryThroughputSpec.scala b/cluster-sharding-typed/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/typed/delivery/DeliveryThroughputSpec.scala index 2a744558a3f..da3a3aab6e4 100644 --- a/cluster-sharding-typed/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/typed/delivery/DeliveryThroughputSpec.scala +++ b/cluster-sharding-typed/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/typed/delivery/DeliveryThroughputSpec.scala @@ -94,7 +94,7 @@ object DeliveryThroughputSpec extends MultiNodeConfig { private case class WrappedDelivery(d: ConsumerController.Delivery[Command]) extends Command - def apply(consumerController: ActorRef[ConsumerController.Start[Command]]): Behavior[Command] = { + def apply(consumerController: ActorRef[ConsumerController.Start[Command]]): Behavior[Command] = Behaviors.setup { context => val traceEnabled = context.log.isTraceEnabled val deliveryAdapter = @@ -128,7 +128,6 @@ object DeliveryThroughputSpec extends MultiNodeConfig { } - } } object Producer { diff --git a/cluster-sharding-typed/src/test/scala/docs/delivery/PointToPointDocExample.scala b/cluster-sharding-typed/src/test/scala/docs/delivery/PointToPointDocExample.scala index 7553a69d87d..d7ef1ef6535 100644 --- a/cluster-sharding-typed/src/test/scala/docs/delivery/PointToPointDocExample.scala +++ b/cluster-sharding-typed/src/test/scala/docs/delivery/PointToPointDocExample.scala @@ -38,7 +38,7 @@ object PointToPointDocExample { private case class WrappedRequestNext(r: ProducerController.RequestNext[FibonacciConsumer.Command]) extends Command def apply( - producerController: ActorRef[ProducerController.Command[FibonacciConsumer.Command]]): Behavior[Command] = { + producerController: ActorRef[ProducerController.Command[FibonacciConsumer.Command]]): Behavior[Command] = Behaviors.setup { context => val requestNextAdapter = context.messageAdapter[ProducerController.RequestNext[FibonacciConsumer.Command]](WrappedRequestNext(_)) @@ -46,9 +46,8 @@ object PointToPointDocExample { fibonacci(0, 1, 0) } - } - private def fibonacci(n: Long, b: BigInt, a: BigInt): Behavior[Command] = { + private def fibonacci(n: Long, b: BigInt, a: BigInt): Behavior[Command] = Behaviors.receive { case (context, WrappedRequestNext(next)) => context.log.info("Generated fibonacci {}: {}", n, a) @@ -59,7 +58,6 @@ object PointToPointDocExample { else fibonacci(n + 1, a + b, b) } - } } // #producer @@ -74,7 +72,7 @@ object PointToPointDocExample { private case class WrappedDelivery(d: ConsumerController.Delivery[Command]) extends Command def apply( - consumerController: ActorRef[ConsumerController.Command[FibonacciConsumer.Command]]): Behavior[Command] = { + consumerController: ActorRef[ConsumerController.Command[FibonacciConsumer.Command]]): Behavior[Command] = Behaviors.setup { context => val deliveryAdapter = context.messageAdapter[ConsumerController.Delivery[FibonacciConsumer.Command]](WrappedDelivery(_)) @@ -87,12 +85,11 @@ object PointToPointDocExample { Behaviors.same } } - } } // #consumer object Guardian { - def apply(): Behavior[Nothing] = { + def apply(): Behavior[Nothing] = Behaviors.setup[Nothing] { context => // #connect val consumerController = context.spawn(ConsumerController[FibonacciConsumer.Command](), "consumerController") @@ -109,10 +106,8 @@ object PointToPointDocExample { Behaviors.empty } - } } - def main(args: Array[String]): Unit = { + def main(args: Array[String]): Unit = ActorSystem[Nothing](Guardian(), "FibonacciExample") - } } diff --git a/cluster-sharding-typed/src/test/scala/docs/delivery/ShardingDocExample.scala b/cluster-sharding-typed/src/test/scala/docs/delivery/ShardingDocExample.scala index 96a90e0d913..0bde626fde7 100644 --- a/cluster-sharding-typed/src/test/scala/docs/delivery/ShardingDocExample.scala +++ b/cluster-sharding-typed/src/test/scala/docs/delivery/ShardingDocExample.scala @@ -58,11 +58,10 @@ object ShardingDocExample { def apply( id: String, db: DB, - consumerController: ActorRef[ConsumerController.Start[Command]]): Behavior[Command] = { + consumerController: ActorRef[ConsumerController.Start[Command]]): Behavior[Command] = Behaviors.setup[Command] { context => new TodoList(context, id, db).start(consumerController) } - } } @@ -87,7 +86,7 @@ object ShardingDocExample { } } - private def active(state: State): Behavior[Command] = { + private def active(state: State): Behavior[Command] = Behaviors.receiveMessagePartial { case CommandDelivery(AddTask(item), confirmTo) => val newState = state.copy(tasks = state.tasks :+ item) @@ -103,14 +102,12 @@ object ShardingDocExample { case DBError(cause) => throw cause } - } - private def save(newState: State, confirmTo: ActorRef[ConsumerController.Confirmed]): Unit = { + private def save(newState: State, confirmTo: ActorRef[ConsumerController.Confirmed]): Unit = context.pipeToSelf(db.save(id, newState)) { case Success(_) => SaveSuccess(confirmTo) case Failure(cause) => DBError(cause) } - } } // #consumer @@ -133,11 +130,10 @@ object ShardingDocExample { private final case class Confirmed(originalReplyTo: ActorRef[Response]) extends Command private final case class TimedOut(originalReplyTo: ActorRef[Response]) extends Command - def apply(producerController: ActorRef[ShardingProducerController.Command[TodoList.Command]]): Behavior[Command] = { + def apply(producerController: ActorRef[ShardingProducerController.Command[TodoList.Command]]): Behavior[Command] = Behaviors.setup { context => new TodoService(context).start(producerController) } - } } @@ -162,7 +158,7 @@ object ShardingDocExample { } } - private def active(requestNext: ShardingProducerController.RequestNext[TodoList.Command]): Behavior[Command] = { + private def active(requestNext: ShardingProducerController.RequestNext[TodoList.Command]): Behavior[Command] = Behaviors.receiveMessage { case WrappedRequestNext(next) => active(next) @@ -189,12 +185,11 @@ object ShardingDocExample { originalReplyTo ! MaybeAccepted Behaviors.same } - } } // #producer - def illustrateInit(): Unit = { + def illustrateInit(): Unit = Behaviors.setup[Nothing] { context => // #init import org.apache.pekko @@ -223,6 +218,5 @@ object ShardingDocExample { Behaviors.empty } - } } diff --git a/cluster-sharding-typed/src/test/scala/docs/delivery/WorkPullingDocExample.scala b/cluster-sharding-typed/src/test/scala/docs/delivery/WorkPullingDocExample.scala index 75a366656ef..3fbdf05c497 100644 --- a/cluster-sharding-typed/src/test/scala/docs/delivery/WorkPullingDocExample.scala +++ b/cluster-sharding-typed/src/test/scala/docs/delivery/WorkPullingDocExample.scala @@ -44,7 +44,7 @@ object WorkPullingDocExample { val serviceKey = ServiceKey[ConsumerController.Command[ConversionJob]]("ImageConverter") - def apply(): Behavior[Command] = { + def apply(): Behavior[Command] = Behaviors.setup { context => val deliveryAdapter = context.messageAdapter[ConsumerController.Delivery[ConversionJob]](WrappedDelivery(_)) @@ -67,7 +67,6 @@ object WorkPullingDocExample { } } - } } // #consumer @@ -106,7 +105,7 @@ object WorkPullingDocExample { // #ask // #producer - def apply(): Behavior[Command] = { + def apply(): Behavior[Command] = Behaviors.setup { context => val requestNextAdapter = context.messageAdapter[WorkPullingProducerController.RequestNext[ImageConverter.ConversionJob]]( @@ -139,7 +138,6 @@ object WorkPullingDocExample { new ImageWorkManager(context, stashBuffer).waitForNext() } } - } } @@ -149,7 +147,7 @@ object WorkPullingDocExample { import ImageWorkManager._ - private def waitForNext(): Behavior[Command] = { + private def waitForNext(): Behavior[Command] = Behaviors.receiveMessagePartial { case WrappedRequestNext(next) => stashBuffer.unstashAll(active(next)) @@ -165,10 +163,9 @@ object WorkPullingDocExample { // TODO retrieve the stored result and reply Behaviors.same } - } private def active( - next: WorkPullingProducerController.RequestNext[ImageConverter.ConversionJob]): Behavior[Command] = { + next: WorkPullingProducerController.RequestNext[ImageConverter.ConversionJob]): Behavior[Command] = Behaviors.receiveMessagePartial { case Convert(from, to, image) => val resultId = UUID.randomUUID() @@ -180,7 +177,6 @@ object WorkPullingDocExample { case _: WrappedRequestNext => throw new IllegalStateException("Unexpected RequestNext") } - } // #producer object askScope { // #ask @@ -190,7 +186,7 @@ object WorkPullingDocExample { implicit val askTimeout: Timeout = 5.seconds - private def waitForNext(): Behavior[Command] = { + private def waitForNext(): Behavior[Command] = Behaviors.receiveMessagePartial { case WrappedRequestNext(next) => stashBuffer.unstashAll(active(next)) @@ -210,10 +206,9 @@ object WorkPullingDocExample { // TODO retrieve the stored result and reply Behaviors.same } - } private def active( - next: WorkPullingProducerController.RequestNext[ImageConverter.ConversionJob]): Behavior[Command] = { + next: WorkPullingProducerController.RequestNext[ImageConverter.ConversionJob]): Behavior[Command] = Behaviors.receiveMessagePartial { case ConvertRequest(from, to, image, originalReplyTo) => val resultId = UUID.randomUUID() @@ -235,7 +230,6 @@ object WorkPullingDocExample { case _: WrappedRequestNext => throw new IllegalStateException("Unexpected RequestNext") } - } // #ask } diff --git a/cluster-sharding-typed/src/test/scala/docs/org/apache/pekko/cluster/sharding/typed/AccountExampleWithCommandHandlersInDurableState.scala b/cluster-sharding-typed/src/test/scala/docs/org/apache/pekko/cluster/sharding/typed/AccountExampleWithCommandHandlersInDurableState.scala index 98573d2a1be..1b3f64aeeae 100644 --- a/cluster-sharding-typed/src/test/scala/docs/org/apache/pekko/cluster/sharding/typed/AccountExampleWithCommandHandlersInDurableState.scala +++ b/cluster-sharding-typed/src/test/scala/docs/org/apache/pekko/cluster/sharding/typed/AccountExampleWithCommandHandlersInDurableState.scala @@ -91,22 +91,19 @@ object AccountExampleWithCommandHandlersInDurableState { } - private def canWithdraw(amount: BigDecimal): Boolean = { + private def canWithdraw(amount: BigDecimal): Boolean = balance - amount >= Zero - } // #reply - private def deposit(cmd: Deposit) = { + private def deposit(cmd: Deposit) = Effect.persist(copy(balance = balance + cmd.amount)).thenReply(cmd.replyTo)(_ => StatusReply.Ack) - } - private def withdraw(cmd: Withdraw) = { + private def withdraw(cmd: Withdraw) = if (canWithdraw(cmd.amount)) Effect.persist(copy(balance = balance - cmd.amount)).thenReply(cmd.replyTo)(_ => StatusReply.Ack) else Effect.reply(cmd.replyTo)( StatusReply.Error(s"Insufficient balance $balance to be able to withdraw ${cmd.amount}")) - } // #reply } @@ -134,10 +131,9 @@ object AccountExampleWithCommandHandlersInDurableState { EntityTypeKey[Command]("Account") // #withEnforcedReplies - def apply(persistenceId: PersistenceId): Behavior[Command] = { + def apply(persistenceId: PersistenceId): Behavior[Command] = DurableStateBehavior .withEnforcedReplies[Command, Account](persistenceId, EmptyAccount, (state, cmd) => state.applyCommand(cmd)) - } // #withEnforcedReplies } // #account-entity diff --git a/cluster-sharding-typed/src/test/scala/docs/org/apache/pekko/cluster/sharding/typed/AccountExampleWithCommandHandlersInState.scala b/cluster-sharding-typed/src/test/scala/docs/org/apache/pekko/cluster/sharding/typed/AccountExampleWithCommandHandlersInState.scala index 68c3f99e669..0ea0a65cfec 100644 --- a/cluster-sharding-typed/src/test/scala/docs/org/apache/pekko/cluster/sharding/typed/AccountExampleWithCommandHandlersInState.scala +++ b/cluster-sharding-typed/src/test/scala/docs/org/apache/pekko/cluster/sharding/typed/AccountExampleWithCommandHandlersInState.scala @@ -115,9 +115,8 @@ object AccountExampleWithCommandHandlersInState { case AccountCreated => throw new IllegalStateException(s"unexpected event [$event] in state [OpenedAccount]") } - def canWithdraw(amount: BigDecimal): Boolean = { + def canWithdraw(amount: BigDecimal): Boolean = balance - amount >= Zero - } } case object ClosedAccount extends Account { @@ -146,13 +145,12 @@ object AccountExampleWithCommandHandlersInState { val TypeKey: EntityTypeKey[Command] = EntityTypeKey[Command]("Account") - def apply(persistenceId: PersistenceId): Behavior[Command] = { + def apply(persistenceId: PersistenceId): Behavior[Command] = EventSourcedBehavior.withEnforcedReplies[Command, Event, Account]( persistenceId, EmptyAccount, (state, cmd) => state.applyCommand(cmd), (state, event) => state.applyEvent(event)) - } } // #account-entity diff --git a/cluster-sharding-typed/src/test/scala/docs/org/apache/pekko/cluster/sharding/typed/AccountExampleWithEventHandlersInState.scala b/cluster-sharding-typed/src/test/scala/docs/org/apache/pekko/cluster/sharding/typed/AccountExampleWithEventHandlersInState.scala index 2fc6caa9c8b..4ec4d0c6a34 100644 --- a/cluster-sharding-typed/src/test/scala/docs/org/apache/pekko/cluster/sharding/typed/AccountExampleWithEventHandlersInState.scala +++ b/cluster-sharding-typed/src/test/scala/docs/org/apache/pekko/cluster/sharding/typed/AccountExampleWithEventHandlersInState.scala @@ -82,9 +82,8 @@ object AccountExampleWithEventHandlersInState { case AccountCreated => throw new IllegalStateException(s"unexpected event [$event] in state [OpenedAccount]") } - def canWithdraw(amount: BigDecimal): Boolean = { + def canWithdraw(amount: BigDecimal): Boolean = balance - amount >= Zero - } } case object ClosedAccount extends Account { @@ -101,9 +100,8 @@ object AccountExampleWithEventHandlersInState { // to generate the stub with types for the command and event handlers. // #withEnforcedReplies - def apply(accountNumber: String, persistenceId: PersistenceId): Behavior[Command] = { + def apply(accountNumber: String, persistenceId: PersistenceId): Behavior[Command] = EventSourcedBehavior.withEnforcedReplies(persistenceId, EmptyAccount, commandHandler(accountNumber), eventHandler) - } // #withEnforcedReplies private def commandHandler(accountNumber: String): (Account, Command) => ReplyEffect[Event, Account] = { @@ -143,42 +141,36 @@ object AccountExampleWithEventHandlersInState { private def replyClosed( accountNumber: String, - replyTo: ActorRef[StatusReply[Done]]): ReplyEffect[Event, Account] = { + replyTo: ActorRef[StatusReply[Done]]): ReplyEffect[Event, Account] = Effect.reply(replyTo)(StatusReply.Error(s"Account $accountNumber is closed")) - } private val eventHandler: (Account, Event) => Account = { (state, event) => state.applyEvent(event) } - private def createAccount(cmd: CreateAccount): ReplyEffect[Event, Account] = { + private def createAccount(cmd: CreateAccount): ReplyEffect[Event, Account] = Effect.persist(AccountCreated).thenReply(cmd.replyTo)(_ => StatusReply.Ack) - } - private def deposit(cmd: Deposit): ReplyEffect[Event, Account] = { + private def deposit(cmd: Deposit): ReplyEffect[Event, Account] = Effect.persist(Deposited(cmd.amount)).thenReply(cmd.replyTo)(_ => StatusReply.Ack) - } // #reply - private def withdraw(acc: OpenedAccount, cmd: Withdraw): ReplyEffect[Event, Account] = { + private def withdraw(acc: OpenedAccount, cmd: Withdraw): ReplyEffect[Event, Account] = if (acc.canWithdraw(cmd.amount)) Effect.persist(Withdrawn(cmd.amount)).thenReply(cmd.replyTo)(_ => StatusReply.Ack) else Effect.reply(cmd.replyTo)( StatusReply.Error(s"Insufficient balance ${acc.balance} to be able to withdraw ${cmd.amount}")) - } // #reply - private def getBalance(acc: OpenedAccount, cmd: GetBalance): ReplyEffect[Event, Account] = { + private def getBalance(acc: OpenedAccount, cmd: GetBalance): ReplyEffect[Event, Account] = Effect.reply(cmd.replyTo)(CurrentBalance(acc.balance)) - } - private def closeAccount(acc: OpenedAccount, cmd: CloseAccount): ReplyEffect[Event, Account] = { + private def closeAccount(acc: OpenedAccount, cmd: CloseAccount): ReplyEffect[Event, Account] = if (acc.balance == Zero) Effect.persist(AccountClosed).thenReply(cmd.replyTo)(_ => StatusReply.Ack) else Effect.reply(cmd.replyTo)(StatusReply.Error("Can't close account with non-zero balance")) - } } // #account-entity diff --git a/cluster-sharding-typed/src/test/scala/docs/org/apache/pekko/cluster/sharding/typed/AccountExampleWithOptionDurableState.scala b/cluster-sharding-typed/src/test/scala/docs/org/apache/pekko/cluster/sharding/typed/AccountExampleWithOptionDurableState.scala index 057dae57d1f..399a61063aa 100644 --- a/cluster-sharding-typed/src/test/scala/docs/org/apache/pekko/cluster/sharding/typed/AccountExampleWithOptionDurableState.scala +++ b/cluster-sharding-typed/src/test/scala/docs/org/apache/pekko/cluster/sharding/typed/AccountExampleWithOptionDurableState.scala @@ -82,9 +82,8 @@ object AccountExampleWithOptionDurableState { } - def canWithdraw(amount: BigDecimal): Boolean = { + def canWithdraw(amount: BigDecimal): Boolean = balance - amount >= Zero - } } case object ClosedAccount extends Account { @@ -110,7 +109,7 @@ object AccountExampleWithOptionDurableState { val TypeKey: EntityTypeKey[Command] = EntityTypeKey[Command]("Account") - def apply(persistenceId: PersistenceId): Behavior[Command] = { + def apply(persistenceId: PersistenceId): Behavior[Command] = DurableStateBehavior.withEnforcedReplies[Command, Option[Account]]( persistenceId, None, @@ -119,9 +118,8 @@ object AccountExampleWithOptionDurableState { case None => onFirstCommand(cmd) case Some(account) => account.applyCommand(cmd) }) - } - def onFirstCommand(cmd: Command): ReplyEffect = { + def onFirstCommand(cmd: Command): ReplyEffect = cmd match { case CreateAccount(replyTo) => Effect.persist(Some(OpenedAccount(Zero))).thenReply(replyTo)(_ => StatusReply.Ack) @@ -129,7 +127,6 @@ object AccountExampleWithOptionDurableState { // CreateAccount before handling any other commands Effect.unhandled.thenNoReply() } - } } // #account-entity diff --git a/cluster-sharding-typed/src/test/scala/docs/org/apache/pekko/cluster/sharding/typed/AccountExampleWithOptionState.scala b/cluster-sharding-typed/src/test/scala/docs/org/apache/pekko/cluster/sharding/typed/AccountExampleWithOptionState.scala index aa591b25749..fb2448399ca 100644 --- a/cluster-sharding-typed/src/test/scala/docs/org/apache/pekko/cluster/sharding/typed/AccountExampleWithOptionState.scala +++ b/cluster-sharding-typed/src/test/scala/docs/org/apache/pekko/cluster/sharding/typed/AccountExampleWithOptionState.scala @@ -99,9 +99,8 @@ object AccountExampleWithOptionState { case AccountCreated => throw new IllegalStateException(s"unexpected event [$event] in state [OpenedAccount]") } - def canWithdraw(amount: BigDecimal): Boolean = { + def canWithdraw(amount: BigDecimal): Boolean = balance - amount >= Zero - } } case object ClosedAccount extends Account { @@ -130,7 +129,7 @@ object AccountExampleWithOptionState { val TypeKey: EntityTypeKey[Command] = EntityTypeKey[Command]("Account") - def apply(persistenceId: PersistenceId): Behavior[Command] = { + def apply(persistenceId: PersistenceId): Behavior[Command] = EventSourcedBehavior.withEnforcedReplies[Command, Event, Option[Account]]( persistenceId, None, @@ -144,9 +143,8 @@ object AccountExampleWithOptionState { case None => Some(onFirstEvent(event)) case Some(account) => Some(account.applyEvent(event)) }) - } - def onFirstCommand(cmd: Command): ReplyEffect = { + def onFirstCommand(cmd: Command): ReplyEffect = cmd match { case CreateAccount(replyTo) => Effect.persist(AccountCreated).thenReply(replyTo)(_ => StatusReply.Ack) @@ -154,14 +152,12 @@ object AccountExampleWithOptionState { // CreateAccount before handling any other commands Effect.unhandled.thenNoReply() } - } - def onFirstEvent(event: Event): Account = { + def onFirstEvent(event: Event): Account = event match { case AccountCreated => OpenedAccount(Zero) case _ => throw new IllegalStateException(s"unexpected event [$event] in state [EmptyAccount]") } - } } // #account-entity diff --git a/cluster-sharding-typed/src/test/scala/docs/org/apache/pekko/cluster/sharding/typed/HelloWorldPersistentEntityExample.scala b/cluster-sharding-typed/src/test/scala/docs/org/apache/pekko/cluster/sharding/typed/HelloWorldPersistentEntityExample.scala index e91e122428c..c4c67605a04 100644 --- a/cluster-sharding-typed/src/test/scala/docs/org/apache/pekko/cluster/sharding/typed/HelloWorldPersistentEntityExample.scala +++ b/cluster-sharding-typed/src/test/scala/docs/org/apache/pekko/cluster/sharding/typed/HelloWorldPersistentEntityExample.scala @@ -93,12 +93,11 @@ object HelloWorldPersistentEntityExample { val TypeKey: EntityTypeKey[Command] = EntityTypeKey[Command]("HelloWorld") - def apply(entityId: String, persistenceId: PersistenceId): Behavior[Command] = { + def apply(entityId: String, persistenceId: PersistenceId): Behavior[Command] = Behaviors.setup { context => context.log.info("Starting HelloWorld {}", entityId) EventSourcedBehavior(persistenceId, emptyState = KnownPeople(Set.empty), commandHandler, eventHandler) } - } } // #persistent-entity diff --git a/cluster-sharding-typed/src/test/scala/docs/org/apache/pekko/cluster/sharding/typed/ShardingCompileOnlySpec.scala b/cluster-sharding-typed/src/test/scala/docs/org/apache/pekko/cluster/sharding/typed/ShardingCompileOnlySpec.scala index a02cff3cadd..905491703d8 100644 --- a/cluster-sharding-typed/src/test/scala/docs/org/apache/pekko/cluster/sharding/typed/ShardingCompileOnlySpec.scala +++ b/cluster-sharding-typed/src/test/scala/docs/org/apache/pekko/cluster/sharding/typed/ShardingCompileOnlySpec.scala @@ -51,7 +51,7 @@ object ShardingCompileOnlySpec { final case class GetValue(replyTo: ActorRef[Int]) extends Command def apply(entityId: String): Behavior[Command] = { - def updated(value: Int): Behavior[Command] = { + def updated(value: Int): Behavior[Command] = Behaviors.receiveMessage[Command] { case Increment => updated(value + 1) @@ -59,7 +59,6 @@ object ShardingCompileOnlySpec { replyTo ! value Behaviors.same } - } updated(0) @@ -111,7 +110,7 @@ object ShardingCompileOnlySpec { private case object Idle extends Command case object GoodByeCounter extends Command - def apply(shard: ActorRef[ClusterSharding.ShardCommand], entityId: String): Behavior[Command] = { + def apply(shard: ActorRef[ClusterSharding.ShardCommand], entityId: String): Behavior[Command] = Behaviors.setup { ctx => def updated(value: Int): Behavior[Command] = Behaviors.receiveMessage[Command] { @@ -132,7 +131,6 @@ object ShardingCompileOnlySpec { ctx.setReceiveTimeout(30.seconds, Idle) updated(0) } - } } // #counter-passivate diff --git a/cluster-sharding-typed/src/test/scala/org/apache/pekko/cluster/sharding/FlightRecording.scala b/cluster-sharding-typed/src/test/scala/org/apache/pekko/cluster/sharding/FlightRecording.scala index 94dc53e2459..918999a6b69 100644 --- a/cluster-sharding-typed/src/test/scala/org/apache/pekko/cluster/sharding/FlightRecording.scala +++ b/cluster-sharding-typed/src/test/scala/org/apache/pekko/cluster/sharding/FlightRecording.scala @@ -33,12 +33,11 @@ class FlightRecording(system: ActorSystem) { private val stopMethod = clazz.map(_.getDeclaredMethod("stop")) private val dumpMethod = clazz.map(_.getDeclaredMethod("dump", classOf[Path])) - def start() = { + def start() = for { r <- recording m <- startMethod } yield m.invoke(r) - } def endAndDump(location: Path) = { // Make sure parent directory exists diff --git a/cluster-sharding-typed/src/test/scala/org/apache/pekko/cluster/sharding/typed/JoinConfigCompatCheckerClusterShardingSpec.scala b/cluster-sharding-typed/src/test/scala/org/apache/pekko/cluster/sharding/typed/JoinConfigCompatCheckerClusterShardingSpec.scala index b2b8183ec75..5f61e5d31cc 100644 --- a/cluster-sharding-typed/src/test/scala/org/apache/pekko/cluster/sharding/typed/JoinConfigCompatCheckerClusterShardingSpec.scala +++ b/cluster-sharding-typed/src/test/scala/org/apache/pekko/cluster/sharding/typed/JoinConfigCompatCheckerClusterShardingSpec.scala @@ -64,7 +64,7 @@ class JoinConfigCompatCheckerClusterShardingSpec private def configured(system: ActorSystem[_]): Int = system.settings.config.getInt(Key) - private def join(sys: ActorSystem[_]): ClassicCluster = { + private def join(sys: ActorSystem[_]): ClassicCluster = if (sys eq system) { configured(system) should ===(Shards) val seedNode = ClassicCluster(system) @@ -77,7 +77,6 @@ class JoinConfigCompatCheckerClusterShardingSpec joiningNode.joinSeedNodes(im.Seq(ClassicCluster(system).selfAddress)) joiningNode } - } "A Joining Node" must { diff --git a/cluster-sharding-typed/src/test/scala/org/apache/pekko/cluster/sharding/typed/ShardingSerializerSpec.scala b/cluster-sharding-typed/src/test/scala/org/apache/pekko/cluster/sharding/typed/ShardingSerializerSpec.scala index 4d52cd50bb6..9a338660686 100644 --- a/cluster-sharding-typed/src/test/scala/org/apache/pekko/cluster/sharding/typed/ShardingSerializerSpec.scala +++ b/cluster-sharding-typed/src/test/scala/org/apache/pekko/cluster/sharding/typed/ShardingSerializerSpec.scala @@ -30,7 +30,7 @@ class ShardingSerializerSpec extends ScalaTestWithActorTestKit with AnyWordSpecL val serialization = SerializationExtension(ActorSystemAdapter.toClassic(system)) - def checkSerialization(obj: AnyRef): Unit = { + def checkSerialization(obj: AnyRef): Unit = serialization.findSerializerFor(obj) match { case serializer: ShardingSerializer => val blob = serializer.toBinary(obj) @@ -48,7 +48,6 @@ class ShardingSerializerSpec extends ScalaTestWithActorTestKit with AnyWordSpecL case s => throw new IllegalStateException(s"Wrong serializer ${s.getClass} for ${obj.getClass}") } - } "must serialize and deserialize ShardingEnvelope" in { checkSerialization(ShardingEnvelope("abc", 42)) diff --git a/cluster-sharding-typed/src/test/scala/org/apache/pekko/cluster/sharding/typed/delivery/ReliableDeliveryShardingSpec.scala b/cluster-sharding-typed/src/test/scala/org/apache/pekko/cluster/sharding/typed/delivery/ReliableDeliveryShardingSpec.scala index 1127e78a85b..4e40869e00a 100644 --- a/cluster-sharding-typed/src/test/scala/org/apache/pekko/cluster/sharding/typed/delivery/ReliableDeliveryShardingSpec.scala +++ b/cluster-sharding-typed/src/test/scala/org/apache/pekko/cluster/sharding/typed/delivery/ReliableDeliveryShardingSpec.scala @@ -55,7 +55,7 @@ object ReliableDeliveryShardingSpec { private case object Tick extends Command - def apply(producerController: ActorRef[ShardingProducerController.Start[TestConsumer.Job]]): Behavior[Command] = { + def apply(producerController: ActorRef[ShardingProducerController.Start[TestConsumer.Job]]): Behavior[Command] = Behaviors.setup { context => context.setLoggerName("TestShardingProducer") val requestNextAdapter: ActorRef[ShardingProducerController.RequestNext[TestConsumer.Job]] = @@ -68,16 +68,14 @@ object ReliableDeliveryShardingSpec { idle(0) } } - } - private def idle(n: Int): Behavior[Command] = { + private def idle(n: Int): Behavior[Command] = Behaviors.receiveMessage { case Tick => Behaviors.same case RequestNext(sendTo) => active(n + 1, sendTo) } - } - private def active(n: Int, sendTo: ActorRef[ShardingEnvelope[TestConsumer.Job]]): Behavior[Command] = { + private def active(n: Int, sendTo: ActorRef[ShardingEnvelope[TestConsumer.Job]]): Behavior[Command] = Behaviors.receive { (ctx, msg) => msg match { case Tick => @@ -92,7 +90,6 @@ object ReliableDeliveryShardingSpec { Behaviors.same } } - } } diff --git a/cluster-sharding-typed/src/test/scala/org/apache/pekko/cluster/sharding/typed/scaladsl/ClusterShardingPersistenceSpec.scala b/cluster-sharding-typed/src/test/scala/org/apache/pekko/cluster/sharding/typed/scaladsl/ClusterShardingPersistenceSpec.scala index 7f8cd731978..d0eb42f68a1 100644 --- a/cluster-sharding-typed/src/test/scala/org/apache/pekko/cluster/sharding/typed/scaladsl/ClusterShardingPersistenceSpec.scala +++ b/cluster-sharding-typed/src/test/scala/org/apache/pekko/cluster/sharding/typed/scaladsl/ClusterShardingPersistenceSpec.scala @@ -81,7 +81,7 @@ object ClusterShardingPersistenceSpec { // Promise completed by the actor when it's started. val entityActorRefs = new ConcurrentHashMap[String, Promise[ActorRef[Any]]] - def persistentEntity(entityId: String, shard: ActorRef[ShardCommand]): Behavior[Command] = { + def persistentEntity(entityId: String, shard: ActorRef[ShardCommand]): Behavior[Command] = Behaviors.setup { ctx => entityActorRefs.get(entityId) match { case null => @@ -150,7 +150,6 @@ object ClusterShardingPersistenceSpec { } } } - } } diff --git a/cluster-sharding-typed/src/test/scala/org/apache/pekko/cluster/sharding/typed/scaladsl/ShardedDaemonProcessSpec.scala b/cluster-sharding-typed/src/test/scala/org/apache/pekko/cluster/sharding/typed/scaladsl/ShardedDaemonProcessSpec.scala index 89ee775e73c..b8400f3ddbd 100644 --- a/cluster-sharding-typed/src/test/scala/org/apache/pekko/cluster/sharding/typed/scaladsl/ShardedDaemonProcessSpec.scala +++ b/cluster-sharding-typed/src/test/scala/org/apache/pekko/cluster/sharding/typed/scaladsl/ShardedDaemonProcessSpec.scala @@ -78,9 +78,8 @@ class ShardedDaemonProcessSpec "have a single node cluster running first" in { val probe = createTestProbe() Cluster(system).manager ! Join(Cluster(system).selfMember.address) - probe.awaitAssert({ - Cluster(system).selfMember.status == MemberStatus.Up - }, 3.seconds) + probe.awaitAssert( + Cluster(system).selfMember.status == MemberStatus.Up, 3.seconds) } "start N actors with unique ids" in { diff --git a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/ClusterSharding.scala b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/ClusterSharding.scala index 9278839da3d..828062f16c0 100755 --- a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/ClusterSharding.scala +++ b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/ClusterSharding.scala @@ -228,8 +228,7 @@ class ClusterSharding(system: ExtendedActorSystem) extends Extension { extractEntityId: ShardRegion.ExtractEntityId, extractShardId: ShardRegion.ExtractShardId, allocationStrategy: ShardAllocationStrategy, - handOffStopMessage: Any): ActorRef = { - + handOffStopMessage: Any): ActorRef = internalStart( typeName, _ => entityProps, @@ -238,7 +237,6 @@ class ClusterSharding(system: ExtendedActorSystem) extends Extension { extractShardId, allocationStrategy, handOffStopMessage) - } /** * Scala API: Register a named entity type by defining the [[pekko.actor.Props]] of the entity actor @@ -270,8 +268,7 @@ class ClusterSharding(system: ExtendedActorSystem) extends Extension { extractEntityId: ShardRegion.ExtractEntityId, extractShardId: ShardRegion.ExtractShardId, allocationStrategy: ShardAllocationStrategy, - handOffStopMessage: Any): ActorRef = { - + handOffStopMessage: Any): ActorRef = start( typeName, entityProps, @@ -280,7 +277,6 @@ class ClusterSharding(system: ExtendedActorSystem) extends Extension { extractShardId, allocationStrategy, handOffStopMessage) - } /** * INTERNAL API @@ -390,10 +386,8 @@ class ClusterSharding(system: ExtendedActorSystem) extends Extension { typeName: String, entityProps: Props, extractEntityId: ShardRegion.ExtractEntityId, - extractShardId: ShardRegion.ExtractShardId): ActorRef = { - + extractShardId: ShardRegion.ExtractShardId): ActorRef = start(typeName, entityProps, ClusterShardingSettings(system), extractEntityId, extractShardId) - } /** * Java/Scala API: Register a named entity type by defining the [[pekko.actor.Props]] of the entity actor @@ -423,8 +417,7 @@ class ClusterSharding(system: ExtendedActorSystem) extends Extension { settings: ClusterShardingSettings, messageExtractor: ShardRegion.MessageExtractor, allocationStrategy: ShardAllocationStrategy, - handOffStopMessage: Any): ActorRef = { - + handOffStopMessage: Any): ActorRef = internalStart( typeName, _ => entityProps, @@ -436,7 +429,6 @@ class ClusterSharding(system: ExtendedActorSystem) extends Extension { extractShardId = msg => messageExtractor.shardId(msg), allocationStrategy = allocationStrategy, handOffStopMessage = handOffStopMessage) - } /** * Java/Scala API: Register a named entity type by defining the [[pekko.actor.Props]] of the entity actor @@ -490,9 +482,8 @@ class ClusterSharding(system: ExtendedActorSystem) extends Extension { * entity from the incoming message * @return the actor ref of the [[ShardRegion]] that is to be responsible for the shard */ - def start(typeName: String, entityProps: Props, messageExtractor: ShardRegion.MessageExtractor): ActorRef = { + def start(typeName: String, entityProps: Props, messageExtractor: ShardRegion.MessageExtractor): ActorRef = start(typeName, entityProps, ClusterShardingSettings(system), messageExtractor) - } /** * Scala API: Register a named entity type `ShardRegion` on this node that will run in proxy only mode, @@ -546,8 +537,7 @@ class ClusterSharding(system: ExtendedActorSystem) extends Extension { role: Option[String], dataCenter: Option[DataCenter], extractEntityId: ShardRegion.ExtractEntityId, - extractShardId: ShardRegion.ExtractShardId): ActorRef = { - + extractShardId: ShardRegion.ExtractShardId): ActorRef = proxies.get(proxyName(typeName, dataCenter)) match { case null => // it's ok to StartProxy several time, the guardian will deduplicate concurrent requests @@ -560,14 +550,12 @@ class ClusterSharding(system: ExtendedActorSystem) extends Extension { shardRegion case ref => ref // already started, use cached ActorRef } - } - private def proxyName(typeName: String, dataCenter: Option[DataCenter]): String = { + private def proxyName(typeName: String, dataCenter: Option[DataCenter]): String = dataCenter match { case None => s"${typeName}Proxy" case Some(t) => s"${typeName}Proxy" + "-" + t } - } /** * Java/Scala API: Register a named entity type `ShardRegion` on this node that will run in proxy only mode, @@ -610,16 +598,13 @@ class ClusterSharding(system: ExtendedActorSystem) extends Extension { typeName: String, role: Optional[String], dataCenter: Optional[String], - messageExtractor: ShardRegion.MessageExtractor): ActorRef = { - + messageExtractor: ShardRegion.MessageExtractor): ActorRef = startProxy(typeName, Option(role.orElse(null)), Option(dataCenter.orElse(null)), extractEntityId = { case msg if messageExtractor.entityId(msg) ne null => (messageExtractor.entityId(msg), messageExtractor.entityMessage(msg)) }, extractShardId = msg => messageExtractor.shardId(msg)) - } - /** * Scala API: get all currently defined sharding type names. */ @@ -635,7 +620,7 @@ class ClusterSharding(system: ExtendedActorSystem) extends Extension { * The entity type must be registered with the [[#start]] or [[#startProxy]] method before it * can be used here. Messages to the entity is always sent via the `ShardRegion`. */ - def shardRegion(typeName: String): ActorRef = { + def shardRegion(typeName: String): ActorRef = regions.get(typeName) match { case null => proxies.get(proxyName(typeName, None)) match { @@ -646,7 +631,6 @@ class ClusterSharding(system: ExtendedActorSystem) extends Extension { } case ref => ref } - } /** * Retrieve the actor reference of the [[ShardRegion]] actor that will act as a proxy to the @@ -655,18 +639,17 @@ class ClusterSharding(system: ExtendedActorSystem) extends Extension { * [[#startProxy]] method before it can be used here. Messages to the entity is always sent * via the `ShardRegion`. */ - def shardRegionProxy(typeName: String, dataCenter: DataCenter): ActorRef = { + def shardRegionProxy(typeName: String, dataCenter: DataCenter): ActorRef = proxies.get(proxyName(typeName, Some(dataCenter))) match { case null => throw new IllegalStateException(s"Shard type [$typeName] must be started first") case ref => ref } - } /** * The default `ShardAllocationStrategy` is configured by `least-shard-allocation-strategy` properties. */ - def defaultShardAllocationStrategy(settings: ClusterShardingSettings): ShardAllocationStrategy = { + def defaultShardAllocationStrategy(settings: ClusterShardingSettings): ShardAllocationStrategy = if (settings.tuningParameters.leastShardAllocationAbsoluteLimit > 0) { // new algorithm val absoluteLimit = settings.tuningParameters.leastShardAllocationAbsoluteLimit @@ -678,7 +661,6 @@ class ClusterSharding(system: ExtendedActorSystem) extends Extension { val maxSimultaneousRebalance = settings.tuningParameters.leastShardAllocationMaxSimultaneousRebalance new ShardCoordinator.LeastShardAllocationStrategy(threshold, maxSimultaneousRebalance) } - } } /** @@ -736,7 +718,7 @@ private[pekko] class ClusterShardingGuardian extends Actor { settingsWithRoles.withDurableKeys(Set.empty[String]) } - private def replicator(settings: ClusterShardingSettings): ActorRef = { + private def replicator(settings: ClusterShardingSettings): ActorRef = if (settings.stateStoreMode == ClusterShardingSettings.StateStoreModeDData || settings.stateStoreMode == ClusterShardingSettings.RememberEntitiesStoreCustom) { // one Replicator per role @@ -753,7 +735,6 @@ private[pekko] class ClusterShardingGuardian extends Actor { } } else context.system.deadLetters - } def receive: Receive = { case Start( diff --git a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/ClusterShardingHealthCheck.scala b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/ClusterShardingHealthCheck.scala index cf11c08ae2c..5d455d916b5 100644 --- a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/ClusterShardingHealthCheck.scala +++ b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/ClusterShardingHealthCheck.scala @@ -72,7 +72,7 @@ final class ClusterShardingHealthCheck private[pekko] ( // Once the check has passed it always does @volatile private var registered = false - override def apply(): Future[Boolean] = { + override def apply(): Future[Boolean] = if (settings.names.isEmpty || registered) { ClusterShardingHealthCheck.Success } else { @@ -108,5 +108,4 @@ final class ClusterShardingHealthCheck private[pekko] ( false } } - } } diff --git a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/ClusterShardingSettings.scala b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/ClusterShardingSettings.scala index db9e21d9da3..39af56ae619 100644 --- a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/ClusterShardingSettings.scala +++ b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/ClusterShardingSettings.scala @@ -65,12 +65,11 @@ object ClusterShardingSettings { */ def apply(config: Config): ClusterShardingSettings = { - def configMajorityPlus(p: String): Int = { + def configMajorityPlus(p: String): Int = toRootLowerCase(config.getString(p)) match { case "all" => Int.MaxValue case _ => config.getInt(p) } - } val tuningParameters = new TuningParameters( coordinatorFailureBackoff = config.getDuration("coordinator-failure-backoff", MILLISECONDS).millis, @@ -313,12 +312,11 @@ object ClusterShardingSettings { new SegmentedSettings(levels, proportions) } - def optional(config: Config): Option[SegmentedSettings] = { + def optional(config: Config): Option[SegmentedSettings] = toRootLowerCase(config.getString("levels")) match { case "off" | "none" => None case _ => Some(SegmentedSettings(config)) } - } } final class SegmentedSettings(val levels: Int, val proportions: immutable.Seq[Double]) { @@ -576,7 +574,7 @@ object ClusterShardingSettings { * testing and feedback. */ @ApiMayChange - def apply(config: Config): PassivationStrategySettings = { + def apply(config: Config): PassivationStrategySettings = toRootLowerCase(config.getString("strategy")) match { case "off" | "none" => PassivationStrategySettings.disabled case strategyName => @@ -595,9 +593,8 @@ object ClusterShardingSettings { replacementPolicySettings, admissionSettings) } - } - def fromSharding(shardingConfig: Config): PassivationStrategySettings = { + def fromSharding(shardingConfig: Config): PassivationStrategySettings = // default to old setting if it exists (defined in application.conf), overriding the new settings if (shardingConfig.hasPath("passivate-idle-entity-after")) { val timeout = @@ -607,7 +604,6 @@ object ClusterShardingSettings { } else { PassivationStrategySettings(shardingConfig.getConfig("passivation")) } - } private[pekko] def oldDefault(idleTimeout: FiniteDuration): PassivationStrategySettings = defaults.withOldIdleStrategy(idleTimeout) @@ -649,7 +645,7 @@ object ClusterShardingSettings { def apply( settings: PassivationStrategySettings.LeastRecentlyUsedSettings, limit: Int, - idle: Option[IdlePassivationStrategy]): LeastRecentlyUsedPassivationStrategy = { + idle: Option[IdlePassivationStrategy]): LeastRecentlyUsedPassivationStrategy = settings.segmentedSettings match { case Some(segmented) => val proportions = @@ -659,7 +655,6 @@ object ClusterShardingSettings { LeastRecentlyUsedPassivationStrategy(limit, proportions, idle) case _ => LeastRecentlyUsedPassivationStrategy(limit, Nil, idle) } - } } /** @@ -1048,7 +1043,7 @@ object ClusterShardingSettings { updatingStateTimeout: FiniteDuration, entityRecoveryStrategy: String, entityRecoveryConstantRateStrategyFrequency: FiniteDuration, - entityRecoveryConstantRateStrategyNumberOfEntities: Int) = { + entityRecoveryConstantRateStrategyNumberOfEntities: Int) = this( coordinatorFailureBackoff, retryInterval, @@ -1067,7 +1062,6 @@ object ClusterShardingSettings { entityRecoveryStrategy, entityRecoveryConstantRateStrategyFrequency, entityRecoveryConstantRateStrategyNumberOfEntities) - } // included for binary compatibility @deprecated("Use the ClusterShardingSettings factory methods or the full constructor instead", since = "Akka 2.6.5") @@ -1084,7 +1078,7 @@ object ClusterShardingSettings { leastShardAllocationRebalanceThreshold: Int, leastShardAllocationMaxSimultaneousRebalance: Int, waitingForStateTimeout: FiniteDuration, - updatingStateTimeout: FiniteDuration) = { + updatingStateTimeout: FiniteDuration) = this( coordinatorFailureBackoff, retryInterval, @@ -1102,7 +1096,6 @@ object ClusterShardingSettings { "all", 100.milliseconds, 5) - } } } diff --git a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/OldCoordinatorStateMigrationEventAdapter.scala b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/OldCoordinatorStateMigrationEventAdapter.scala index 3a3fe6b0073..ea34c7d1ece 100644 --- a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/OldCoordinatorStateMigrationEventAdapter.scala +++ b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/OldCoordinatorStateMigrationEventAdapter.scala @@ -33,12 +33,11 @@ private[pekko] final class OldCoordinatorStateMigrationEventAdapter extends Even override def toJournal(event: Any): Any = event - override def fromJournal(event: Any, manifest: String): EventSeq = { + override def fromJournal(event: Any, manifest: String): EventSeq = event match { case ShardHomeAllocated(shardId, _) => EventSeq.single(shardId) case _ => EventSeq.empty } - } } diff --git a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/RemoveInternalClusterShardingData.scala b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/RemoveInternalClusterShardingData.scala index 2e9ee369538..6f466b73eb6 100644 --- a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/RemoveInternalClusterShardingData.scala +++ b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/RemoveInternalClusterShardingData.scala @@ -69,7 +69,7 @@ object RemoveInternalClusterShardingData { /** * @see [[RemoveInternalClusterShardingData$ RemoveInternalClusterShardingData companion object]] */ - def main(args: Array[String]): Unit = { + def main(args: Array[String]): Unit = if (args.isEmpty) println("Specify the Cluster Sharding type names to remove in program arguments") else { @@ -86,7 +86,6 @@ object RemoveInternalClusterShardingData { } } } - } /** * API corresponding to the [[#main]] method as described in the @@ -223,9 +222,8 @@ class RemoveInternalClusterShardingData( def persistenceId2dot3(typeName: String): String = s"/user/sharding/${typeName}Coordinator/singleton/coordinator" - override def preStart(): Unit = { + override def preStart(): Unit = removeNext() - } def removeNext(): Unit = { currentPid = remainingPids.head diff --git a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/Shard.scala b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/Shard.scala index 5ed37f9c85b..293168d5930 100644 --- a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/Shard.scala +++ b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/Shard.scala @@ -285,12 +285,11 @@ private[pekko] object Shard { // optimization to not have to go through all entities to find batched writes private val remembering = new util.HashSet[EntityId]() - def alreadyRemembered(set: Set[EntityId]): Unit = { + def alreadyRemembered(set: Set[EntityId]): Unit = set.foreach { entityId => val state = entityState(entityId).transition(RememberedButNotCreated, this) entities.put(entityId, state) } - } def rememberingStart(entityId: EntityId, ackTo: Option[ActorRef]): Unit = { val newState = RememberingStart(ackTo) val state = entityState(entityId).transition(newState, this) @@ -344,12 +343,11 @@ private[pekko] object Shard { def entityId(ref: ActorRef): OptionVal[EntityId] = OptionVal(byRef.get(ref)) - def isPassivating(id: EntityId): Boolean = { + def isPassivating(id: EntityId): Boolean = entities.get(id) match { case _: Passivating => true case _ => false } - } def entityPassivating(entityId: EntityId): Unit = { if (verboseDebug) log.debug("[{}] passivating", entityId) entities.get(entityId) match { @@ -361,13 +359,12 @@ private[pekko] object Shard { s"Tried to passivate entity without an actor ref $entityId. Current state $other") } } - private def removeRefIfThereIsOne(state: EntityState): Unit = { + private def removeRefIfThereIsOne(state: EntityState): Unit = state match { case wr: WithRef => byRef.remove(wr.ref) case _ => } - } import pekko.util.ccompat.JavaConverters._ // only called once during handoff @@ -381,7 +378,7 @@ private[pekko] object Shard { /** * @return (remembering start, remembering stop) */ - def pendingRememberEntities(): (Map[EntityId, RememberingStart], Set[EntityId]) = { + def pendingRememberEntities(): (Map[EntityId, RememberingStart], Set[EntityId]) = if (remembering.isEmpty) { (Map.empty, Set.empty) } else { @@ -395,7 +392,6 @@ private[pekko] object Shard { }) (starts.result(), stops.result()) } - } def pendingRememberedEntitiesExist(): Boolean = !remembering.isEmpty @@ -500,7 +496,7 @@ private[pekko] class Shard( } // ===== lease handling initialization ===== - def acquireLeaseIfNeeded(): Unit = { + def acquireLeaseIfNeeded(): Unit = lease match { case Some(l) => tryGetLease(l) @@ -508,7 +504,6 @@ private[pekko] class Shard( case None => tryLoadRememberedEntities() } - } // Don't send back ShardInitialized so that messages are buffered in the ShardRegion // while awaiting the lease @@ -555,7 +550,7 @@ private[pekko] class Shard( } // ===== remember entities initialization ===== - def tryLoadRememberedEntities(): Unit = { + def tryLoadRememberedEntities(): Unit = rememberEntitiesStore match { case Some(store) => log.debug("{}: Waiting for load of entity ids using [{}] to complete", typeName, store) @@ -568,7 +563,6 @@ private[pekko] class Shard( case None => shardInitialized() } - } def awaitingRememberedEntities(): Receive = { case RememberEntitiesShardStore.RememberedEntities(entityIds) => @@ -635,14 +629,13 @@ private[pekko] class Shard( case msg if extractEntityId.isDefinedAt(msg) => deliverMessage(msg, sender()) } - def rememberUpdate(add: Set[EntityId] = Set.empty, remove: Set[EntityId] = Set.empty): Unit = { + def rememberUpdate(add: Set[EntityId] = Set.empty, remove: Set[EntityId] = Set.empty): Unit = rememberEntitiesStore match { case None => onUpdateDone(add, remove) case Some(store) => sendToRememberStore(store, storingStarts = add, storingStops = remove) } - } def sendToRememberStore(store: ActorRef, storingStarts: Set[EntityId], storingStops: Set[EntityId]): Unit = { if (verboseDebug) @@ -814,7 +807,7 @@ private[pekko] class Shard( // this could be because of a start message or due to a new message for the entity // if it is a start entity then start entity ack is sent after it is created - private def startEntity(entityId: EntityId, ackTo: Option[ActorRef]): Unit = { + private def startEntity(entityId: EntityId, ackTo: Option[ActorRef]): Unit = entities.entityState(entityId) match { case Active(_) => if (verboseDebug) @@ -844,7 +837,6 @@ private[pekko] class Shard( entities.rememberingStart(entityId, ackTo) rememberUpdate(add = Set(entityId)) } - } private def receiveCoordinatorMessage(msg: CoordinatorMessage): Unit = msg match { case HandOff(`shardId`) => @@ -875,7 +867,7 @@ private[pekko] class Shard( val activeEntities = entities.activeEntities() if (preparingForShutdown) { log.info("{}: HandOff shard [{}] while preparing for shutdown. Stopping right away.", typeName, shardId) - activeEntities.foreach { _ ! handOffStopMessage } + activeEntities.foreach(_ ! handOffStopMessage) replyTo ! ShardStopped(shardId) context.stop(self) } else if (activeEntities.nonEmpty && !preparingForShutdown) { @@ -901,10 +893,9 @@ private[pekko] class Shard( } } - private def receiveTerminated(ref: ActorRef): Unit = { + private def receiveTerminated(ref: ActorRef): Unit = if (handOffStopper.contains(ref)) context.stop(self) - } @InternalStableApi def entityTerminated(ref: ActorRef): Unit = { @@ -971,7 +962,7 @@ private[pekko] class Shard( } } - private def passivate(entity: ActorRef, stopMessage: Any): Unit = { + private def passivate(entity: ActorRef, stopMessage: Any): Unit = entities.entityId(entity) match { case OptionVal.Some(id) => if (entities.isPassivating(id)) { @@ -991,7 +982,6 @@ private[pekko] class Shard( case _ => log.debug("{}: Unknown entity passivating [{}]. Not sending stopMessage back to entity", typeName, entity) } - } private def activeEntityLimitUpdated(updated: ShardRegion.SetActiveEntityLimit): Unit = { val entitiesToPassivate = passivationStrategy.limitUpdated(updated.perRegionLimit) @@ -1008,7 +998,7 @@ private[pekko] class Shard( passivateEntities(entitiesToPassivate) } - private def passivateEntities(entitiesToPassivate: EntityPassivationStrategy.PassivateEntities): Unit = { + private def passivateEntities(entitiesToPassivate: EntityPassivationStrategy.PassivateEntities): Unit = if (entitiesToPassivate.nonEmpty) { val refsToPassivate = entitiesToPassivate.collect { case entityId if entities.entity(entityId).isDefined => entities.entity(entityId).get @@ -1018,7 +1008,6 @@ private[pekko] class Shard( refsToPassivate.foreach(passivate(_, handOffStopMessage)) } } - } // After entity stopped def passivateCompleted(entityId: EntityId): Unit = { @@ -1121,7 +1110,7 @@ private[pekko] class Shard( } @InternalStableApi - def getOrCreateEntity(id: EntityId): ActorRef = { + def getOrCreateEntity(id: EntityId): ActorRef = entities.entity(id) match { case OptionVal.Some(child) => child case _ => @@ -1133,7 +1122,6 @@ private[pekko] class Shard( entityCreated(id) a } - } /** * Called when an entity has been created. Returning the number @@ -1143,7 +1131,7 @@ private[pekko] class Shard( def entityCreated(@unused id: EntityId): Int = entities.nrActiveEntities() // ===== buffering while busy saving a start or stop when remembering entities ===== - def appendToMessageBuffer(id: EntityId, msg: Any, snd: ActorRef): Unit = { + def appendToMessageBuffer(id: EntityId, msg: Any, snd: ActorRef): Unit = if (messageBuffers.totalSize >= settings.tuningParameters.bufferSize) { if (log.isDebugEnabled) log.debug( @@ -1157,7 +1145,6 @@ private[pekko] class Shard( log.debug("{}: Message of type [{}] for entity [{}] buffered", typeName, msg.getClass.getName, id) messageBuffers.append(id, msg, snd) } - } // After entity started def sendMsgBuffer(entityId: EntityId): Unit = { @@ -1184,9 +1171,8 @@ private[pekko] class Shard( } } - private def rememberEntityStoreCrashed(msg: RememberEntityStoreCrashed): Unit = { + private def rememberEntityStoreCrashed(msg: RememberEntityStoreCrashed): Unit = throw new RuntimeException(s"Remember entities store [${msg.store}] crashed") - } override def postStop(): Unit = { passivateIntervalTask.foreach(_.cancel()) diff --git a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/ShardCoordinator.scala b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/ShardCoordinator.scala index f687553dd13..561c7d332b9 100644 --- a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/ShardCoordinator.scala +++ b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/ShardCoordinator.scala @@ -299,7 +299,7 @@ object ShardCoordinator { override def rebalance( currentShardAllocations: Map[ActorRef, immutable.IndexedSeq[ShardId]], - rebalanceInProgress: Set[ShardId]): Future[Set[ShardId]] = { + rebalanceInProgress: Set[ShardId]): Future[Set[ShardId]] = if (rebalanceInProgress.size < maxSimultaneousRebalance) { val sortedRegionEntries = regionEntriesFor(currentShardAllocations).toVector.sorted(ShardSuitabilityOrdering) if (isAGoodTimeToRebalance(sortedRegionEntries)) { @@ -320,7 +320,6 @@ object ShardCoordinator { emptyRebalanceResult } else emptyRebalanceResult } else emptyRebalanceResult - } } /** @@ -465,12 +464,11 @@ object ShardCoordinator { override def toString = s"State($shards)" - def withRememberEntities(enabled: Boolean): State = { + def withRememberEntities(enabled: Boolean): State = if (enabled) copy(rememberEntities = enabled) else copy(unallocatedShards = Set.empty, rememberEntities = enabled) - } def isEmpty: Boolean = shards.isEmpty && regions.isEmpty && regionProxies.isEmpty @@ -647,9 +645,8 @@ object ShardCoordinator { shardRegionFrom: ActorRef, handOffTimeout: FiniteDuration, regions: Set[ActorRef], - isRebalance: Boolean): Props = { + isRebalance: Boolean): Props = Props(new RebalanceWorker(typeName, shard, shardRegionFrom, handOffTimeout, regions, isRebalance)) - } } @@ -949,7 +946,7 @@ abstract class ShardCoordinator( terminate() }: Receive).orElse[Any, Unit](receiveTerminated) - private def terminate(): Unit = { + private def terminate(): Unit = if (aliveRegions.exists(_.path.address.hasLocalScope) || gracefulShutdownInProgress.exists( _.path.address.hasLocalScope)) { aliveRegions @@ -978,9 +975,8 @@ abstract class ShardCoordinator( } context.stop(self) } - } - private def clearRebalanceInProgress(shard: String): Unit = { + private def clearRebalanceInProgress(shard: String): Unit = rebalanceInProgress.get(shard) match { case Some(pendingGetShardHome) => val msg = GetShardHome(shard) @@ -990,7 +986,6 @@ abstract class ShardCoordinator( rebalanceInProgress -= shard case None => } - } private def deferGetShardHomeRequest(shard: ShardId, from: ActorRef): Unit = { log.debug( @@ -1041,7 +1036,7 @@ abstract class ShardCoordinator( * @return `true` if the message could be handled without state update, i.e. * the shard location was known or the request was deferred or ignored */ - def handleGetShardHome(shard: ShardId): Boolean = { + def handleGetShardHome(shard: ShardId): Boolean = if (rebalanceInProgress.contains(shard)) { deferGetShardHomeRequest(shard, sender()) unstashOneGetShardHomeRequest() // continue unstashing @@ -1071,7 +1066,6 @@ abstract class ShardCoordinator( false // location not known, yet, caller will handle allocation } } - } def receiveTerminated: Receive = { case t @ Terminated(ref) => @@ -1130,14 +1124,13 @@ abstract class ShardCoordinator( allocateShardHomesForRememberEntities() } - def hasAllRegionsRegistered(): Boolean = { + def hasAllRegionsRegistered(): Boolean = // the check is only for startup, i.e. once all have registered we don't check more if (allRegionsRegistered) true else { allRegionsRegistered = aliveRegions.size >= minMembers allRegionsRegistered } - } def regionTerminated(ref: ActorRef): Unit = { rebalanceWorkers.foreach(_ ! RebalanceWorker.ShardRegionTerminated(ref)) @@ -1190,12 +1183,11 @@ abstract class ShardCoordinator( unAckedHostShards = unAckedHostShards.updated(shard, cancel) } - def allocateShardHomesForRememberEntities(): Unit = { + def allocateShardHomesForRememberEntities(): Unit = if (settings.rememberEntities && state.unallocatedShards.nonEmpty) state.unallocatedShards.foreach { shard => self.tell(GetShardHome(shard), ignoreRef) } - } def continueGetShardHome(shard: ShardId, region: ActorRef, getShardHomeSender: ActorRef): Unit = if (rebalanceInProgress.contains(shard)) { @@ -1238,10 +1230,9 @@ abstract class ShardCoordinator( protected def unstashOneGetShardHomeRequest(): Unit - private def regionAddress(region: ActorRef): Address = { + private def regionAddress(region: ActorRef): Address = if (region.path.address.host.isEmpty) cluster.selfAddress else region.path.address - } /** * Start a RebalanceWorker to manage the shard rebalance. @@ -1251,7 +1242,7 @@ abstract class ShardCoordinator( shard: String, from: ActorRef, handOffTimeout: FiniteDuration, - isRebalance: Boolean): Unit = { + isRebalance: Boolean): Unit = if (!rebalanceInProgress.contains(shard)) { rebalanceInProgress = rebalanceInProgress.updated(shard, Set.empty) rebalanceWorkers += context.actorOf( @@ -1263,7 +1254,6 @@ abstract class ShardCoordinator( state.regions.keySet.union(state.regionProxies), isRebalance = isRebalance).withDispatcher(context.props.dispatcher)) } - } def continueRebalance(shards: Set[ShardId]): Unit = { if ((log: BusLogging).isInfoEnabled && (shards.nonEmpty || rebalanceInProgress.nonEmpty)) { @@ -1418,12 +1408,11 @@ class PersistentShardCoordinator( persist(evt)(f) } - def saveSnapshotWhenNeeded(): Unit = { + def saveSnapshotWhenNeeded(): Unit = if (lastSequenceNr % snapshotAfter == 0 && lastSequenceNr != 0) { log.debug("{}: Saving snapshot, sequence number [{}]", typeName, snapshotSequenceNr) saveSnapshot(state) } - } override protected def unstashOneGetShardHomeRequest(): Unit = () } @@ -1776,7 +1765,7 @@ private[pekko] class DDataShardCoordinator( getShardHomeRequests += (sender -> request) } - override protected def unstashOneGetShardHomeRequest(): Unit = { + override protected def unstashOneGetShardHomeRequest(): Unit = if (getShardHomeRequests.nonEmpty) { // unstash one, will continue unstash of next after receive GetShardHome or update completed val requestTuple = getShardHomeRequests.head @@ -1784,7 +1773,6 @@ private[pekko] class DDataShardCoordinator( self.tell(request, sender = originalSender) getShardHomeRequests -= requestTuple } - } def activate(): Unit = { context.become(active.orElse(receiveLateRememberedEntities)) @@ -1834,9 +1822,8 @@ private[pekko] class DDataShardCoordinator( context.become(waitingReceive, discardOld = false) } - def getCoordinatorState(): Unit = { + def getCoordinatorState(): Unit = replicator ! Get(CoordinatorStateKey, stateReadConsistency) - } def getAllRememberedShards(): Unit = { timers.startSingleTimer( diff --git a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/ShardRegion.scala b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/ShardRegion.scala index 20e9a8f3a19..7d9b1b87593 100644 --- a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/ShardRegion.scala +++ b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/ShardRegion.scala @@ -162,12 +162,11 @@ object ShardRegion { /** INTERNAL API */ @InternalApi - private[sharding] def shardId(id: String, maxNumberOfShards: Int): String = { + private[sharding] def shardId(id: String, maxNumberOfShards: Int): String = // It would be better to have abs(id.hashCode % maxNumberOfShards), see issue #25034 // but to avoid getting different values when rolling upgrade we keep the old way, // and it doesn't have any serious consequences (math.abs(id.hashCode) % maxNumberOfShards).toString - } } /** @@ -719,7 +718,7 @@ private[pekko] class ShardRegion( * the likely locations of the coordinator. */ def coordinatorSelection: List[ActorSelection] = { - @tailrec def select(result: List[Member], remaining: immutable.SortedSet[Member]): List[Member] = { + @tailrec def select(result: List[Member], remaining: immutable.SortedSet[Member]): List[Member] = if (remaining.isEmpty) result else { @@ -729,7 +728,6 @@ private[pekko] class ShardRegion( else select(m :: result, remaining.tail) } - } select(Nil, membersByAge).map(m => context.actorSelection(RootActorPath(m.address).toString + coordinatorPath)) } @@ -768,12 +766,11 @@ private[pekko] class ShardRegion( log.warning("{}: Message does not have an extractor defined in shard so it was ignored: {}", typeName, unknownMsg) } - def receiveClusterState(state: CurrentClusterState): Unit = { + def receiveClusterState(state: CurrentClusterState): Unit = changeMembers( immutable.SortedSet .empty(ageOrdering) .union(state.members.filter(m => memberStatusOfInterest(m.status) && matchingRole(m)))) - } def receiveClusterEvent(evt: ClusterDomainEvent): Unit = evt match { case MemberUp(m) => @@ -805,12 +802,11 @@ private[pekko] class ShardRegion( case _ => unhandled(evt) } - private def addMember(m: Member): Unit = { + private def addMember(m: Member): Unit = if (matchingRole(m) && memberStatusOfInterest(m.status)) { // replace, it's possible that the status, or upNumber is changed changeMembers(membersByAge.filterNot(_.uniqueAddress == m.uniqueAddress) + m) } - } def receiveCoordinatorMessage(msg: CoordinatorMessage): Unit = msg match { case HostShard(shard) => @@ -978,7 +974,7 @@ private[pekko] class ShardRegion( case null => unhandled(query) } - def receiveTerminated(ref: ActorRef): Unit = { + def receiveTerminated(ref: ActorRef): Unit = if (coordinator.contains(ref)) { coordinator = None startRegistration() @@ -1022,7 +1018,6 @@ private[pekko] class ShardRegion( // If so, we can try to speed-up the region shutdown. We don't need to wait for the next tick. tryCompleteGracefulShutdownIfInProgress() } - } def receiveShardHome(shard: ShardId, shardRegionRef: ActorRef): Unit = { log.debug("{}: Shard [{}] located at [{}]", typeName, shard, shardRegionRef) @@ -1045,7 +1040,7 @@ private[pekko] class ShardRegion( deliverBufferedMessages(shard, shardRegionRef) } - def replyToRegionStateQuery(ref: ActorRef): Unit = { + def replyToRegionStateQuery(ref: ActorRef): Unit = queryShards[Shard.CurrentShardState](shards, Shard.GetCurrentShardState) .map { qr => CurrentShardRegionState( @@ -1053,15 +1048,13 @@ private[pekko] class ShardRegion( qr.failed) } .pipeTo(ref) - } - def replyToRegionStatsQuery(ref: ActorRef): Unit = { + def replyToRegionStatsQuery(ref: ActorRef): Unit = queryShards[ShardStats](shards, Shard.GetShardStats) .map { qr => ShardRegionStats(qr.responses.map(stats => (stats.shardId, stats.entityCount)).toMap, qr.failed) } .pipeTo(ref) - } /** * Query all or a subset of shards, e.g. unresponsive shards that initially timed out. @@ -1103,17 +1096,15 @@ private[pekko] class ShardRegion( scheduleNextRegistration() } - def scheduleNextRegistration(): Unit = { + def scheduleNextRegistration(): Unit = if (nextRegistrationDelay < retryInterval) { timers.startSingleTimer(RegisterRetry, RegisterRetry, nextRegistrationDelay) // exponentially increasing retry interval until reaching the normal retryInterval nextRegistrationDelay *= 2 } - } - def finishRegistration(): Unit = { + def finishRegistration(): Unit = timers.cancel(RegisterRetry) - } def register(): Unit = { val actorSelections = coordinatorSelection @@ -1171,7 +1162,7 @@ private[pekko] class ShardRegion( * Send GetShardHome for all shards with buffered messages * If coordinator is empty, nothing happens */ - def tryRequestShardBufferHomes(): Unit = { + def tryRequestShardBufferHomes(): Unit = coordinator.foreach { coord => // Have to use vars because MessageBufferMap has no map, only foreach var totalBuffered = 0 @@ -1198,7 +1189,6 @@ private[pekko] class ShardRegion( totalBuffered) } } - } def initializeShard(id: ShardId, shard: ActorRef): Unit = { log.debug("{}: Shard was initialized [{}]", typeName, id) @@ -1256,17 +1246,16 @@ private[pekko] class ShardRegion( retryCount = 0 } - def deliverStartEntity(msg: StartEntity, snd: ActorRef): Unit = { - try { + def deliverStartEntity(msg: StartEntity, snd: ActorRef): Unit = + try deliverMessage(msg, snd) - } catch { + catch { case ex: MatchError => log.error( ex, "{}: When using remember-entities the shard id extractor must handle ShardRegion.StartEntity(id).", typeName) } - } def deliverToAllShards(msg: Any, snd: ActorRef): Unit = shards.values.foreach(_.tell(msg, snd)) @@ -1321,7 +1310,7 @@ private[pekko] class ShardRegion( } } - def getShard(id: ShardId): Option[ActorRef] = { + def getShard(id: ShardId): Option[ActorRef] = if (startingShards.contains(id)) None else { @@ -1359,13 +1348,11 @@ private[pekko] class ShardRegion( throw new IllegalStateException("Shard must not be allocated to a proxy only ShardRegion") }) } - } - def sendGracefulShutdownToCoordinatorIfInProgress(): Unit = { + def sendGracefulShutdownToCoordinatorIfInProgress(): Unit = if (gracefulShutdownInProgress) { val actorSelections = coordinatorSelection log.debug("{}: Sending graceful shutdown to {}", typeName, actorSelections) actorSelections.foreach(_ ! GracefulShutdownReq(self)) } - } } diff --git a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/ShardingQueries.scala b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/ShardingQueries.scala index b774e074744..b6ffc839678 100644 --- a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/ShardingQueries.scala +++ b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/ShardingQueries.scala @@ -46,14 +46,13 @@ private[sharding] object ShardingQueries { */ val queried: Int = failed.size + responses.size - override val toString: String = { + override val toString: String = if (total == 0) s"Shard region had zero shards to gather metadata from." else { val shardsOf = if (queried < total) s"shards of [$total]:" else "shards:" s"Queried [$queried] $shardsOf [${responses.size}] responsive, [${failed.size}] failed after $timeout." } - } } object ShardsQueryResult { diff --git a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/external/ExternalShardAllocation.scala b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/external/ExternalShardAllocation.scala index 68c6ec86348..981126aedbf 100644 --- a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/external/ExternalShardAllocation.scala +++ b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/external/ExternalShardAllocation.scala @@ -48,9 +48,8 @@ final class ExternalShardAllocation(system: ExtendedActorSystem) extends Extensi */ def getClient(typeName: String): javadsl.ExternalShardAllocationClient = client(typeName) - private def client(typeName: String): ExternalShardAllocationClientImpl = { + private def client(typeName: String): ExternalShardAllocationClientImpl = clients.computeIfAbsent(typeName, factory) - } } object ExternalShardAllocation extends ExtensionId[ExternalShardAllocation] with ExtensionIdProvider { diff --git a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/external/ExternalShardAllocationStrategy.scala b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/external/ExternalShardAllocationStrategy.scala index bf2fb5a78b9..422d616e8d0 100644 --- a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/external/ExternalShardAllocationStrategy.scala +++ b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/external/ExternalShardAllocationStrategy.scala @@ -57,9 +57,8 @@ object ExternalShardAllocationStrategy { * Scala API: Create an [[ExternalShardAllocationStrategy]] */ def apply(systemProvider: ClassicActorSystemProvider, typeName: String, timeout: FiniteDuration) - : ExternalShardAllocationStrategy = { + : ExternalShardAllocationStrategy = new ExternalShardAllocationStrategy(systemProvider, typeName)(timeout) - } /** * Java API: Create an [[ExternalShardAllocationStrategy]] @@ -83,9 +82,8 @@ object ExternalShardAllocationStrategy { // uses a string primitive types are optimized in ddata to not serialize every entity // separately - private[pekko] def ddataKey(typeName: String): LWWMapKey[ShardId, String] = { + private[pekko] def ddataKey(typeName: String): LWWMapKey[ShardId, String] = LWWMapKey[ShardId, String](s"external-sharding-$typeName") - } private class DDataStateActor(typeName: String) extends Actor with ActorLogging with Stash { @@ -133,17 +131,15 @@ class ExternalShardAllocationStrategy(systemProvider: ClassicActorSystemProvider private var shardState: ActorRef = _ - private[pekko] def createShardStateActor(): ActorRef = { + private[pekko] def createShardStateActor(): ActorRef = system .asInstanceOf[ExtendedActorSystem] .systemActorOf(DDataStateActor.props(typeName), s"external-allocation-state-$typeName") - } private val cluster = Cluster(system) - override def start(): Unit = { + override def start(): Unit = shardState = createShardStateActor() - } override def allocateShard( requester: ShardRegion, diff --git a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/external/internal/ExternalShardAllocationClientImpl.scala b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/external/internal/ExternalShardAllocationClientImpl.scala index ef42bcf8e81..b84fbb872ed 100644 --- a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/external/internal/ExternalShardAllocationClientImpl.scala +++ b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/external/internal/ExternalShardAllocationClientImpl.scala @@ -87,7 +87,7 @@ final private[external] class ExternalShardAllocationClientImpl(system: ActorSys override def setShardLocation(shard: ShardId, location: Address): CompletionStage[Done] = updateShardLocation(shard, location).asJava - override def shardLocations(): Future[ShardLocations] = { + override def shardLocations(): Future[ShardLocations] = (replicator ? Get(Key, ReadMajority(timeout))) .flatMap { case success @ GetSuccess(`Key`, _) => @@ -102,7 +102,6 @@ final private[external] class ExternalShardAllocationClientImpl(system: ActorSys .map { locations => new ShardLocations(locations) } - } override def getShardLocations(): CompletionStage[ShardLocations] = shardLocations().asJava @@ -120,7 +119,6 @@ final private[external] class ExternalShardAllocationClientImpl(system: ActorSys } } - override def setShardLocations(locations: java.util.Map[ShardId, Address]): CompletionStage[Done] = { + override def setShardLocations(locations: java.util.Map[ShardId, Address]): CompletionStage[Done] = updateShardLocations(locations.asScala.toMap).asJava - } } diff --git a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/internal/AbstractLeastShardAllocationStrategy.scala b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/internal/AbstractLeastShardAllocationStrategy.scala index 4f1f2cd70cd..6eb6eeae8b7 100644 --- a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/internal/AbstractLeastShardAllocationStrategy.scala +++ b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/internal/AbstractLeastShardAllocationStrategy.scala @@ -101,15 +101,14 @@ private[pekko] abstract class AbstractLeastShardAllocationStrategy extends Actor } } - final protected def isAGoodTimeToRebalance(regionEntries: Iterable[RegionEntry]): Boolean = { + final protected def isAGoodTimeToRebalance(regionEntries: Iterable[RegionEntry]): Boolean = // Avoid rebalance when rolling update is in progress // (This will ignore versions on members with no shard regions, because of sharding role or not yet completed joining) regionEntries.headOption match { case None => false // empty list of regions, probably not a good time to rebalance... case Some(firstRegion) => - def allNodesSameVersion = { + def allNodesSameVersion = regionEntries.forall(_.member.appVersion == firstRegion.member.appVersion) - } // Rebalance requires ack from regions and proxies - no need to rebalance if it cannot be completed // FIXME #29589, we currently only look at same dc but proxies in other dcs may delay complete as well right now def neededMembersReachable = @@ -120,7 +119,6 @@ private[pekko] abstract class AbstractLeastShardAllocationStrategy extends Actor allNodesSameVersion && neededMembersReachable && !membersInProgressOfJoining } - } final protected def mostSuitableRegion( regionEntries: Iterable[RegionEntry]): (ActorRef, immutable.IndexedSeq[ShardId]) = { @@ -132,10 +130,9 @@ private[pekko] abstract class AbstractLeastShardAllocationStrategy extends Actor val addressToMember: Map[Address, Member] = clusterState.members.iterator.map(m => m.address -> m).toMap currentShardAllocations.flatMap { case (region, shardIds) => - val regionAddress = { + val regionAddress = if (region.path.address.hasLocalScope) selfMember.address else region.path.address - } val memberForRegion = addressToMember.get(regionAddress) // if the member is unknown (very unlikely but not impossible) because of view not updated yet diff --git a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/internal/DDataRememberEntitiesCoordinatorStore.scala b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/internal/DDataRememberEntitiesCoordinatorStore.scala index 5b23f90eba5..a02614a06ec 100644 --- a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/internal/DDataRememberEntitiesCoordinatorStore.scala +++ b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/internal/DDataRememberEntitiesCoordinatorStore.scala @@ -60,9 +60,8 @@ private[pekko] final class DDataRememberEntitiesCoordinatorStore( private var coordinatorWaitingForShards: Option[ActorRef] = None // eager load of remembered shard ids - def getAllShards(): Unit = { + def getAllShards(): Unit = replicator ! Replicator.Get(AllShardsKey, readMajority) - } getAllShards() override def receive: Receive = { @@ -115,7 +114,7 @@ private[pekko] final class DDataRememberEntitiesCoordinatorStore( replyTo ! RememberEntitiesCoordinatorStore.UpdateFailed(shardId) } - def onGotAllShards(shardIds: Set[ShardId]): Unit = { + def onGotAllShards(shardIds: Set[ShardId]): Unit = coordinatorWaitingForShards match { case Some(coordinator) => coordinator ! RememberEntitiesCoordinatorStore.RememberedShards(shardIds) @@ -126,6 +125,5 @@ private[pekko] final class DDataRememberEntitiesCoordinatorStore( // wait for coordinator to ask allShards = Some(shardIds) } - } } diff --git a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/internal/DDataRememberEntitiesShardStore.scala b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/internal/DDataRememberEntitiesShardStore.scala index 5d7c4475b9d..95a1537a16d 100644 --- a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/internal/DDataRememberEntitiesShardStore.scala +++ b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/internal/DDataRememberEntitiesShardStore.scala @@ -117,9 +117,8 @@ private[pekko] final class DDataRememberEntitiesShardStore( keys(i) } - override def receive: Receive = { + override def receive: Receive = waitingForAllEntityIds(Set.empty, Set.empty, None) - } def idle: Receive = { case RememberEntitiesShardStore.GetEntities => @@ -260,11 +259,10 @@ private[pekko] final class DDataRememberEntitiesShardStore( next(allUpdates) } - private def loadAllEntities(): Unit = { + private def loadAllEntities(): Unit = (0 until numberOfKeys).toSet[Int].foreach { i => val key = keys(i) replicator ! Get(key, readMajority, Some(i)) } - } } diff --git a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/internal/EntityPassivationStrategy.scala b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/internal/EntityPassivationStrategy.scala index f51df8aa4d5..066d67cf104 100644 --- a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/internal/EntityPassivationStrategy.scala +++ b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/internal/EntityPassivationStrategy.scala @@ -36,7 +36,7 @@ private[pekko] object EntityPassivationStrategy { val none: PassivateEntities = immutable.Seq.empty[EntityId] } - def apply(settings: ClusterShardingSettings): EntityPassivationStrategy = { + def apply(settings: ClusterShardingSettings): EntityPassivationStrategy = settings.passivationStrategy match { case ClusterShardingSettings.IdlePassivationStrategy(timeout, interval) => new IdleEntityPassivationStrategy(new IdleCheck(timeout, interval)) @@ -77,7 +77,6 @@ private[pekko] object EntityPassivationStrategy { } case _ => DisabledEntityPassivationStrategy } - } } /** @@ -708,7 +707,7 @@ private[pekko] final class CompositeEntityPassivationStrategy( window.removeIdle(idle.timeout) ++ main.removeIdle(idle.timeout) } - private def maybeAdmitToMain(candidates: PassivateEntities): PassivateEntities = { + private def maybeAdmitToMain(candidates: PassivateEntities): PassivateEntities = if (candidates.nonEmpty) { var passivated: PassivateEntities = PassivateEntities.none candidates.foreach { candidate => @@ -724,7 +723,6 @@ private[pekko] final class CompositeEntityPassivationStrategy( } passivated } else PassivateEntities.none - } private def adaptWindow(): Unit = { val adjustment = windowOptimizer.calculateAdjustment() @@ -838,7 +836,7 @@ private[pekko] final class HillClimbingAdmissionOptimizer( override def updateLimit(newLimit: Int): Unit = adjustSize = adjustMultiplier * newLimit - override def calculateAdjustment(): Double = { + override def calculateAdjustment(): Double = if (accesses >= adjustSize) { val activeRate = activeAccesses.toDouble / accesses val delta = activeRate - previousActiveRate @@ -851,7 +849,6 @@ private[pekko] final class HillClimbingAdmissionOptimizer( activeAccesses = 0 adjustment } else 0.0 - } } /** @@ -925,12 +922,11 @@ private[pekko] object FrequencySketchAdmissionFilter { widthMultiplier: Int, resetMultiplier: Double, depth: Int, - counterBits: Int): AdmissionFilter = { + counterBits: Int): AdmissionFilter = if (depth == 4 && counterBits == 4) new FastFrequencySketchAdmissionFilter(initialCapacity, widthMultiplier, resetMultiplier) else new FrequencySketchAdmissionFilter(initialCapacity, widthMultiplier, resetMultiplier, depth, counterBits) - } } /** diff --git a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/internal/EventSourcedRememberEntitiesCoordinatorStore.scala b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/internal/EventSourcedRememberEntitiesCoordinatorStore.scala index 495e7c696bf..0ac2f0ab9b6 100644 --- a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/internal/EventSourcedRememberEntitiesCoordinatorStore.scala +++ b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/internal/EventSourcedRememberEntitiesCoordinatorStore.scala @@ -125,10 +125,9 @@ private[pekko] final class EventSourcedRememberEntitiesCoordinatorStore( log.warning("Snapshots matching [{}] deletion failure: [{}]", m, reason.getMessage) } - def saveSnapshotWhenNeeded(): Unit = { + def saveSnapshotWhenNeeded(): Unit = if (lastSequenceNr % settings.tuningParameters.snapshotAfter == 0 && lastSequenceNr != 0) { log.debug("Saving snapshot, sequence number [{}]", snapshotSequenceNr) saveSnapshot(State(shards.toSet, writtenMarker)) } - } } diff --git a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/internal/EventSourcedRememberEntitiesShardStore.scala b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/internal/EventSourcedRememberEntitiesShardStore.scala index 1395fd66bf5..7916e1c1e71 100644 --- a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/internal/EventSourcedRememberEntitiesShardStore.scala +++ b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/internal/EventSourcedRememberEntitiesShardStore.scala @@ -107,7 +107,7 @@ private[pekko] final class EventSourcedRememberEntitiesShardStore( (if (stopped.nonEmpty) EntitiesStopped(stopped) :: Nil else Nil) var left = events.size var saveSnap = false - def persistEventsAndHandleComplete(evts: List[StateChange]): Unit = { + def persistEventsAndHandleComplete(evts: List[StateChange]): Unit = persistAll(evts) { _ => left -= 1 saveSnap = saveSnap || isSnapshotNeeded @@ -119,7 +119,6 @@ private[pekko] final class EventSourcedRememberEntitiesShardStore( } } } - } if (left <= maxUpdatesPerWrite) { // optimized when batches are small persistEventsAndHandleComplete(events) @@ -166,18 +165,16 @@ private[pekko] final class EventSourcedRememberEntitiesShardStore( log.debug("Store stopping") } - def saveSnapshotWhenNeeded(): Unit = { + def saveSnapshotWhenNeeded(): Unit = if (isSnapshotNeeded) { saveSnapshot() } - } private def saveSnapshot(): Unit = { log.debug("Saving snapshot, sequence number [{}]", snapshotSequenceNr) saveSnapshot(state) } - private def isSnapshotNeeded = { + private def isSnapshotNeeded = lastSequenceNr % snapshotAfter == 0 && lastSequenceNr != 0 - } } diff --git a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/internal/RememberEntityStarter.scala b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/internal/RememberEntityStarter.scala index 22069ddddeb..d2889c09ac0 100644 --- a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/internal/RememberEntityStarter.scala +++ b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/internal/RememberEntityStarter.scala @@ -123,7 +123,7 @@ private[pekko] final class RememberEntityStarter( entityIds.foreach(entityId => region ! ShardRegion.StartEntity(entityId)) } - private def retryUnacked(): Unit = { + private def retryUnacked(): Unit = if (waitingForAck.nonEmpty) { log.debug("Found [{}] remembered entities waiting for StartEntityAck, retrying", waitingForAck.size) waitingForAck.foreach { id => @@ -132,6 +132,5 @@ private[pekko] final class RememberEntityStarter( region ! ShardRegion.StartEntity(id) } } - } } diff --git a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/protobuf/ClusterShardingMessageSerializer.scala b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/protobuf/ClusterShardingMessageSerializer.scala index 3781d1d71b7..09f7f40db1c 100644 --- a/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/protobuf/ClusterShardingMessageSerializer.scala +++ b/cluster-sharding/src/main/scala/org/apache/pekko/cluster/sharding/protobuf/ClusterShardingMessageSerializer.scala @@ -192,8 +192,8 @@ private[pekko] class ClusterShardingMessageSerializer(val system: ExtendedActorS CurrentRegionsManifest -> { bytes => currentRegionsFromBinary(bytes) }, - StartEntityManifest -> { startEntityFromBinary }, - StartEntityAckManifest -> { startEntityAckFromBinary }, + StartEntityManifest -> startEntityFromBinary, + StartEntityAckManifest -> startEntityAckFromBinary, GetCurrentShardStateManifest -> { _ => GetCurrentShardState }, @@ -360,7 +360,7 @@ private[pekko] class ClusterShardingMessageSerializer(val system: ExtendedActorS state.regionProxies.foreach { ref => builder.addRegionProxies(Serialization.serializedActorPath(ref)) } - state.unallocatedShards.foreach { builder.addUnallocatedShards } + state.unallocatedShards.foreach(builder.addUnallocatedShards) builder.build() } @@ -381,7 +381,7 @@ private[pekko] class ClusterShardingMessageSerializer(val system: ExtendedActorS case (acc, (shardId, regionRef)) => acc.updated(regionRef, acc(regionRef) :+ shardId) } - val proxies: Set[ActorRef] = state.getRegionProxiesList.asScala.iterator.map { resolveActorRef }.to(immutable.Set) + val proxies: Set[ActorRef] = state.getRegionProxiesList.asScala.iterator.map(resolveActorRef).to(immutable.Set) val unallocatedShards: Set[String] = state.getUnallocatedShardsList.asScala.toSet State(shards, regions, proxies, unallocatedShards) @@ -419,7 +419,7 @@ private[pekko] class ClusterShardingMessageSerializer(val system: ExtendedActorS ShardHome(m.getShard, resolveActorRef(m.getRegion)) } - private def shardHomesToProto(sh: ShardHomes): sm.ShardHomes = { + private def shardHomesToProto(sh: ShardHomes): sm.ShardHomes = sm.ShardHomes .newBuilder() .addAllHomes(sh.homes.map { @@ -431,7 +431,6 @@ private[pekko] class ClusterShardingMessageSerializer(val system: ExtendedActorS .build() }.asJava) .build() - } private def shardHomesFromBinary(bytes: Array[Byte]): ShardHomes = { val sh = sm.ShardHomes.parseFrom(bytes) @@ -521,9 +520,8 @@ private[pekko] class ClusterShardingMessageSerializer(val system: ExtendedActorS ClusterShardingStats(stats) } - private def getClusterShardingStatsToProto(evt: GetClusterShardingStats): sm.GetClusterShardingStats = { + private def getClusterShardingStatsToProto(evt: GetClusterShardingStats): sm.GetClusterShardingStats = sm.GetClusterShardingStats.newBuilder().setTimeoutNanos(evt.timeout.toNanos).build() - } private def getClusterShardingStatsFromBinary(bytes: Array[Byte]): GetClusterShardingStats = { val parsed = sm.GetClusterShardingStats.parseFrom(bytes) @@ -567,22 +565,19 @@ private[pekko] class ClusterShardingMessageSerializer(val system: ExtendedActorS StartEntityAck(sea.getEntityId, sea.getShardId) } - private def shardStateToProto(evt: ShardState): sm.ShardState = { + private def shardStateToProto(evt: ShardState): sm.ShardState = sm.ShardState.newBuilder().setShardId(evt.shardId).addAllEntityIds(evt.entityIds.asJava).build() - } - private def currentShardStateToProto(evt: CurrentShardState): sm.CurrentShardState = { + private def currentShardStateToProto(evt: CurrentShardState): sm.CurrentShardState = sm.CurrentShardState.newBuilder().setShardId(evt.shardId).addAllEntityIds(evt.entityIds.asJava).build() - } private def currentShardStateFromBinary(bytes: Array[Byte]): CurrentShardState = { val parsed = sm.CurrentShardState.parseFrom(bytes) CurrentShardState(parsed.getShardId, parsed.getEntityIdsList.asScala.toSet) } - private def shardStateFromProto(parsed: ClusterShardingMessages.ShardState): ShardState = { + private def shardStateFromProto(parsed: ClusterShardingMessages.ShardState): ShardState = ShardState(parsed.getShardId, parsed.getEntityIdsList.asScala.toSet) - } private def shardStateFromBinary(bytes: Array[Byte]): ShardState = { val parsed = sm.ShardState.parseFrom(bytes) @@ -612,9 +607,8 @@ private[pekko] class ClusterShardingMessageSerializer(val system: ExtendedActorS def deserializeAddress(address: sm.Address): Address = Address(address.getProtocol, address.getSystem, address.getHostname, address.getPort) - private def resolveActorRef(path: String): ActorRef = { + private def resolveActorRef(path: String): ActorRef = system.provider.resolveActorRef(path) - } private def compress(msg: MessageLite): Array[Byte] = { val bos = new ByteArrayOutputStream(BufferSize) diff --git a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sbr/RandomizedBrainResolverIntegrationSpec.scala b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sbr/RandomizedBrainResolverIntegrationSpec.scala index 0672f412232..30012438f5a 100644 --- a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sbr/RandomizedBrainResolverIntegrationSpec.scala +++ b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sbr/RandomizedBrainResolverIntegrationSpec.scala @@ -129,10 +129,9 @@ class RandomizedSplitBrainResolverIntegrationSpec } } - override def afterEach(): Unit = { + override def afterEach(): Unit = if (disposableSys ne null) disposableSys.shutdownSys() - } class DisposableSys(scenario: Scenario) { @@ -169,9 +168,8 @@ class RandomizedSplitBrainResolverIntegrationSpec lazy val region = ClusterSharding(sys).shardRegion(s"Entity-$c") - def shutdownSys(): Unit = { + def shutdownSys(): Unit = TestKit.shutdownActorSystem(sys, 10.seconds, verifySystemShutdown = true) - } def gremlinControllerProxy(at: RoleName): ActorRef = { system.actorSelection(node(at) / "user" / s"gremlinControllerProxy-$c") ! Identify(None) @@ -225,28 +223,26 @@ class RandomizedSplitBrainResolverIntegrationSpec } } - def createSingleton(): ActorRef = { + def createSingleton(): ActorRef = sys.actorOf( ClusterSingletonManager.props( singletonProps = SingletonActor.props(singletonRegistry), terminationMessage = PoisonPill, settings = ClusterSingletonManagerSettings(system)), name = "singletonRegistry") - } - def startSharding(): Unit = { + def startSharding(): Unit = ClusterSharding(sys).start( typeName = s"Entity-$c", entityProps = SingletonActor.props(shardingRegistry), settings = ClusterShardingSettings(system), extractEntityId = SingletonActor.extractEntityId, extractShardId = SingletonActor.extractShardId) - } def verify(): Unit = { val nodes = roles.take(scenario.numberOfNodes) - def sendToSharding(expectReply: Boolean): Unit = { + def sendToSharding(expectReply: Boolean): Unit = runOn(nodes: _*) { if (!Cluster(sys).isTerminated) { val probe = TestProbe()(sys) @@ -257,7 +253,6 @@ class RandomizedSplitBrainResolverIntegrationSpec } } } - } runOn(nodes: _*) { log.info("Running {} {} in round {}", myself.name, Cluster(sys).selfUniqueAddress, c) @@ -413,7 +408,7 @@ class RandomizedSplitBrainResolverIntegrationSpec "SplitBrainResolver with lease" must { - for (scenario <- scenarios) { + for (scenario <- scenarios) scenario.toString taggedAs LongRunningTest in { // temporarily disabled for aeron-udp in multi-node: https://github.com/akka/akka/pull/30706/ val arteryConfig = system.settings.config.getConfig("pekko.remote.artery") @@ -423,7 +418,6 @@ class RandomizedSplitBrainResolverIntegrationSpec } DisposableSys(scenario).verify() } - } } } diff --git a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sbr/SbrTestLeaseActor.scala b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sbr/SbrTestLeaseActor.scala index ee397cc1c09..eaefcfba536 100644 --- a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sbr/SbrTestLeaseActor.scala +++ b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sbr/SbrTestLeaseActor.scala @@ -120,16 +120,14 @@ class SbrTestLeaseActorClient(settings: LeaseSettings, system: ExtendedActorSyst def setActorLeaseRef(ref: ActorRef): Unit = _leaseRef.set(ref) - override def acquire(): Future[Boolean] = { + override def acquire(): Future[Boolean] = (leaseRef ? Acquire(settings.ownerName)).mapTo[Boolean] - } override def acquire(leaseLostCallback: Option[Throwable] => Unit): Future[Boolean] = acquire() - override def release(): Future[Boolean] = { + override def release(): Future[Boolean] = (leaseRef ? Release(settings.ownerName)).mapTo[Boolean] - } override def checkLease(): Boolean = false } diff --git a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sbr/SplitBrainResolverIntegrationSpec.scala b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sbr/SplitBrainResolverIntegrationSpec.scala index 9bd9bba49fc..dca54a8b563 100644 --- a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sbr/SplitBrainResolverIntegrationSpec.scala +++ b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sbr/SplitBrainResolverIntegrationSpec.scala @@ -101,10 +101,9 @@ class SplitBrainResolverIntegrationSpec override def initialParticipants = roles.size - override def afterEach(): Unit = { + override def afterEach(): Unit = if (disposableSys ne null) disposableSys.shutdownSys() - } // counter for unique naming for each test var c = 0 @@ -163,9 +162,8 @@ class SplitBrainResolverIntegrationSpec lazy val region = ClusterSharding(sys).shardRegion(s"Entity-$c") - def shutdownSys(): Unit = { + def shutdownSys(): Unit = TestKit.shutdownActorSystem(sys, 10.seconds, verifySystemShutdown = true) - } def gremlinControllerProxy(at: RoleName): ActorRef = { system.actorSelection(node(at) / "user" / s"gremlinControllerProxy-$c") ! Identify(None) @@ -220,23 +218,21 @@ class SplitBrainResolverIntegrationSpec } } - def createSingleton(): ActorRef = { + def createSingleton(): ActorRef = sys.actorOf( ClusterSingletonManager.props( singletonProps = SingletonActor.props(singletonRegistry), terminationMessage = PoisonPill, settings = ClusterSingletonManagerSettings(system)), name = "singletonRegistry") - } - def startSharding(): Unit = { + def startSharding(): Unit = ClusterSharding(sys).start( typeName = s"Entity-$c", entityProps = SingletonActor.props(shardingRegistry), settings = ClusterShardingSettings(system), extractEntityId = SingletonActor.extractEntityId, extractShardId = SingletonActor.extractShardId) - } def verify(): Unit = { val side1 = roles.take(scenario.side1Size) @@ -436,10 +432,9 @@ class SplitBrainResolverIntegrationSpec val activeStrategy: String = cfg.getString("pekko.cluster.split-brain-resolver.active-strategy") - override def toString: String = { + override def toString: String = s"$expected when using $activeStrategy and side1=$side1Size and side2=$side2Size" + (if (dcDecider ne defaultDcDecider) "with multi-DC" else "") - } def usingLease: Boolean = activeStrategy.contains("lease") } @@ -467,7 +462,7 @@ class SplitBrainResolverIntegrationSpec "Cluster SplitBrainResolver" must { - for (scenario <- scenarios) { + for (scenario <- scenarios) scenario.toString taggedAs LongRunningTest in { // temporarily disabled for aeron-udp in multi-node: https://github.com/akka/akka/pull/30706/ val arteryConfig = system.settings.config.getConfig("pekko.remote.artery") @@ -477,7 +472,6 @@ class SplitBrainResolverIntegrationSpec } DisposableSys(scenario).verify() } - } } } diff --git a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardCoordinatorDowning2Spec.scala b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardCoordinatorDowning2Spec.scala index d099c9719f2..d0a78f9d48b 100644 --- a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardCoordinatorDowning2Spec.scala +++ b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardCoordinatorDowning2Spec.scala @@ -96,14 +96,13 @@ abstract class ClusterShardCoordinatorDowning2Spec(multiNodeConfig: ClusterShard import ClusterShardCoordinatorDowning2Spec._ - def startSharding(): Unit = { + def startSharding(): Unit = startSharding( system, typeName = "Entity", entityProps = Props[Entity](), extractEntityId = extractEntityId, extractShardId = extractShardId) - } lazy val region = ClusterSharding(system).shardRegion("Entity") diff --git a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardCoordinatorDowningSpec.scala b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardCoordinatorDowningSpec.scala index 10119414b17..58f112920e8 100644 --- a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardCoordinatorDowningSpec.scala +++ b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardCoordinatorDowningSpec.scala @@ -99,14 +99,13 @@ abstract class ClusterShardCoordinatorDowningSpec(multiNodeConfig: ClusterShardC import ClusterShardCoordinatorDowningSpec._ - def startSharding(): Unit = { + def startSharding(): Unit = startSharding( system, typeName = "Entity", entityProps = Props[Entity](), extractEntityId = extractEntityId, extractShardId = extractShardId) - } lazy val region = ClusterSharding(system).shardRegion("Entity") diff --git a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingCustomShardAllocationSpec.scala b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingCustomShardAllocationSpec.scala index 0dd4c88bed9..4deaac67f7c 100644 --- a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingCustomShardAllocationSpec.scala +++ b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingCustomShardAllocationSpec.scala @@ -42,7 +42,7 @@ object ClusterShardingCustomShardAllocationSpec { useRegion = Some(region) sender() ! UseRegionAck case AllocateReq => - useRegion.foreach { sender() ! _ } + useRegion.foreach(sender() ! _) case RebalanceShards(shards) => rebalance = shards sender() ! RebalanceShardsAck @@ -57,15 +57,13 @@ object ClusterShardingCustomShardAllocationSpec { override def allocateShard( requester: ActorRef, shardId: ShardRegion.ShardId, - currentShardAllocations: Map[ActorRef, immutable.IndexedSeq[ShardRegion.ShardId]]): Future[ActorRef] = { + currentShardAllocations: Map[ActorRef, immutable.IndexedSeq[ShardRegion.ShardId]]): Future[ActorRef] = (ref ? AllocateReq).mapTo[ActorRef] - } override def rebalance( currentShardAllocations: Map[ActorRef, immutable.IndexedSeq[ShardRegion.ShardId]], - rebalanceInProgress: Set[ShardRegion.ShardId]): Future[Set[ShardRegion.ShardId]] = { + rebalanceInProgress: Set[ShardRegion.ShardId]): Future[Set[ShardRegion.ShardId]] = (ref ? RebalanceReq).mapTo[Set[String]] - } } } @@ -108,7 +106,7 @@ abstract class ClusterShardingCustomShardAllocationSpec(multiNodeConfig: Cluster import ClusterShardingCustomShardAllocationSpec._ import multiNodeConfig._ - def join(from: RoleName, to: RoleName): Unit = { + def join(from: RoleName, to: RoleName): Unit = join( from, to, @@ -119,7 +117,6 @@ abstract class ClusterShardingCustomShardAllocationSpec(multiNodeConfig: Cluster extractEntityId = MultiNodeClusterShardingSpec.intExtractEntityId, extractShardId = MultiNodeClusterShardingSpec.intExtractShardId, allocationStrategy = TestAllocationStrategy(allocator))) - } lazy val region = ClusterSharding(system).shardRegion("Entity") diff --git a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingFailureSpec.scala b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingFailureSpec.scala index 1632d82b41d..94bc88446a1 100644 --- a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingFailureSpec.scala +++ b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingFailureSpec.scala @@ -111,7 +111,7 @@ abstract class ClusterShardingFailureSpec(multiNodeConfig: ClusterShardingFailur import ClusterShardingFailureSpec._ import multiNodeConfig._ - def join(from: RoleName, to: RoleName): Unit = { + def join(from: RoleName, to: RoleName): Unit = join( from, to, @@ -121,7 +121,6 @@ abstract class ClusterShardingFailureSpec(multiNodeConfig: ClusterShardingFailur entityProps = Props[Entity](), extractEntityId = extractEntityId, extractShardId = extractShardId)) - } lazy val region = ClusterSharding(system).shardRegion("Entity") diff --git a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingGetStatsSpec.scala b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingGetStatsSpec.scala index ba7cb5cea56..bb2f621d4b2 100644 --- a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingGetStatsSpec.scala +++ b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingGetStatsSpec.scala @@ -66,7 +66,7 @@ abstract class ClusterShardingGetStatsSpec extends MultiNodeClusterShardingSpec( import ClusterShardingGetStatsSpecConfig._ import MultiNodeClusterShardingSpec.PingPongActor - def startShard(): ActorRef = { + def startShard(): ActorRef = startSharding( system, typeName = shardTypeName, @@ -74,7 +74,6 @@ abstract class ClusterShardingGetStatsSpec extends MultiNodeClusterShardingSpec( settings = settings.withRole("shard"), extractEntityId = extractEntityId, extractShardId = extractShardId) - } lazy val region = ClusterSharding(system).shardRegion(shardTypeName) diff --git a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingGracefulShutdownSpec.scala b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingGracefulShutdownSpec.scala index b86fb8c1258..af05297229d 100644 --- a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingGracefulShutdownSpec.scala +++ b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingGracefulShutdownSpec.scala @@ -112,9 +112,9 @@ abstract class ClusterShardingGracefulShutdownSpec(multiNodeConfig: ClusterShard // Make sure the 'cluster-sharding-shutdown-region' phase takes at least 40 seconds, // to validate region shutdown completion is propagated immediately and not postponed // until when the cluster member leaves - CoordinatedShutdown(system).addTask("cluster-sharding-shutdown-region", "postpone-actual-stop")(() => { + CoordinatedShutdown(system).addTask("cluster-sharding-shutdown-region", "postpone-actual-stop") { () => pekko.pattern.after(40.seconds)(Future.successful(Done)) - }) + } CoordinatedShutdown(system).run(CoordinatedShutdown.unknownReason) } diff --git a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingLeavingSpec.scala b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingLeavingSpec.scala index 408de114507..e432c7ca62a 100644 --- a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingLeavingSpec.scala +++ b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingLeavingSpec.scala @@ -100,14 +100,13 @@ abstract class ClusterShardingLeavingSpec(multiNodeConfig: ClusterShardingLeavin import ClusterShardingLeavingSpec._ import multiNodeConfig._ - def startSharding(): Unit = { + def startSharding(): Unit = startSharding( system, typeName = "Entity", entityProps = Props[Entity](), extractEntityId = extractEntityId, extractShardId = extractShardId) - } lazy val region = ClusterSharding(system).shardRegion("Entity") diff --git a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingMinMembersSpec.scala b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingMinMembersSpec.scala index 2f565a12c25..7549ede24d4 100644 --- a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingMinMembersSpec.scala +++ b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingMinMembersSpec.scala @@ -60,7 +60,7 @@ abstract class ClusterShardingMinMembersSpec(multiNodeConfig: ClusterShardingMin import MultiNodeClusterShardingSpec.ShardedEntity import multiNodeConfig._ - def startSharding(): Unit = { + def startSharding(): Unit = startSharding( system, typeName = "Entity", @@ -69,7 +69,6 @@ abstract class ClusterShardingMinMembersSpec(multiNodeConfig: ClusterShardingMin extractShardId = MultiNodeClusterShardingSpec.intExtractShardId, allocationStrategy = ShardAllocationStrategy.leastShardAllocationStrategy(absoluteLimit = 2, relativeLimit = 1.0), handOffStopMessage = ShardedEntity.Stop) - } lazy val region = ClusterSharding(system).shardRegion("Entity") diff --git a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingRegistrationCoordinatedShutdownSpec.scala b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingRegistrationCoordinatedShutdownSpec.scala index 63bd09dee23..1db8dc06b2b 100644 --- a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingRegistrationCoordinatedShutdownSpec.scala +++ b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingRegistrationCoordinatedShutdownSpec.scala @@ -63,13 +63,13 @@ abstract class ClusterShardingRegistrationCoordinatedShutdownSpec val csTaskDone = TestProbe() runOn(third) { - CoordinatedShutdown(system).addTask(CoordinatedShutdown.PhaseBeforeClusterShutdown, "test")(() => { + CoordinatedShutdown(system).addTask(CoordinatedShutdown.PhaseBeforeClusterShutdown, "test") { () => Thread.sleep(200) region ! 1 expectMsg(1) csTaskDone.ref ! Done Future.successful(Done) - }) + } } diff --git a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingRememberEntitiesNewExtractorSpec.scala b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingRememberEntitiesNewExtractorSpec.scala index 1614d401458..659dfe72467 100644 --- a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingRememberEntitiesNewExtractorSpec.scala +++ b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingRememberEntitiesNewExtractorSpec.scala @@ -124,7 +124,7 @@ abstract class ClusterShardingRememberEntitiesNewExtractorSpec( val typeName = "Entity" - def startShardingWithExtractor1(): Unit = { + def startShardingWithExtractor1(): Unit = startSharding( system, typeName = typeName, @@ -132,9 +132,8 @@ abstract class ClusterShardingRememberEntitiesNewExtractorSpec( settings = settings.withRole("sharding"), extractEntityId = extractEntityId, extractShardId = extractShardId1) - } - def startShardingWithExtractor2(sys: ActorSystem, probe: ActorRef): Unit = { + def startShardingWithExtractor2(sys: ActorSystem, probe: ActorRef): Unit = startSharding( sys, typeName = typeName, @@ -142,7 +141,6 @@ abstract class ClusterShardingRememberEntitiesNewExtractorSpec( settings = ClusterShardingSettings(sys).withRememberEntities(config.rememberEntities).withRole("sharding"), extractEntityId = extractEntityId, extractShardId = extractShardId2) - } def region(sys: ActorSystem = system) = ClusterSharding(sys).shardRegion(typeName) diff --git a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingRememberEntitiesSpec.scala b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingRememberEntitiesSpec.scala index a24c33d3061..ba2bf3083a3 100644 --- a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingRememberEntitiesSpec.scala +++ b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingRememberEntitiesSpec.scala @@ -128,7 +128,7 @@ abstract class ClusterShardingRememberEntitiesSpec(multiNodeConfig: ClusterShard val dataType = "Entity" - def startSharding(sys: ActorSystem, probe: ActorRef): ActorRef = { + def startSharding(sys: ActorSystem, probe: ActorRef): ActorRef = startSharding( sys, typeName = dataType, @@ -136,7 +136,6 @@ abstract class ClusterShardingRememberEntitiesSpec(multiNodeConfig: ClusterShard settings = ClusterShardingSettings(sys).withRememberEntities(multiNodeConfig.rememberEntities), extractEntityId = extractEntityId, extractShardId = extractShardId) - } lazy val region = ClusterSharding(system).shardRegion(dataType) diff --git a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingSingleShardPerEntitySpec.scala b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingSingleShardPerEntitySpec.scala index bef6f9a3619..6cff0671260 100644 --- a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingSingleShardPerEntitySpec.scala +++ b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingSingleShardPerEntitySpec.scala @@ -48,7 +48,7 @@ abstract class ClusterShardingSingleShardPerEntitySpec import ClusterShardingSingleShardPerEntitySpecConfig._ import MultiNodeClusterShardingSpec.ShardedEntity - def join(from: RoleName, to: RoleName): Unit = { + def join(from: RoleName, to: RoleName): Unit = join( from, to, @@ -58,7 +58,6 @@ abstract class ClusterShardingSingleShardPerEntitySpec entityProps = Props[ShardedEntity](), extractEntityId = MultiNodeClusterShardingSpec.intExtractEntityId, extractShardId = MultiNodeClusterShardingSpec.intExtractShardId)) - } lazy val region = ClusterSharding(system).shardRegion("Entity") diff --git a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingSpec.scala b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingSpec.scala index 5adffa7f22d..013ae0d8383 100644 --- a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingSpec.scala +++ b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/ClusterShardingSpec.scala @@ -294,9 +294,8 @@ abstract class ClusterShardingSpec(multiNodeConfig: ClusterShardingSpecConfig) import ClusterShardingSpec._ import multiNodeConfig._ - def join(from: RoleName, to: RoleName): Unit = { + def join(from: RoleName, to: RoleName): Unit = join(from, to, createCoordinator()) - } lazy val replicator = system.actorOf( Replicator.props(ReplicatorSettings(system).withGossipInterval(1.second).withMaxDeltaElements(10)), @@ -307,9 +306,8 @@ abstract class ClusterShardingSpec(multiNodeConfig: ClusterShardingSpecConfig) new DDataRememberEntitiesProvider(typeName, settings, majorityMinCap, replicator) } - def eventSourcedRememberEntitiesProvider(typeName: String, settings: ClusterShardingSettings) = { + def eventSourcedRememberEntitiesProvider(typeName: String, settings: ClusterShardingSettings) = new EventSourcedRememberEntitiesProvider(typeName, settings) - } def createCoordinator(): Unit = { @@ -995,9 +993,8 @@ abstract class ClusterShardingSpec(multiNodeConfig: ClusterShardingSpecConfig) "ensure rebalance restarts shards" in within(50.seconds) { runOn(fourth) { - for (i <- 2 to 12) { + for (i <- 2 to 12) rebalancingPersistentRegion ! EntityEnvelope(i, Increment) - } for (i <- 2 to 12) { rebalancingPersistentRegion ! Get(i) diff --git a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/MultiDcClusterShardingSpec.scala b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/MultiDcClusterShardingSpec.scala index f944b109804..b783e35bb3a 100644 --- a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/MultiDcClusterShardingSpec.scala +++ b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/MultiDcClusterShardingSpec.scala @@ -92,7 +92,7 @@ abstract class MultiDcClusterShardingSpec import MultiDcClusterShardingSpec._ import MultiDcClusterShardingSpecConfig._ - def join(from: RoleName, to: RoleName): Unit = { + def join(from: RoleName, to: RoleName): Unit = join( from, to, { @@ -106,29 +106,26 @@ abstract class MultiDcClusterShardingSpec } } }) - } - def startSharding(): Unit = { + def startSharding(): Unit = startSharding( system, typeName = "Entity", entityProps = Props[Entity](), extractEntityId = extractEntityId, extractShardId = extractShardId) - } lazy val region = ClusterSharding(system).shardRegion("Entity") private def fillAddress(a: Address): Address = if (a.hasLocalScope) Cluster(system).selfAddress else a - private def assertCurrentRegions(expected: Set[Address]): Unit = { + private def assertCurrentRegions(expected: Set[Address]): Unit = awaitAssert({ val p = TestProbe() region.tell(GetCurrentRegions, p.ref) p.expectMsg(CurrentRegions(expected)) }, 10.seconds) - } "Cluster sharding in multi data center cluster" must { "join cluster" in within(20.seconds) { @@ -137,11 +134,10 @@ abstract class MultiDcClusterShardingSpec join(third, first) join(fourth, first) - awaitAssert({ - withClue(s"Members: ${Cluster(system).state}") { - Cluster(system).state.members.size should ===(4) - Cluster(system).state.members.unsorted.map(_.status) should ===(Set(MemberStatus.Up)) - } + awaitAssert( + withClue(s"Members: ${Cluster(system).state}") { + Cluster(system).state.members.size should ===(4) + Cluster(system).state.members.unsorted.map(_.status) should ===(Set(MemberStatus.Up)) }, 10.seconds) runOn(first, second) { diff --git a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/MultiNodeClusterShardingConfig.scala b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/MultiNodeClusterShardingConfig.scala index e49a149dd4a..6b2c0fda216 100644 --- a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/MultiNodeClusterShardingConfig.scala +++ b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/MultiNodeClusterShardingConfig.scala @@ -26,13 +26,12 @@ object MultiNodeClusterShardingConfig { private[sharding] def testNameFromCallStack(classToStartFrom: Class[_]): String = { - def isAbstractClass(className: String): Boolean = { - try { + def isAbstractClass(className: String): Boolean = + try Modifier.isAbstract(Class.forName(className).getModifiers) - } catch { + catch { case _: Throwable => false // yes catch everything, best effort check } - } val startFrom = classToStartFrom.getName val filteredStack = Thread.currentThread.getStackTrace.iterator @@ -59,12 +58,11 @@ object MultiNodeClusterShardingConfig { * replacing invalid characters. `name` may for example be a fully qualified * class name and then the short class name will be used. */ - def scrubActorSystemName(name: String): String = { + def scrubActorSystemName(name: String): String = name .replaceFirst("""^.*\.""", "") // drop package name .replaceAll("""\$\$?\w+""", "") // drop scala anonymous functions/classes .replaceAll("[^a-zA-Z_0-9]", "_") - } def persistenceConfig(targetDir: String): Config = ConfigFactory.parseString(s""" diff --git a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/MultiNodeClusterShardingSpec.scala b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/MultiNodeClusterShardingSpec.scala index 11ab681f952..605ffed9d6c 100644 --- a/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/MultiNodeClusterShardingSpec.scala +++ b/cluster-sharding/src/multi-jvm/scala/org/apache/pekko/cluster/sharding/MultiNodeClusterShardingSpec.scala @@ -159,8 +159,7 @@ abstract class MultiNodeClusterShardingSpec(val config: MultiNodeClusterSharding extractEntityId: ShardRegion.ExtractEntityId = intExtractEntityId, extractShardId: ShardRegion.ExtractShardId = intExtractShardId, allocationStrategy: ShardAllocationStrategy = defaultShardAllocationStrategy, - handOffStopMessage: Any = PoisonPill): ActorRef = { - + handOffStopMessage: Any = PoisonPill): ActorRef = ClusterSharding(sys).start( typeName, entityProps, @@ -169,16 +168,14 @@ abstract class MultiNodeClusterShardingSpec(val config: MultiNodeClusterSharding extractShardId, allocationStrategy, handOffStopMessage) - } protected def startProxy( sys: ActorSystem, typeName: String, role: Option[String], extractEntityId: ShardRegion.ExtractEntityId, - extractShardId: ShardRegion.ExtractShardId): ActorRef = { + extractShardId: ShardRegion.ExtractShardId): ActorRef = ClusterSharding(sys).startProxy(typeName, role, extractEntityId, extractShardId) - } protected def isDdataMode = mode == ClusterShardingSettings.StateStoreModeDData protected def persistenceIsNeeded: Boolean = diff --git a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/ClusterShardingInternalsSpec.scala b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/ClusterShardingInternalsSpec.scala index 749d75e56f6..b9d8dbf7b08 100644 --- a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/ClusterShardingInternalsSpec.scala +++ b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/ClusterShardingInternalsSpec.scala @@ -31,9 +31,8 @@ object ClusterShardingInternalsSpec { case _ => } - override def postStop(): Unit = { + override def postStop(): Unit = super.postStop() - } } } diff --git a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/CoordinatedShutdownShardingSpec.scala b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/CoordinatedShutdownShardingSpec.scala index c232989b8e9..deb3d406669 100644 --- a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/CoordinatedShutdownShardingSpec.scala +++ b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/CoordinatedShutdownShardingSpec.scala @@ -100,8 +100,9 @@ class CoordinatedShutdownShardingSpec extends PekkoSpec(CoordinatedShutdownShard } // Using region 2 as it is not shutdown in either test - def pingEntities(): Unit = { - awaitAssert({ + def pingEntities(): Unit = + awaitAssert( + { val p1 = TestProbe()(sys2) region2.tell(1, p1.ref) p1.expectMsg(1.seconds, 1) @@ -112,7 +113,6 @@ class CoordinatedShutdownShardingSpec extends PekkoSpec(CoordinatedShutdownShard region2.tell(3, p3.ref) p3.expectMsg(1.seconds, 3) }, 10.seconds) - } "Sharding and CoordinatedShutdown" must { "init cluster" in { diff --git a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/LeastShardAllocationStrategyRandomizedSpec.scala b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/LeastShardAllocationStrategyRandomizedSpec.scala index a72f964f4d7..3ac0a8415b5 100644 --- a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/LeastShardAllocationStrategyRandomizedSpec.scala +++ b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/LeastShardAllocationStrategyRandomizedSpec.scala @@ -39,12 +39,11 @@ class LeastShardAllocationStrategyRandomizedSpec extends PekkoSpec("pekko.loglev @volatile var clusterMembers: SortedSet[Member] = SortedSet.empty - def createAllocations(countPerRegion: Map[ActorRef, Int]): Map[ActorRef, immutable.IndexedSeq[ShardId]] = { + def createAllocations(countPerRegion: Map[ActorRef, Int]): Map[ActorRef, immutable.IndexedSeq[ShardId]] = countPerRegion.map { case (region, count) => region -> (1 to count).map(n => ("00" + n.toString).takeRight(3)).map(n => s"${region.path.name}-$n").toVector } - } private val strategyWithoutLimits = strategyWithFakeCluster() @@ -68,7 +67,7 @@ class LeastShardAllocationStrategyRandomizedSpec extends PekkoSpec("pekko.loglev allocationStrategy: ShardAllocationStrategy, maxRegions: Int, maxShardsPerRegion: Int, - expectedMaxSteps: Int): Unit = { + expectedMaxSteps: Int): Unit = (1 to iterationsPerTest).foreach { _ => iteration += 1 val numberOfRegions = rnd.nextInt(maxRegions) + 1 @@ -84,7 +83,6 @@ class LeastShardAllocationStrategyRandomizedSpec extends PekkoSpec("pekko.loglev } regions.foreach(system.stop) } - } @tailrec private def testRebalance( allocationStrategy: ShardAllocationStrategy, diff --git a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/LeastShardAllocationStrategySpec.scala b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/LeastShardAllocationStrategySpec.scala index 17635886999..945d3cd37c9 100644 --- a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/LeastShardAllocationStrategySpec.scala +++ b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/LeastShardAllocationStrategySpec.scala @@ -60,20 +60,17 @@ object LeastShardAllocationStrategySpec { } } - def countShardsPerRegion(newAllocations: Map[ActorRef, immutable.IndexedSeq[ShardId]]): Vector[Int] = { + def countShardsPerRegion(newAllocations: Map[ActorRef, immutable.IndexedSeq[ShardId]]): Vector[Int] = newAllocations.valuesIterator.map(_.size).toVector - } - def countShards(allocations: Map[ActorRef, immutable.IndexedSeq[ShardId]]): Int = { + def countShards(allocations: Map[ActorRef, immutable.IndexedSeq[ShardId]]): Int = countShardsPerRegion(allocations).sum - } def allocationCountsAfterRebalance( allocationStrategy: ShardAllocationStrategy, allocations: Map[ActorRef, immutable.IndexedSeq[ShardId]], - rebalance: Set[ShardId]): Vector[Int] = { + rebalance: Set[ShardId]): Vector[Int] = countShardsPerRegion(afterRebalance(allocationStrategy, allocations, rebalance)) - } final class DummyActorRef(val path: ActorPath) extends MinimalActorRef { override def provider: ActorRefProvider = ??? @@ -102,12 +99,11 @@ class LeastShardAllocationStrategySpec extends PekkoSpec { private val shards = (1 to 999).map(n => ("00" + n.toString).takeRight(3)) - def createAllocations(aCount: Int, bCount: Int = 0, cCount: Int = 0): Map[ActorRef, Vector[String]] = { + def createAllocations(aCount: Int, bCount: Int = 0, cCount: Int = 0): Map[ActorRef, Vector[String]] = Map( regionA -> shards.take(aCount).toVector, regionB -> shards.slice(aCount, aCount + bCount).toVector, regionC -> shards.slice(aCount + bCount, aCount + bCount + cCount).toVector) - } private val strategyWithoutLimits = strategyWithFakeCluster(absoluteLimit = 1000, relativeLimit = 1.0) diff --git a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/PersistentShardingMigrationSpec.scala b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/PersistentShardingMigrationSpec.scala index 2c20e1cf3c7..5ab602b9984 100644 --- a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/PersistentShardingMigrationSpec.scala +++ b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/PersistentShardingMigrationSpec.scala @@ -182,17 +182,15 @@ class PersistentShardingMigrationSpec extends PekkoSpec(PersistentShardingMigrat extractEntityId, extractShardId(rememberedEntitiesProbe.ref)) f(system, region, rememberedEntitiesProbe) - } finally { + } finally Await.ready(system.terminate(), 20.seconds) - } } - def assertRegionRegistrationComplete(region: ActorRef): Unit = { + def assertRegionRegistrationComplete(region: ActorRef): Unit = awaitAssert { region ! ShardRegion.GetCurrentRegions expectMsgType[CurrentRegions].regions should have size 1 } - } } } diff --git a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/RememberEntitiesBatchedUpdatesSpec.scala b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/RememberEntitiesBatchedUpdatesSpec.scala index b98d21da6a0..ccfc1550857 100644 --- a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/RememberEntitiesBatchedUpdatesSpec.scala +++ b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/RememberEntitiesBatchedUpdatesSpec.scala @@ -44,9 +44,8 @@ object RememberEntitiesBatchedUpdatesSpec { case "ping" => } - override def postStop(): Unit = { + override def postStop(): Unit = probe ! Stopped(self.path.name.toInt) - } } def config = ConfigFactory.parseString(""" diff --git a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/RememberEntitiesFailureSpec.scala b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/RememberEntitiesFailureSpec.scala index 27c0029c919..b990d2d8ec4 100644 --- a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/RememberEntitiesFailureSpec.scala +++ b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/RememberEntitiesFailureSpec.scala @@ -241,9 +241,8 @@ class RememberEntitiesFailureSpec } system.stop(sharding) - } finally { + } finally failShardGetEntities = Map.empty - } } s"recover when shard storing a start event fails $wayToFail" in { diff --git a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/RememberEntitiesShardIdExtractorChangeSpec.scala b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/RememberEntitiesShardIdExtractorChangeSpec.scala index 45dbacf1511..e79f5391507 100644 --- a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/RememberEntitiesShardIdExtractorChangeSpec.scala +++ b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/RememberEntitiesShardIdExtractorChangeSpec.scala @@ -143,17 +143,15 @@ class RememberEntitiesShardIdExtractorChangeSpec try { val region = ClusterSharding(system).start(TypeName, Props(new PA()), extractEntityId, extractShardId) f(system, region) - } finally { + } finally Await.ready(system.terminate(), 20.seconds) - } } - def assertRegionRegistrationComplete(region: ActorRef): Unit = { + def assertRegionRegistrationComplete(region: ActorRef): Unit = awaitAssert { region ! ShardRegion.GetCurrentRegions expectMsgType[CurrentRegions].regions should have size 1 } - } } } diff --git a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/RemoveInternalClusterShardingDataSpec.scala b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/RemoveInternalClusterShardingDataSpec.scala index 15435c26700..45cde6cf841 100644 --- a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/RemoveInternalClusterShardingDataSpec.scala +++ b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/RemoveInternalClusterShardingDataSpec.scala @@ -117,13 +117,11 @@ class RemoveInternalClusterShardingDataSpec List("pekko.persistence.journal.leveldb.dir", "pekko.persistence.snapshot-store.local.dir").map(s => new File(system.settings.config.getString(s))) - override protected def atStartup(): Unit = { + override protected def atStartup(): Unit = storageLocations.foreach(dir => if (dir.exists) FileUtils.deleteDirectory(dir)) - } - override protected def afterTermination(): Unit = { + override protected def afterTermination(): Unit = storageLocations.foreach(dir => if (dir.exists) FileUtils.deleteDirectory(dir)) - } // same persistenceId as is used by ShardCoordinator def persistenceId(typeName: String): String = s"/sharding/${typeName}Coordinator" diff --git a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/ShardRegionSpec.scala b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/ShardRegionSpec.scala index 95a7df4296b..d326c5b9daf 100644 --- a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/ShardRegionSpec.scala +++ b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/ShardRegionSpec.scala @@ -126,17 +126,14 @@ class ShardRegionSpec extends PekkoSpec(ShardRegionSpec.config) with WithLogCapt private val region1 = startShard(sysA) private val region2 = startShard(sysB) - override protected def atStartup(): Unit = { + override protected def atStartup(): Unit = storageLocation.foreach(dir => if (dir.exists) FileUtils.deleteQuietly(dir)) - } - override def beforeTermination(): Unit = { + override def beforeTermination(): Unit = shutdown(sysB) - } - override protected def afterTermination(): Unit = { + override protected def afterTermination(): Unit = storageLocation.foreach(dir => if (dir.exists) FileUtils.deleteQuietly(dir)) - } def startShard(sys: ActorSystem): ActorRef = ClusterSharding(sys).start( diff --git a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/SupervisionSpec.scala b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/SupervisionSpec.scala index 1075cfae030..47ed93f37f8 100644 --- a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/SupervisionSpec.scala +++ b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/SupervisionSpec.scala @@ -52,13 +52,11 @@ object SupervisionSpec { class PassivatingActor extends Actor with ActorLogging { - override def preStart(): Unit = { + override def preStart(): Unit = log.info("Starting") - } - override def postStop(): Unit = { + override def postStop(): Unit = log.info("Stopping") - } override def receive: Receive = { case "passivate" => diff --git a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/passivation/CompositeSpec.scala b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/passivation/CompositeSpec.scala index 096ba2430b0..48f69c94ce3 100644 --- a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/passivation/CompositeSpec.scala +++ b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/passivation/CompositeSpec.scala @@ -177,9 +177,8 @@ class AdmissionWindowAndFilterSpec // activating a second shard will divide the per-shard limit in two, passivating half of the first shard region ! Envelope(shard = 2, id = 41, message = "F") expectReceived(id = 41, message = "F") - for (id <- List(25, 26, 17, 18, 19, 20, 5, 6, 7, 8)) { + for (id <- List(25, 26, 17, 18, 19, 20, 5, 6, 7, 8)) expectReceived(id = id, message = Stop) - } // shard 1: window: 27-28, main level 0: 9-10, level 1: 11-16 // shard 2: window: 41, main level 0: empty, level 1: empty @@ -244,9 +243,8 @@ class AdmissionFilterNoWindowSpec // activating a second shard will divide the per-shard limit in two, passivating half of the first shard region ! Envelope(shard = 2, id = 21, message = "D") expectReceived(id = 21, message = "D") - for (id <- 11 to 15) { + for (id <- 11 to 15) expectReceived(id = id, message = Stop) - } // shard 1: 16-20, shard 2: 21 expectState(region)(1 -> (16 to 20), 2 -> Set(21)) @@ -336,11 +334,10 @@ class AdaptiveAdmissionWindowSpec region ! Envelope(shard = 1, id = id, message = s"E$i") expectReceived(id = id, message = s"E$i") val previousWindow = IndexedSeq(30, 5, 6, 21, 22, 23, 24, 7) - val passivated = { + val passivated = if (i == 1 && id <= 38) previousWindow(id - 31) else if (id <= 38) id + 2 else id - 8 // window size - } expectReceived(id = passivated, message = Stop) } @@ -446,17 +443,15 @@ class CompositeLimitAdjustmentSpec // activating a second shard will divide the per-shard limit in two, passivating half of the first shard region ! Envelope(shard = 2, id = 41, message = "B") expectReceived(id = 41, message = "B") - for (id <- List(37, 38) ++ (1 to 8)) { + for (id <- List(37, 38) ++ (1 to 8)) expectReceived(id = id, message = Stop) - } expectState(region)(1 -> ((9 to 16) ++ (39 to 40)), 2 -> Set(41)) // reduce the per-region limit from 20 to 10, per-shard limit becomes 5 region ! ShardRegion.SetActiveEntityLimit(10) - for (id <- 39 +: (9 to 12)) { // passivate entities over new limit + for (id <- 39 +: (9 to 12)) // passivate entities over new limit expectReceived(id = id, message = Stop) - } expectState(region)(1 -> ((13 to 16) ++ Set(40)), 2 -> Set(41)) diff --git a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/passivation/LeastFrequentlyUsedSpec.scala b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/passivation/LeastFrequentlyUsedSpec.scala index d8d08803e5f..b37f3510338 100644 --- a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/passivation/LeastFrequentlyUsedSpec.scala +++ b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/passivation/LeastFrequentlyUsedSpec.scala @@ -93,9 +93,8 @@ class LeastFrequentlyUsedSpec // activating a second shard will divide the per-shard limit in two, passivating half of the first shard region ! Envelope(shard = 2, id = 21, message = "B") expectReceived(id = 21, message = "B") - for (id <- Seq(3, 7, 11, 15, 19)) { + for (id <- Seq(3, 7, 11, 15, 19)) expectReceived(id = id, message = Stop) - } // shard 1: frequency 4 = (4, 8, 12, 16, 20) // shard 2: frequency 1 = (21) @@ -130,9 +129,8 @@ class LeastFrequentlyUsedSpec // activating a third shard will divide the per-shard limit in three, passivating entities over the new limits region ! Envelope(shard = 3, id = 31, message = "E") expectReceived(id = 31, message = "E") - for (id <- Seq(4, 8, 22)) { + for (id <- Seq(4, 8, 22)) expectReceived(id = id, message = Stop) - } // shard 1: frequency 4 = (12, 16, 20) // shard 2: frequency 1 = (23, 24), frequency 2 = (21) @@ -227,19 +225,17 @@ class LeastFrequentlyUsedWithDynamicAgingSpec // only one active shard at first // ids 1 and 2 are quite popular initially - for (id <- 1 to 2) { + for (id <- 1 to 2) for (x <- 1 to 5) { region ! Envelope(shard = 1, id = id, message = s"A$x") expectReceived(id = id, message = s"A$x") } - } // ids 3, 4, and 5 are very popular initially - for (id <- 3 to 5) { + for (id <- 3 to 5) for (x <- 1 to 10) { region ! Envelope(shard = 1, id = id, message = s"A$x") expectReceived(id = id, message = s"A$x") } - } // shard 1: age = 0, @5 (5 + 0) = (1, 2), @10 (10 + 0) = (3, 4, 5) expectState(region)(1 -> Set(1, 2, 3, 4, 5)) @@ -357,17 +353,15 @@ class LeastFrequentlyUsedLimitAdjustmentSpec // activating a second shard will divide the per-shard limit in two, passivating half of the first shard region ! Envelope(shard = 2, id = 21, message = "B") expectReceived(id = 21, message = "B") - for (id <- 11 to 15) { + for (id <- 11 to 15) expectReceived(id = id, message = Stop) - } expectState(region)(1 -> (16 to 20), 2 -> Set(21)) // reduce the per-region limit from 10 to 6, per-shard limit becomes 3 region ! ShardRegion.SetActiveEntityLimit(6) - for (id <- 16 to 17) { // passivate entities over new limit + for (id <- 16 to 17) // passivate entities over new limit expectReceived(id = id, message = Stop) - } expectState(region)(1 -> (18 to 20), 2 -> Set(21)) diff --git a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/passivation/LeastRecentlyUsedSpec.scala b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/passivation/LeastRecentlyUsedSpec.scala index 49dbd789b83..1824ef6be51 100644 --- a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/passivation/LeastRecentlyUsedSpec.scala +++ b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/passivation/LeastRecentlyUsedSpec.scala @@ -94,9 +94,8 @@ class LeastRecentlyUsedSpec extends AbstractEntityPassivationSpec(LeastRecentlyU // activating a second shard will divide the per-shard limit in two, passivating half of the first shard region ! Envelope(shard = 2, id = 21, message = "B") expectReceived(id = 21, message = "B") - for (id <- 11 to 15) { + for (id <- 11 to 15) expectReceived(id = id, message = Stop) - } expectState(region)(1 -> (16 to 20), 2 -> Set(21)) @@ -121,9 +120,8 @@ class LeastRecentlyUsedSpec extends AbstractEntityPassivationSpec(LeastRecentlyU // activating a third shard will divide the per-shard limit in three, passivating entities over the new limits region ! Envelope(shard = 3, id = 31, message = "E") expectReceived(id = 31, message = "E") - for (id <- Seq(16, 17, 21)) { + for (id <- Seq(16, 17, 21)) expectReceived(id = id, message = Stop) - } expectState(region)(1 -> Set(18, 19, 20), 2 -> Set(22, 23, 24), 3 -> Set(31)) @@ -227,9 +225,8 @@ class SegmentedLeastRecentlyUsedSpec // activating a second shard will divide the per-shard limit in two, passivating half of the first shard region ! Envelope(shard = 2, id = 21, message = "D") expectReceived(id = 21, message = "D") - for (id <- List(4, 5, 13, 14, 15)) { + for (id <- List(4, 5, 13, 14, 15)) expectReceived(id = id, message = Stop) - } // shard 1: level 0: 16, level 1: 17-20 // shard 2: level 0: 21, level 1: empty @@ -317,17 +314,15 @@ class LeastRecentlyUsedLimitAdjustmentSpec // activating a second shard will divide the per-shard limit in two, passivating half of the first shard region ! Envelope(shard = 2, id = 21, message = "B") expectReceived(id = 21, message = "B") - for (id <- 11 to 15) { + for (id <- 11 to 15) expectReceived(id = id, message = Stop) - } expectState(region)(1 -> (16 to 20), 2 -> Set(21)) // reduce the per-region limit from 10 to 6, per-shard limit becomes 3 region ! ShardRegion.SetActiveEntityLimit(6) - for (id <- 16 to 17) { // passivate entities over new limit + for (id <- 16 to 17) // passivate entities over new limit expectReceived(id = id, message = Stop) - } expectState(region)(1 -> (18 to 20), 2 -> Set(21)) @@ -378,17 +373,15 @@ class SegmentedLeastRecentlyUsedLimitAdjustmentSpec // activating a second shard will divide the per-shard limit in two, passivating half of the first shard region ! Envelope(shard = 2, id = 31, message = "B") expectReceived(id = 31, message = "B") - for (id <- 11 to 20) { + for (id <- 11 to 20) expectReceived(id = id, message = Stop) - } expectState(region)(1 -> (21 to 30), 2 -> Set(31)) // reduce the per-region limit from 20 to 10, per-shard limit becomes 5 region ! ShardRegion.SetActiveEntityLimit(10) - for (id <- 21 to 25) { // passivate entities over new limit + for (id <- 21 to 25) // passivate entities over new limit expectReceived(id = id, message = Stop) - } expectState(region)(1 -> (26 to 30), 2 -> Set(31)) diff --git a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/passivation/MostRecentlyUsedSpec.scala b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/passivation/MostRecentlyUsedSpec.scala index c9203a4049d..39002df97d2 100644 --- a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/passivation/MostRecentlyUsedSpec.scala +++ b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/passivation/MostRecentlyUsedSpec.scala @@ -69,9 +69,8 @@ class MostRecentlyUsedSpec extends AbstractEntityPassivationSpec(MostRecentlyUse // activating a second shard will divide the per-shard limit in two, passivating half of the first shard region ! Envelope(shard = 2, id = 21, message = "B") expectReceived(id = 21, message = "B") - for (id <- Seq(20, 9, 8, 7, 6)) { + for (id <- Seq(20, 9, 8, 7, 6)) expectReceived(id, message = Stop) - } expectState(region)(1 -> Set(1, 2, 3, 4, 5), 2 -> Set(21)) @@ -95,9 +94,8 @@ class MostRecentlyUsedSpec extends AbstractEntityPassivationSpec(MostRecentlyUse // activating a third shard will divide the per-shard limit in three, passivating entities over the new limits region ! Envelope(shard = 3, id = 31, message = "E") expectReceived(id = 31, message = "E") - for (id <- Seq(24, 20, 4)) { + for (id <- Seq(24, 20, 4)) expectReceived(id = id, message = Stop) - } expectState(region)(1 -> Set(1, 2, 3), 2 -> Set(21, 22, 23), 3 -> Set(31)) @@ -220,17 +218,15 @@ class MostRecentlyUsedLimitAdjustmentSpec // activating a second shard will divide the per-shard limit in two, passivating half of the first shard region ! Envelope(shard = 2, id = 21, message = "B") expectReceived(id = 21, message = "B") - for (id <- Seq(20, 9, 8, 7, 6)) { + for (id <- Seq(20, 9, 8, 7, 6)) expectReceived(id, message = Stop) - } expectState(region)(1 -> Set(1, 2, 3, 4, 5), 2 -> Set(21)) // reduce the per-region limit from 10 to 6, per-shard limit becomes 3 region ! ShardRegion.SetActiveEntityLimit(6) - for (id <- Seq(5, 4)) { // passivate entities over new limit + for (id <- Seq(5, 4)) // passivate entities over new limit expectReceived(id = id, message = Stop) - } expectState(region)(1 -> Set(1, 2, 3), 2 -> Set(21)) diff --git a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/passivation/simulator/Simulator.scala b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/passivation/simulator/Simulator.scala index 82a7122ef38..1cf92237525 100644 --- a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/passivation/simulator/Simulator.scala +++ b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/passivation/simulator/Simulator.scala @@ -457,9 +457,8 @@ object Simulator { private def passivateExcessEntities(): immutable.Seq[EntityId] = { val passivated = mutable.ListBuffer.empty[EntityId] - while (nextAccess.size > perShardLimit) { + while (nextAccess.size > perShardLimit) nextAccess.remove(nextAccess.lastKey).foreach(passivated.+=) - } passivated.result() } } diff --git a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/passivation/simulator/SimulatorSettings.scala b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/passivation/simulator/SimulatorSettings.scala index 611f90f7554..e02b10f1e5d 100644 --- a/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/passivation/simulator/SimulatorSettings.scala +++ b/cluster-sharding/src/test/scala/org/apache/pekko/cluster/sharding/passivation/simulator/SimulatorSettings.scala @@ -126,7 +126,7 @@ object SimulatorSettings { counterBits: Int) extends AdmissionFilterSettings - def apply(config: Config): AdmissionFilterSettings = { + def apply(config: Config): AdmissionFilterSettings = lowerCase(config.getString("admission.filter")) match { case "frequency-sketch" => FrequencySketchFilter( @@ -136,7 +136,6 @@ object SimulatorSettings { config.getInt("admission.frequency-sketch.counter-bits")) case _ => NoFilter } - } } sealed trait AdmissionOptimizerSettings @@ -150,7 +149,7 @@ object SimulatorSettings { stepDecay: Double) extends AdmissionOptimizerSettings - def apply(config: Config): AdmissionOptimizerSettings = { + def apply(config: Config): AdmissionOptimizerSettings = lowerCase(config.getString("admission.optimizer")) match { case "hill-climbing" => HillClimbingOptimizer( @@ -160,7 +159,6 @@ object SimulatorSettings { config.getDouble("admission.hill-climbing.step-decay")) case _ => NoOptimizer } - } } } diff --git a/cluster-tools/src/main/scala/org/apache/pekko/cluster/client/ClusterClient.scala b/cluster-tools/src/main/scala/org/apache/pekko/cluster/client/ClusterClient.scala index bd7cfe71f49..a1ce2c761fe 100644 --- a/cluster-tools/src/main/scala/org/apache/pekko/cluster/client/ClusterClient.scala +++ b/cluster-tools/src/main/scala/org/apache/pekko/cluster/client/ClusterClient.scala @@ -415,7 +415,7 @@ final class ClusterClient(settings: ClusterClientSettings) extends Actor with Ac var buffer = MessageBuffer.empty def scheduleRefreshContactsTick(interval: FiniteDuration): Unit = { - refreshContactsTask.foreach { _.cancel() } + refreshContactsTask.foreach(_.cancel()) refreshContactsTask = Some( context.system.scheduler.scheduleWithFixedDelay(interval, interval, self, RefreshContactsTick)) } @@ -423,7 +423,7 @@ final class ClusterClient(settings: ClusterClientSettings) extends Actor with Ac override def postStop(): Unit = { super.postStop() heartbeatTask.cancel() - refreshContactsTask.foreach { _.cancel() } + refreshContactsTask.foreach(_.cancel()) } def receive = establishing.orElse(contactPointMessages) @@ -438,7 +438,7 @@ final class ClusterClient(settings: ClusterClientSettings) extends Actor with Ac if (contactPoints.nonEmpty) { contactPaths = contactPoints.map(ActorPath.fromString).to(HashSet) contacts = contactPaths.map(context.actorSelection) - contacts.foreach { _ ! Identify(Array.emptyByteArray) } + contacts.foreach(_ ! Identify(Array.emptyByteArray)) } publishContactPoints() case ActorIdentity(_, Some(receptionist)) => @@ -522,7 +522,7 @@ final class ClusterClient(settings: ClusterClientSettings) extends Actor with Ac else contacts if (log.isDebugEnabled) log.debug(s"""Sending GetContacts to [${sendTo.mkString(",")}]""") - sendTo.foreach { _ ! GetContacts } + sendTo.foreach(_ ! GetContacts) } def buffer(msg: Any): Unit = @@ -638,7 +638,7 @@ final class ClusterClientReceptionist(system: ExtendedActorSystem) extends Exten /** * The [[ClusterReceptionist]] actor */ - private val receptionist: ActorRef = { + private val receptionist: ActorRef = if (isTerminated) system.deadLetters else { @@ -650,7 +650,6 @@ final class ClusterClientReceptionist(system: ExtendedActorSystem) extends Exten ClusterReceptionist.props(mediator, ClusterReceptionistSettings(config)).withDispatcher(dispatcher), name) } - } /** * Returns the underlying receptionist actor, particularly so that its diff --git a/cluster-tools/src/main/scala/org/apache/pekko/cluster/pubsub/DistributedPubSubMediator.scala b/cluster-tools/src/main/scala/org/apache/pekko/cluster/pubsub/DistributedPubSubMediator.scala index 875511e7d96..9b00288002e 100644 --- a/cluster-tools/src/main/scala/org/apache/pekko/cluster/pubsub/DistributedPubSubMediator.scala +++ b/cluster-tools/src/main/scala/org/apache/pekko/cluster/pubsub/DistributedPubSubMediator.scala @@ -404,7 +404,7 @@ object DistributedPubSubMediator { case Count => sender() ! subscribers.size case msg => - subscribers.foreach { _.forward(msg) } + subscribers.foreach(_.forward(msg)) } def business: Receive @@ -913,7 +913,7 @@ class DistributedPubSubMediator(settings: DistributedPubSubSettings) def selectRandomNode(addresses: immutable.IndexedSeq[Address]): Option[Address] = if (addresses.isEmpty) None else Some(addresses(ThreadLocalRandom.current.nextInt(addresses.size))) - def prune(): Unit = { + def prune(): Unit = registry.foreach { case (owner, bucket) => val oldRemoved = bucket.content.collect { @@ -922,7 +922,6 @@ class DistributedPubSubMediator(settings: DistributedPubSubSettings) if (oldRemoved.nonEmpty) registry += owner -> bucket.copy(content = bucket.content -- oldRemoved) } - } def newTopicActor(encTopic: String): ActorRef = { val t = context.actorOf(Props(classOf[Topic], removedTimeToLive, routingLogic), name = encTopic) @@ -960,7 +959,7 @@ class DistributedPubSub(system: ExtendedActorSystem) extends Extension { /** * The [[DistributedPubSubMediator]] */ - val mediator: ActorRef = { + val mediator: ActorRef = if (isTerminated) system.deadLetters else { @@ -968,5 +967,4 @@ class DistributedPubSub(system: ExtendedActorSystem) extends Extension { val dispatcher = system.settings.config.getString("pekko.cluster.pub-sub.use-dispatcher") system.systemActorOf(DistributedPubSubMediator.props(settings).withDispatcher(dispatcher), name) } - } } diff --git a/cluster-tools/src/main/scala/org/apache/pekko/cluster/pubsub/PerGroupingBuffer.scala b/cluster-tools/src/main/scala/org/apache/pekko/cluster/pubsub/PerGroupingBuffer.scala index 8f0bae2913f..9a506c31a2a 100644 --- a/cluster-tools/src/main/scala/org/apache/pekko/cluster/pubsub/PerGroupingBuffer.scala +++ b/cluster-tools/src/main/scala/org/apache/pekko/cluster/pubsub/PerGroupingBuffer.scala @@ -21,10 +21,9 @@ private[pubsub] trait PerGroupingBuffer { private val buffers: MessageBufferMap[String] = new MessageBufferMap() - def bufferOr(grouping: String, message: Any, originalSender: ActorRef)(action: => Unit): Unit = { + def bufferOr(grouping: String, message: Any, originalSender: ActorRef)(action: => Unit): Unit = if (!buffers.contains(grouping)) action else buffers.append(grouping, message, originalSender) - } def recreateAndForwardMessagesIfNeeded(grouping: String, recipient: => ActorRef): Unit = { val buffer = buffers.getOrEmpty(grouping) @@ -39,11 +38,10 @@ private[pubsub] trait PerGroupingBuffer { buffers.remove(grouping) } - private def forwardMessages(messages: MessageBuffer, recipient: ActorRef): Unit = { + private def forwardMessages(messages: MessageBuffer, recipient: ActorRef): Unit = messages.foreach { case (message, originalSender) => recipient.tell(message, originalSender) } - } def initializeGrouping(grouping: String): Unit = buffers.add(grouping) } diff --git a/cluster-tools/src/main/scala/org/apache/pekko/cluster/pubsub/protobuf/DistributedPubSubMessageSerializer.scala b/cluster-tools/src/main/scala/org/apache/pekko/cluster/pubsub/protobuf/DistributedPubSubMessageSerializer.scala index 4416877555d..54f500c6190 100644 --- a/cluster-tools/src/main/scala/org/apache/pekko/cluster/pubsub/protobuf/DistributedPubSubMessageSerializer.scala +++ b/cluster-tools/src/main/scala/org/apache/pekko/cluster/pubsub/protobuf/DistributedPubSubMessageSerializer.scala @@ -180,18 +180,16 @@ private[pekko] class DistributedPubSubMessageSerializer(val system: ExtendedActo Bucket(addressFromProto(b.getOwner), b.getVersion, content) }) - private def resolveActorRef(path: String): ActorRef = { + private def resolveActorRef(path: String): ActorRef = system.provider.resolveActorRef(path) - } - private def sendToProto(send: Send): dm.Send = { + private def sendToProto(send: Send): dm.Send = dm.Send .newBuilder() .setPath(send.path) .setLocalAffinity(send.localAffinity) .setPayload(payloadToProto(send.msg)) .build() - } private def sendFromBinary(bytes: Array[Byte]): Send = sendFromProto(dm.Send.parseFrom(bytes)) @@ -199,14 +197,13 @@ private[pekko] class DistributedPubSubMessageSerializer(val system: ExtendedActo private def sendFromProto(send: dm.Send): Send = Send(send.getPath, payloadFromProto(send.getPayload), send.getLocalAffinity) - private def sendToAllToProto(sendToAll: SendToAll): dm.SendToAll = { + private def sendToAllToProto(sendToAll: SendToAll): dm.SendToAll = dm.SendToAll .newBuilder() .setPath(sendToAll.path) .setAllButSelf(sendToAll.allButSelf) .setPayload(payloadToProto(sendToAll.msg)) .build() - } private def sendToAllFromBinary(bytes: Array[Byte]): SendToAll = sendToAllFromProto(dm.SendToAll.parseFrom(bytes)) @@ -214,9 +211,8 @@ private[pekko] class DistributedPubSubMessageSerializer(val system: ExtendedActo private def sendToAllFromProto(sendToAll: dm.SendToAll): SendToAll = SendToAll(sendToAll.getPath, payloadFromProto(sendToAll.getPayload), sendToAll.getAllButSelf) - private def publishToProto(publish: Publish): dm.Publish = { + private def publishToProto(publish: Publish): dm.Publish = dm.Publish.newBuilder().setTopic(publish.topic).setPayload(payloadToProto(publish.msg)).build() - } private def publishFromBinary(bytes: Array[Byte]): Publish = publishFromProto(dm.Publish.parseFrom(bytes)) @@ -224,9 +220,8 @@ private[pekko] class DistributedPubSubMessageSerializer(val system: ExtendedActo private def publishFromProto(publish: dm.Publish): Publish = Publish(publish.getTopic, payloadFromProto(publish.getPayload)) - private def sendToOneSubscriberToProto(sendToOneSubscriber: SendToOneSubscriber): dm.SendToOneSubscriber = { + private def sendToOneSubscriberToProto(sendToOneSubscriber: SendToOneSubscriber): dm.SendToOneSubscriber = dm.SendToOneSubscriber.newBuilder().setPayload(payloadToProto(sendToOneSubscriber.msg)).build() - } private def sendToOneSubscriberFromBinary(bytes: Array[Byte]): SendToOneSubscriber = sendToOneSubscriberFromProto(dm.SendToOneSubscriber.parseFrom(bytes)) diff --git a/cluster-tools/src/main/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManager.scala b/cluster-tools/src/main/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManager.scala index c46e8e135c4..d2b9441904f 100644 --- a/cluster-tools/src/main/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManager.scala +++ b/cluster-tools/src/main/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManager.scala @@ -354,30 +354,27 @@ object ClusterSingletonManager { changes :+= initial } - def add(m: Member): Unit = { + def add(m: Member): Unit = if (matchingRole(m)) trackChange { () => // replace, it's possible that the upNumber is changed membersByAge = membersByAge.filterNot(_.uniqueAddress == m.uniqueAddress) membersByAge += m } - } - def remove(m: Member): Unit = { + def remove(m: Member): Unit = if (matchingRole(m)) trackChange { () => membersByAge = membersByAge.filterNot(_.uniqueAddress == m.uniqueAddress) } - } - def sendFirstChange(): Unit = { + def sendFirstChange(): Unit = // don't send cluster change events if this node is shutting its self down, just wait for SelfExiting if (!cluster.isTerminated) { val event = changes.head changes = changes.tail context.parent ! event } - } def receive = { case state: CurrentClusterState => handleInitial(state) @@ -415,19 +412,17 @@ object ClusterSingletonManager { sender() ! Done // reply to ask } - def deliverChanges(): Unit = { + def deliverChanges(): Unit = if (changes.nonEmpty) { sendFirstChange() context.unbecome() } - } - override def unhandled(msg: Any): Unit = { + override def unhandled(msg: Any): Unit = msg match { case _: MemberEvent => // ok, silence case _ => super.unhandled(msg) } - } } } } @@ -543,9 +538,8 @@ class ClusterSingletonManager(singletonProps: Props, terminationMessage: Any, se def addRemoved(node: UniqueAddress): Unit = removed += node -> (Deadline.now + 15.minutes) - def cleanupOverdueNotMemberAnyMore(): Unit = { + def cleanupOverdueNotMemberAnyMore(): Unit = removed = removed.filter { case (_, deadline) => deadline.hasTimeLeft() } - } // for CoordinatedShutdown val coordShutdown = CoordinatedShutdown(context.system) @@ -649,7 +643,7 @@ class ClusterSingletonManager(singletonProps: Props, terminationMessage: Any, se handleMemberEvent(event) } - def handleMemberEvent(event: MemberEvent): State = { + def handleMemberEvent(event: MemberEvent): State = event match { case _: MemberRemoved if event.member.uniqueAddress == cluster.selfUniqueAddress => logInfo("Self removed, stopping ClusterSingletonManager") @@ -666,7 +660,6 @@ class ClusterSingletonManager(singletonProps: Props, terminationMessage: Any, se case _ => stay() } - } when(Younger) { case Event(OldestChanged(oldestOption), YoungerData(previousOldest)) => @@ -818,13 +811,12 @@ class ClusterSingletonManager(singletonProps: Props, terminationMessage: Any, se s"Becoming singleton oldest was stuck because previous oldest [${previousOldest.headOption}] is unresponsive") } - def scheduleDelayedMemberRemoved(m: Member): Unit = { + def scheduleDelayedMemberRemoved(m: Member): Unit = if (removalMargin > Duration.Zero) { log.debug("Schedule DelayedMemberRemoved for [{}]", m.address) context.system.scheduler.scheduleOnce(removalMargin, self, DelayedMemberRemoved(m))(context.dispatcher) } else self ! DelayedMemberRemoved(m) - } def tryAcquireLease() = { import context.dispatcher @@ -838,7 +830,7 @@ class ClusterSingletonManager(singletonProps: Props, terminationMessage: Any, se } // Try and go to oldest, taking the lease if needed - def tryGotoOldest(): State = { + def tryGotoOldest(): State = // check if lease lease match { case None => @@ -847,7 +839,6 @@ class ClusterSingletonManager(singletonProps: Props, terminationMessage: Any, se logInfo("Trying to acquire lease before starting singleton") tryAcquireLease() } - } when(AcquiringLease) { case Event(AcquireLeaseResult(result), _) => @@ -893,7 +884,7 @@ class ClusterSingletonManager(singletonProps: Props, terminationMessage: Any, se } @InternalStableApi - def gotoOldest(): State = { + def gotoOldest(): State = if (preparingForFullShutdown) { logInfo( ClusterLogMarker.singletonStarted, @@ -909,8 +900,6 @@ class ClusterSingletonManager(singletonProps: Props, terminationMessage: Any, se goto(Oldest).using(OldestData(Some(singleton))) } - } - def handleOldestChanged(singleton: Option[ActorRef], oldestOption: Option[UniqueAddress]) = { oldestChangedReceived = true logInfo("{} observed OldestChanged: [{} -> {}]", stateName, cluster.selfAddress, oldestOption.map(_.address)) @@ -1046,17 +1035,16 @@ class ClusterSingletonManager(singletonProps: Props, terminationMessage: Any, se } - def gotoHandingOver(singleton: Option[ActorRef], handOverTo: Option[ActorRef]): State = { + def gotoHandingOver(singleton: Option[ActorRef], handOverTo: Option[ActorRef]): State = singleton match { case None => handOverDone(handOverTo) case Some(s) => - handOverTo.foreach { _ ! HandOverInProgress } + handOverTo.foreach(_ ! HandOverInProgress) logInfo("Singleton manager stopping singleton actor [{}]", s.path) s ! terminationMessage goto(HandingOver).using(HandingOverData(s, handOverTo)) } - } when(HandingOver) { case Event(Terminated(ref), HandingOverData(singleton, handOverTo)) if ref == singleton => @@ -1092,7 +1080,7 @@ class ClusterSingletonManager(singletonProps: Props, terminationMessage: Any, se "Singleton terminated, hand-over done [{} -> {}]", cluster.selfAddress, newOldest) - handOverTo.foreach { _ ! HandOverDone } + handOverTo.foreach(_ ! HandOverDone) memberExitingProgress.trySuccess(Done) if (removed.contains(cluster.selfUniqueAddress)) { logInfo("Self removed, stopping ClusterSingletonManager") diff --git a/cluster-tools/src/main/scala/org/apache/pekko/cluster/singleton/ClusterSingletonProxy.scala b/cluster-tools/src/main/scala/org/apache/pekko/cluster/singleton/ClusterSingletonProxy.scala index b4f09e22a4e..0d76ffcd35d 100644 --- a/cluster-tools/src/main/scala/org/apache/pekko/cluster/singleton/ClusterSingletonProxy.scala +++ b/cluster-tools/src/main/scala/org/apache/pekko/cluster/singleton/ClusterSingletonProxy.scala @@ -210,7 +210,7 @@ final class ClusterSingletonProxy(singletonManagerPath: String, settings: Cluste def matchingRole(member: Member): Boolean = member.hasRole(targetDcRole) && role.forall(member.hasRole) - def handleInitial(state: CurrentClusterState): Unit = { + def handleInitial(state: CurrentClusterState): Unit = trackChange { () => membersByAge = immutable.SortedSet .empty(ageOrdering) @@ -218,7 +218,6 @@ final class ClusterSingletonProxy(singletonManagerPath: String, settings: Cluste case m if m.status == MemberStatus.Up && matchingRole(m) => m }) } - } /** * Discard old singleton ActorRef and send a periodic message to self to identify the singleton. @@ -250,26 +249,24 @@ final class ClusterSingletonProxy(singletonManagerPath: String, settings: Cluste * Adds new member if it has the right role. * @param m New cluster member. */ - def add(m: Member): Unit = { + def add(m: Member): Unit = if (matchingRole(m)) trackChange { () => // replace, it's possible that the upNumber is changed membersByAge = membersByAge.filterNot(_.uniqueAddress == m.uniqueAddress) membersByAge += m } - } /** * Removes a member. * @param m Cluster member to remove. */ - def remove(m: Member): Unit = { + def remove(m: Member): Unit = if (matchingRole(m)) trackChange { () => // filter, it's possible that the upNumber is changed membersByAge = membersByAge.filterNot(_.uniqueAddress == m.uniqueAddress) } - } def receive = { // cluster logic diff --git a/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/client/ClusterClientSpec.scala b/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/client/ClusterClientSpec.scala index 2854065cd51..efe0d54e379 100644 --- a/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/client/ClusterClientSpec.scala +++ b/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/client/ClusterClientSpec.scala @@ -185,13 +185,12 @@ class ClusterClientSpec extends MultiNodeSpec(ClusterClientSpec) with STMultiNod def createReceptionist(): Unit = ClusterClientReceptionist(system) - def awaitCount(expected: Int): Unit = { + def awaitCount(expected: Int): Unit = awaitAssert { DistributedPubSub(system).mediator ! DistributedPubSubMediator.Count val actual = expectMsgType[Int] actual should ===(expected) } - } var remainingServerRoleNames = Set(first, second, third, fourth) diff --git a/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/client/ClusterClientStopSpec.scala b/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/client/ClusterClientStopSpec.scala index 6af92d89a7e..3af86129125 100644 --- a/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/client/ClusterClientStopSpec.scala +++ b/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/client/ClusterClientStopSpec.scala @@ -71,13 +71,12 @@ class ClusterClientStopSpec extends MultiNodeSpec(ClusterClientStopSpec) with ST enterBarrier(from.name + "-joined") } - def awaitCount(expected: Int): Unit = { + def awaitCount(expected: Int): Unit = awaitAssert { DistributedPubSub(system).mediator ! DistributedPubSubMediator.Count val actual = expectMsgType[Int] actual should ===(expected) } - } def initialContacts = Set(first, second).map { r => node(r) / "system" / "receptionist" diff --git a/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/pubsub/DistributedPubSubMediatorSpec.scala b/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/pubsub/DistributedPubSubMediatorSpec.scala index 26b6a1837d0..bbe38801220 100644 --- a/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/pubsub/DistributedPubSubMediatorSpec.scala +++ b/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/pubsub/DistributedPubSubMediatorSpec.scala @@ -168,21 +168,19 @@ class DistributedPubSubMediatorSpec def chatUser(name: String): ActorRef = chatUsers(name) - def awaitCount(expected: Int): Unit = { + def awaitCount(expected: Int): Unit = awaitAssert { mediator ! Count val actual = expectMsgType[Int] actual should ===(expected) } - } - def awaitCountSubscribers(expected: Int, topic: String): Unit = { + def awaitCountSubscribers(expected: Int, topic: String): Unit = awaitAssert { mediator ! CountSubscribers(topic) val actual = expectMsgType[Int] actual should ===(expected) } - } "A DistributedPubSubMediator" must { @@ -353,9 +351,8 @@ class DistributedPubSubMediatorSpec } "demonstrate usage of Publish" in within(15 seconds) { - def later(): Unit = { + def later(): Unit = awaitCount(10) - } // #start-subscribers runOn(first) { @@ -380,9 +377,8 @@ class DistributedPubSubMediatorSpec } "demonstrate usage of Send" in within(15 seconds) { - def later(): Unit = { + def later(): Unit = awaitCount(12) - } // #start-send-destinations runOn(first) { diff --git a/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManagerChaosSpec.scala b/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManagerChaosSpec.scala index 57b0819af34..a99e4ca6ae2 100644 --- a/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManagerChaosSpec.scala +++ b/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManagerChaosSpec.scala @@ -81,30 +81,27 @@ class ClusterSingletonManagerChaosSpec override def initialParticipants = roles.size - def join(from: RoleName, to: RoleName): Unit = { + def join(from: RoleName, to: RoleName): Unit = runOn(from) { Cluster(system).join(node(to).address) createSingleton() } - } - def createSingleton(): ActorRef = { + def createSingleton(): ActorRef = system.actorOf( ClusterSingletonManager.props( singletonProps = Props(classOf[Echo], testActor), terminationMessage = PoisonPill, settings = ClusterSingletonManagerSettings(system)), name = "echo") - } - def crash(roles: RoleName*): Unit = { + def crash(roles: RoleName*): Unit = runOn(controller) { roles.foreach { r => log.info("Shutdown [{}]", node(r).address) testConductor.exit(r, 0).await } } - } def echo(oldest: RoleName): ActorSelection = system.actorSelection(RootActorPath(node(oldest).address) / "user" / "echo" / "singleton") diff --git a/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManagerDownedSpec.scala b/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManagerDownedSpec.scala index eea59ea44cd..54ad69c047b 100644 --- a/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManagerDownedSpec.scala +++ b/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManagerDownedSpec.scala @@ -55,9 +55,8 @@ object ClusterSingletonManagerDownedSpec extends MultiNodeConfig { class Echo(testActor: ActorRef) extends Actor { testActor ! EchoStarted - override def postStop(): Unit = { + override def postStop(): Unit = testActor ! EchoStopped - } def receive = { case _ => sender() ! self @@ -79,21 +78,19 @@ class ClusterSingletonManagerDownedSpec private val cluster = Cluster(system) - def join(from: RoleName, to: RoleName): Unit = { + def join(from: RoleName, to: RoleName): Unit = runOn(from) { cluster.join(node(to).address) createSingleton() } - } - def createSingleton(): ActorRef = { + def createSingleton(): ActorRef = system.actorOf( ClusterSingletonManager.props( singletonProps = Props(classOf[Echo], testActor), terminationMessage = PoisonPill, settings = ClusterSingletonManagerSettings(system)), name = "echo") - } "A ClusterSingletonManager downing" must { diff --git a/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManagerLeaseSpec.scala b/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManagerLeaseSpec.scala index 1107bd90a98..7b73256f629 100644 --- a/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManagerLeaseSpec.scala +++ b/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManagerLeaseSpec.scala @@ -64,12 +64,10 @@ object ClusterSingletonManagerLeaseSpec extends MultiNodeConfig { class ImportantSingleton extends Actor with ActorLogging { val selfAddress = Cluster(context.system).selfAddress - override def preStart(): Unit = { + override def preStart(): Unit = log.info("Singleton starting") - } - override def postStop(): Unit = { + override def postStop(): Unit = log.info("Singleton stopping") - } override def receive: Receive = { case msg => sender() ! Response(msg, selfAddress) @@ -186,9 +184,8 @@ class ClusterSingletonManagerLeaseSpec cluster.state.members.size shouldEqual 5 runOn(controller) { cluster.down(address(first)) - awaitAssert({ - cluster.state.members.toList.map(_.status) shouldEqual List(Up, Up, Up, Up) - }, 20.seconds) + awaitAssert( + cluster.state.members.toList.map(_.status) shouldEqual List(Up, Up, Up, Up), 20.seconds) val requests = awaitAssert({ TestLeaseActorClientExt(system).getLeaseActor() ! GetRequests val msg = expectMsgType[LeaseRequests] @@ -202,9 +199,8 @@ class ClusterSingletonManagerLeaseSpec requests.requests should contain(Acquire(address(second).hostPort)) } runOn(second, third, fourth) { - awaitAssert({ - cluster.state.members.toList.map(_.status) shouldEqual List(Up, Up, Up, Up) - }, 20.seconds) + awaitAssert( + cluster.state.members.toList.map(_.status) shouldEqual List(Up, Up, Up, Up), 20.seconds) } enterBarrier("first node downed") val proxy = system.actorOf( diff --git a/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManagerLeave2Spec.scala b/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManagerLeave2Spec.scala index 3740745cf19..fee0b7d663c 100644 --- a/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManagerLeave2Spec.scala +++ b/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManagerLeave2Spec.scala @@ -90,31 +90,28 @@ class ClusterSingletonManagerLeave2Spec lazy val cluster = Cluster(system) - def join(from: RoleName, to: RoleName): Unit = { + def join(from: RoleName, to: RoleName): Unit = runOn(from) { cluster.join(node(to).address) createSingleton() } - } - def createSingleton(): ActorRef = { + def createSingleton(): ActorRef = system.actorOf( ClusterSingletonManager.props( singletonProps = Props(classOf[Echo], testActor), terminationMessage = "stop", settings = ClusterSingletonManagerSettings(system)), name = "echo") - } val echoProxyTerminatedProbe = TestProbe() - lazy val echoProxy: ActorRef = { + lazy val echoProxy: ActorRef = echoProxyTerminatedProbe.watch( system.actorOf( ClusterSingletonProxy .props(singletonManagerPath = "/user/echo", settings = ClusterSingletonProxySettings(system)), name = "echoProxy")) - } "Leaving ClusterSingletonManager with two nodes" must { diff --git a/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManagerLeaveSpec.scala b/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManagerLeaveSpec.scala index 8c624802b9e..ac6fac9966b 100644 --- a/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManagerLeaveSpec.scala +++ b/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManagerLeaveSpec.scala @@ -48,12 +48,10 @@ object ClusterSingletonManagerLeaveSpec extends MultiNodeConfig { * The singleton actor */ class Echo(testActor: ActorRef) extends Actor { - override def preStart(): Unit = { + override def preStart(): Unit = testActor ! "preStart" - } - override def postStop(): Unit = { + override def postStop(): Unit = testActor ! "postStop" - } def receive = { case "stop" => @@ -79,31 +77,28 @@ class ClusterSingletonManagerLeaveSpec lazy val cluster = Cluster(system) - def join(from: RoleName, to: RoleName): Unit = { + def join(from: RoleName, to: RoleName): Unit = runOn(from) { cluster.join(node(to).address) createSingleton() } - } - def createSingleton(): ActorRef = { + def createSingleton(): ActorRef = system.actorOf( ClusterSingletonManager.props( singletonProps = Props(classOf[Echo], testActor), terminationMessage = "stop", settings = ClusterSingletonManagerSettings(system)), name = "echo") - } val echoProxyTerminatedProbe = TestProbe() - lazy val echoProxy: ActorRef = { + lazy val echoProxy: ActorRef = echoProxyTerminatedProbe.watch( system.actorOf( ClusterSingletonProxy .props(singletonManagerPath = "/user/echo", settings = ClusterSingletonProxySettings(system)), name = "echoProxy")) - } "Leaving ClusterSingletonManager" must { diff --git a/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManagerPreparingForShutdownSpec.scala b/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManagerPreparingForShutdownSpec.scala index efcf08ad29b..e353bdb4632 100644 --- a/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManagerPreparingForShutdownSpec.scala +++ b/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManagerPreparingForShutdownSpec.scala @@ -53,9 +53,8 @@ object ClusterSingletonManagerPreparingForShutdownSpec extends MultiNodeConfig { log.info("Singleton starting on {}", Cluster(context.system).selfUniqueAddress) testActor ! "preStart" } - override def postStop(): Unit = { + override def postStop(): Unit = testActor ! "postStop" - } def receive = { case "stop" => @@ -79,24 +78,22 @@ class ClusterSingletonManagerPreparingForShutdownSpec override def initialParticipants = roles.size - def createSingleton(): ActorRef = { + def createSingleton(): ActorRef = system.actorOf( ClusterSingletonManager.props( singletonProps = Props(classOf[Echo], testActor), terminationMessage = "stop", settings = ClusterSingletonManagerSettings(system)), name = "echo") - } val echoProxyTerminatedProbe = TestProbe() - lazy val echoProxy: ActorRef = { + lazy val echoProxy: ActorRef = echoProxyTerminatedProbe.watch( system.actorOf( ClusterSingletonProxy .props(singletonManagerPath = "/user/echo", settings = ClusterSingletonProxySettings(system)), name = "echoProxy")) - } "Preparing for shut down ClusterSingletonManager" must { @@ -120,10 +117,9 @@ class ClusterSingletonManagerPreparingForShutdownSpec runOn(first) { Cluster(system).prepareForFullClusterShutdown() } - awaitAssert({ - withClue("members: " + Cluster(system).readView.members) { - Cluster(system).selfMember.status shouldEqual MemberStatus.ReadyForShutdown - } + awaitAssert( + withClue("members: " + Cluster(system).readView.members) { + Cluster(system).selfMember.status shouldEqual MemberStatus.ReadyForShutdown }, 10.seconds) enterBarrier("preparation-complete") @@ -162,10 +158,9 @@ class ClusterSingletonManagerPreparingForShutdownSpec Cluster(system).leave(address(third)) Cluster(system).leave(address(second)) } - awaitAssert({ - withClue("self member: " + Cluster(system).selfMember) { - Cluster(system).selfMember.status shouldEqual Removed - } + awaitAssert( + withClue("self member: " + Cluster(system).selfMember) { + Cluster(system).selfMember.status shouldEqual Removed }, 10.seconds) enterBarrier("done") } diff --git a/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManagerSpec.scala b/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManagerSpec.scala index f04c2aa2763..0e4b4b0fe6b 100644 --- a/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManagerSpec.scala +++ b/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManagerSpec.scala @@ -140,10 +140,9 @@ object ClusterSingletonManagerSpec extends MultiNodeConfig { override def preStart(): Unit = queue ! RegisterConsumer - override def postStop(): Unit = { + override def postStop(): Unit = if (stoppedBeforeUnregistration) log.warning("Stopped before unregistration") - } def receive = { case n: Int if n <= current => @@ -206,7 +205,7 @@ class ClusterSingletonManagerSpec identifyProbe.expectMsgType[ActorIdentity].ref.get } - def join(from: RoleName, to: RoleName): Unit = { + def join(from: RoleName, to: RoleName): Unit = runOn(from) { Cluster(system).join(node(to).address) if (Cluster(system).selfRoles.contains("worker")) { @@ -214,7 +213,6 @@ class ClusterSingletonManagerSpec createSingletonProxy() } } - } def awaitMemberUp(memberProbe: TestProbe, nodes: RoleName*): Unit = { runOn(nodes.filterNot(_ == nodes.head): _*) { @@ -227,7 +225,7 @@ class ClusterSingletonManagerSpec enterBarrier(nodes.head.name + "-up") } - def createSingleton(): ActorRef = { + def createSingleton(): ActorRef = // #create-singleton-manager system.actorOf( ClusterSingletonManager.props( @@ -235,8 +233,7 @@ class ClusterSingletonManagerSpec terminationMessage = End, settings = ClusterSingletonManagerSettings(system).withRole("worker")), name = "consumer") - // #create-singleton-manager - } + // #create-singleton-manager def createSingletonProxy(): ActorRef = { // #create-singleton-proxy @@ -324,7 +321,7 @@ class ClusterSingletonManagerSpec enterBarrier("after-" + msg + "-verified") } - def crash(roles: RoleName*): Unit = { + def crash(roles: RoleName*): Unit = runOn(controller) { queue ! Reset expectMsg(ResetOk) @@ -333,7 +330,6 @@ class ClusterSingletonManagerSpec testConductor.exit(r, 0).await } } - } "A ClusterSingletonManager" must { diff --git a/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManagerStartupSpec.scala b/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManagerStartupSpec.scala index 15a78fa9136..62fd2281792 100644 --- a/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManagerStartupSpec.scala +++ b/cluster-tools/src/multi-jvm/scala/org/apache/pekko/cluster/singleton/ClusterSingletonManagerStartupSpec.scala @@ -68,28 +68,25 @@ class ClusterSingletonManagerStartupSpec override def initialParticipants = roles.size - def join(from: RoleName, to: RoleName): Unit = { + def join(from: RoleName, to: RoleName): Unit = runOn(from) { Cluster(system).join(node(to).address) createSingleton() } - } - def createSingleton(): ActorRef = { + def createSingleton(): ActorRef = system.actorOf( ClusterSingletonManager.props( singletonProps = Props(classOf[Echo]), terminationMessage = PoisonPill, settings = ClusterSingletonManagerSettings(system)), name = "echo") - } - lazy val echoProxy: ActorRef = { + lazy val echoProxy: ActorRef = system.actorOf( ClusterSingletonProxy .props(singletonManagerPath = "/user/echo", settings = ClusterSingletonProxySettings(system)), name = "echoProxy") - } "Startup of Cluster Singleton" must { diff --git a/cluster-tools/src/test/scala/org/apache/pekko/cluster/singleton/ClusterSingletonLeavingSpeedSpec.scala b/cluster-tools/src/test/scala/org/apache/pekko/cluster/singleton/ClusterSingletonLeavingSpeedSpec.scala index c7546db1782..f3b8180a030 100644 --- a/cluster-tools/src/test/scala/org/apache/pekko/cluster/singleton/ClusterSingletonLeavingSpeedSpec.scala +++ b/cluster-tools/src/test/scala/org/apache/pekko/cluster/singleton/ClusterSingletonLeavingSpeedSpec.scala @@ -40,9 +40,8 @@ object ClusterSingletonLeavingSpeedSpec { class TheSingleton(probe: ActorRef) extends Actor { probe ! "started" - override def postStop(): Unit = { + override def postStop(): Unit = probe ! "stopped" - } override def receive: Receive = { case msg => sender() ! msg @@ -155,7 +154,6 @@ class ClusterSingletonLeavingSpeedSpec } } - override def afterTermination(): Unit = { + override def afterTermination(): Unit = systems.foreach(shutdown(_)) - } } diff --git a/cluster-typed/src/main/scala/org/apache/pekko/cluster/ddata/typed/internal/ReplicatorBehavior.scala b/cluster-typed/src/main/scala/org/apache/pekko/cluster/ddata/typed/internal/ReplicatorBehavior.scala index 8f4bdfe8950..0d0ead63076 100644 --- a/cluster-typed/src/main/scala/org/apache/pekko/cluster/ddata/typed/internal/ReplicatorBehavior.scala +++ b/cluster-typed/src/main/scala/org/apache/pekko/cluster/ddata/typed/internal/ReplicatorBehavior.scala @@ -63,7 +63,7 @@ import pekko.util.Timeout ReplicatedData]]]): Behavior[SReplicator.Command] = { def stopSubscribeAdapter( - subscriber: ActorRef[JReplicator.SubscribeResponse[ReplicatedData]]): Behavior[SReplicator.Command] = { + subscriber: ActorRef[JReplicator.SubscribeResponse[ReplicatedData]]): Behavior[SReplicator.Command] = subscribeAdapters.get(subscriber) match { case Some(adapter) => // will be unsubscribed from classicReplicator via Terminated @@ -72,7 +72,6 @@ import pekko.util.Timeout case None => // already unsubscribed or terminated Behaviors.same } - } Behaviors .receive[SReplicator.Command] { (ctx, msg) => @@ -100,7 +99,7 @@ import pekko.util.Timeout .recover { case _ => JReplicator.GetFailure(cmd.key) } - reply.foreach { cmd.replyTo ! _ } + reply.foreach(cmd.replyTo ! _) Behaviors.same case cmd: SReplicator.Update[_] => @@ -129,7 +128,7 @@ import pekko.util.Timeout .recover { case _ => JReplicator.UpdateTimeout(cmd.key) } - reply.foreach { cmd.replyTo ! _ } + reply.foreach(cmd.replyTo ! _) Behaviors.same case cmd: SReplicator.Subscribe[_] => @@ -195,7 +194,7 @@ import pekko.util.Timeout .recover { case _ => JReplicator.DeleteFailure(cmd.key) } - reply.foreach { cmd.replyTo ! _ } + reply.foreach(cmd.replyTo ! _) Behaviors.same case SReplicator.GetReplicaCount(replyTo) => @@ -209,7 +208,7 @@ import pekko.util.Timeout (classicReplicator ? dd.Replicator.GetReplicaCount) .mapTo[dd.Replicator.ReplicaCount] .map(rsp => JReplicator.ReplicaCount(rsp.n)) - reply.foreach { replyTo ! _ } + reply.foreach(replyTo ! _) Behaviors.same case SReplicator.FlushChanges | JReplicator.FlushChanges => diff --git a/cluster-typed/src/main/scala/org/apache/pekko/cluster/ddata/typed/javadsl/DistributedData.scala b/cluster-typed/src/main/scala/org/apache/pekko/cluster/ddata/typed/javadsl/DistributedData.scala index 7c8ce8400ac..988c9d3aceb 100644 --- a/cluster-typed/src/main/scala/org/apache/pekko/cluster/ddata/typed/javadsl/DistributedData.scala +++ b/cluster-typed/src/main/scala/org/apache/pekko/cluster/ddata/typed/javadsl/DistributedData.scala @@ -55,7 +55,7 @@ object DistributedData extends ExtensionId[DistributedData] { * @tparam B Type of the [[ReplicatedData]]. */ def withReplicatorMessageAdapter[A, B <: ReplicatedData]( - factory: JFunction[ReplicatorMessageAdapter[A, B], Behavior[A]]): Behavior[A] = { + factory: JFunction[ReplicatorMessageAdapter[A, B], Behavior[A]]): Behavior[A] = Behaviors.setup[A] { context => val distributedData = pekko.cluster.ddata.typed.scaladsl.DistributedData(context.getSystem) val replicatorAdapter = @@ -65,7 +65,6 @@ object DistributedData extends ExtensionId[DistributedData] { distributedData.unexpectedAskTimeout.asJava) factory(replicatorAdapter) } - } } /** diff --git a/cluster-typed/src/main/scala/org/apache/pekko/cluster/ddata/typed/javadsl/ReplicatorMessageAdapter.scala b/cluster-typed/src/main/scala/org/apache/pekko/cluster/ddata/typed/javadsl/ReplicatorMessageAdapter.scala index d6cf1e39d7e..3c65b79fe50 100644 --- a/cluster-typed/src/main/scala/org/apache/pekko/cluster/ddata/typed/javadsl/ReplicatorMessageAdapter.scala +++ b/cluster-typed/src/main/scala/org/apache/pekko/cluster/ddata/typed/javadsl/ReplicatorMessageAdapter.scala @@ -90,11 +90,10 @@ class ReplicatorMessageAdapter[A, B <: ReplicatedData]( * Unsubscribe from a previous subscription of a given `key`. * @see [[ReplicatorMessageAdapter.subscribe]] */ - def unsubscribe(key: Key[B]): Unit = { + def unsubscribe(key: Key[B]): Unit = changedMessageAdapters.get(key).foreach { subscriber => replicator ! Replicator.Unsubscribe(key, subscriber) } - } /** * Send a [[Replicator.Update]] request to the replicator. The [[Replicator.UpdateResponse]] @@ -107,13 +106,12 @@ class ReplicatorMessageAdapter[A, B <: ReplicatedData]( */ def askUpdate( createRequest: JFunction[ActorRef[Replicator.UpdateResponse[B]], Replicator.Update[B]], - responseAdapter: JFunction[Replicator.UpdateResponse[B], A]): Unit = { + responseAdapter: JFunction[Replicator.UpdateResponse[B], A]): Unit = context.asScala .ask[Replicator.Update[B], Replicator.UpdateResponse[B]](replicator, askReplyTo => createRequest(askReplyTo)) { case Success(value) => responseAdapter(value) case Failure(ex) => throw ex // unexpected ask timeout } - } /** * Send a [[Replicator.Get]] request to the replicator. The [[Replicator.GetResponse]] @@ -127,13 +125,12 @@ class ReplicatorMessageAdapter[A, B <: ReplicatedData]( @nowarn def askGet( createRequest: JFunction[ActorRef[Replicator.GetResponse[B]], Replicator.Get[B]], - responseAdapter: JFunction[Replicator.GetResponse[B], A]): Unit = { + responseAdapter: JFunction[Replicator.GetResponse[B], A]): Unit = context.asScala .ask[Replicator.Get[B], Replicator.GetResponse[B]](replicator, askReplyTo => createRequest(askReplyTo)) { case Success(value) => responseAdapter(value) case Failure(ex) => throw ex // unexpected ask timeout } - } /** * Send a [[Replicator.Delete]] request to the replicator. The [[Replicator.DeleteResponse]] @@ -146,13 +143,12 @@ class ReplicatorMessageAdapter[A, B <: ReplicatedData]( */ def askDelete( createRequest: JFunction[ActorRef[Replicator.DeleteResponse[B]], Replicator.Delete[B]], - responseAdapter: JFunction[Replicator.DeleteResponse[B], A]): Unit = { + responseAdapter: JFunction[Replicator.DeleteResponse[B], A]): Unit = context.asScala .ask[Replicator.Delete[B], Replicator.DeleteResponse[B]](replicator, askReplyTo => createRequest(askReplyTo)) { case Success(value) => responseAdapter(value) case Failure(ex) => throw ex // unexpected ask timeout } - } /** * Send a [[Replicator.GetReplicaCount]] request to the replicator. The [[Replicator.ReplicaCount]] @@ -165,12 +161,11 @@ class ReplicatorMessageAdapter[A, B <: ReplicatedData]( */ def askReplicaCount( createRequest: JFunction[ActorRef[Replicator.ReplicaCount], Replicator.GetReplicaCount], - responseAdapter: JFunction[Replicator.ReplicaCount, A]): Unit = { + responseAdapter: JFunction[Replicator.ReplicaCount, A]): Unit = context.asScala .ask[Replicator.GetReplicaCount, Replicator.ReplicaCount](replicator, askReplyTo => createRequest(askReplyTo)) { case Success(value) => responseAdapter(value) case Failure(ex) => throw ex // unexpected ask timeout } - } } diff --git a/cluster-typed/src/main/scala/org/apache/pekko/cluster/ddata/typed/scaladsl/DistributedData.scala b/cluster-typed/src/main/scala/org/apache/pekko/cluster/ddata/typed/scaladsl/DistributedData.scala index b3ef6aaf697..9ddc0865306 100644 --- a/cluster-typed/src/main/scala/org/apache/pekko/cluster/ddata/typed/scaladsl/DistributedData.scala +++ b/cluster-typed/src/main/scala/org/apache/pekko/cluster/ddata/typed/scaladsl/DistributedData.scala @@ -56,14 +56,13 @@ object DistributedData extends ExtensionId[DistributedData] { * @tparam B Type of the [[ReplicatedData]]. */ def withReplicatorMessageAdapter[A, B <: ReplicatedData]( - factory: ReplicatorMessageAdapter[A, B] => Behavior[A]): Behavior[A] = { + factory: ReplicatorMessageAdapter[A, B] => Behavior[A]): Behavior[A] = Behaviors.setup[A] { context => val distributedData = DistributedData(context.system) val replicatorAdapter = new ReplicatorMessageAdapter[A, B](context, distributedData.replicator, distributedData.unexpectedAskTimeout) factory(replicatorAdapter) } - } } diff --git a/cluster-typed/src/main/scala/org/apache/pekko/cluster/ddata/typed/scaladsl/ReplicatorMessageAdapter.scala b/cluster-typed/src/main/scala/org/apache/pekko/cluster/ddata/typed/scaladsl/ReplicatorMessageAdapter.scala index 2544515e80d..ddd94893f31 100644 --- a/cluster-typed/src/main/scala/org/apache/pekko/cluster/ddata/typed/scaladsl/ReplicatorMessageAdapter.scala +++ b/cluster-typed/src/main/scala/org/apache/pekko/cluster/ddata/typed/scaladsl/ReplicatorMessageAdapter.scala @@ -92,11 +92,10 @@ class ReplicatorMessageAdapter[A, B <: ReplicatedData]( * Unsubscribe from a previous subscription of a given `key`. * @see [[ReplicatorMessageAdapter.subscribe]] */ - def unsubscribe(key: Key[B]): Unit = { + def unsubscribe(key: Key[B]): Unit = changedMessageAdapters.get(key).foreach { subscriber => replicator ! Replicator.Unsubscribe(key, subscriber) } - } /** * Send a [[Replicator.Update]] request to the replicator. The [[Replicator.UpdateResponse]] @@ -109,13 +108,12 @@ class ReplicatorMessageAdapter[A, B <: ReplicatedData]( */ def askUpdate( createRequest: ActorRef[Replicator.UpdateResponse[B]] => Replicator.Update[B], - responseAdapter: Replicator.UpdateResponse[B] => A): Unit = { + responseAdapter: Replicator.UpdateResponse[B] => A): Unit = context .ask[Replicator.Update[B], Replicator.UpdateResponse[B]](replicator, askReplyTo => createRequest(askReplyTo)) { case Success(value) => responseAdapter(value) case Failure(ex) => throw ex // unexpected ask timeout } - } /** * Send a [[Replicator.Get]] request to the replicator. The [[Replicator.GetResponse]] @@ -128,12 +126,11 @@ class ReplicatorMessageAdapter[A, B <: ReplicatedData]( */ def askGet( createRequest: ActorRef[Replicator.GetResponse[B]] => Replicator.Get[B], - responseAdapter: Replicator.GetResponse[B] => A): Unit = { + responseAdapter: Replicator.GetResponse[B] => A): Unit = context.ask[Replicator.Get[B], Replicator.GetResponse[B]](replicator, askReplyTo => createRequest(askReplyTo)) { case Success(value) => responseAdapter(value) case Failure(ex) => throw ex // unexpected ask timeout } - } /** * Send a [[Replicator.Delete]] request to the replicator. The [[Replicator.DeleteResponse]] @@ -146,13 +143,12 @@ class ReplicatorMessageAdapter[A, B <: ReplicatedData]( */ def askDelete( createRequest: ActorRef[Replicator.DeleteResponse[B]] => Replicator.Delete[B], - responseAdapter: Replicator.DeleteResponse[B] => A): Unit = { + responseAdapter: Replicator.DeleteResponse[B] => A): Unit = context .ask[Replicator.Delete[B], Replicator.DeleteResponse[B]](replicator, askReplyTo => createRequest(askReplyTo)) { case Success(value) => responseAdapter(value) case Failure(ex) => throw ex // unexpected ask timeout } - } /** * Send a [[Replicator.GetReplicaCount]] request to the replicator. The [[Replicator.ReplicaCount]] @@ -165,12 +161,11 @@ class ReplicatorMessageAdapter[A, B <: ReplicatedData]( */ def askReplicaCount( createRequest: ActorRef[Replicator.ReplicaCount] => Replicator.GetReplicaCount, - responseAdapter: Replicator.ReplicaCount => A): Unit = { + responseAdapter: Replicator.ReplicaCount => A): Unit = context .ask[Replicator.GetReplicaCount, Replicator.ReplicaCount](replicator, askReplyTo => createRequest(askReplyTo)) { case Success(value) => responseAdapter(value) case Failure(ex) => throw ex // unexpected ask timeout } - } } diff --git a/cluster-typed/src/main/scala/org/apache/pekko/cluster/typed/ClusterSingleton.scala b/cluster-typed/src/main/scala/org/apache/pekko/cluster/typed/ClusterSingleton.scala index 92e2cbbcfeb..02e55ebe5c8 100644 --- a/cluster-typed/src/main/scala/org/apache/pekko/cluster/typed/ClusterSingleton.scala +++ b/cluster-typed/src/main/scala/org/apache/pekko/cluster/typed/ClusterSingleton.scala @@ -124,19 +124,17 @@ final class ClusterSingletonSettings( * INTERNAL API: */ @InternalApi - private[pekko] def toProxySettings(singletonName: String): ClusterSingletonProxySettings = { + private[pekko] def toProxySettings(singletonName: String): ClusterSingletonProxySettings = new ClusterSingletonProxySettings(singletonName, role, singletonIdentificationInterval, bufferSize) .withDataCenter(dataCenter) - } /** * INTERNAL API: */ @InternalApi - private[pekko] def shouldRunManager(cluster: Cluster): Boolean = { + private[pekko] def shouldRunManager(cluster: Cluster): Boolean = (role.isEmpty || cluster.selfMember.roles(role.get)) && (dataCenter.isEmpty || dataCenter.contains(cluster.selfMember.dataCenter)) - } override def toString = s"ClusterSingletonSettings($role, $dataCenter, $singletonIdentificationInterval, $removalMargin, $handOverRetryInterval, $bufferSize, $leaseSettings)" diff --git a/cluster-typed/src/main/scala/org/apache/pekko/cluster/typed/internal/AdaptedClusterImpl.scala b/cluster-typed/src/main/scala/org/apache/pekko/cluster/typed/internal/AdaptedClusterImpl.scala index 9ed646b668b..67704001510 100644 --- a/cluster-typed/src/main/scala/org/apache/pekko/cluster/typed/internal/AdaptedClusterImpl.scala +++ b/cluster-typed/src/main/scala/org/apache/pekko/cluster/typed/internal/AdaptedClusterImpl.scala @@ -49,7 +49,7 @@ private[pekko] object AdapterClusterImpl { // important to not eagerly refer to it or we get a cycle here lazy val cluster = Cluster(ctx.system) - def onSelfMemberEvent(event: MemberEvent): Unit = { + def onSelfMemberEvent(event: MemberEvent): Unit = event match { case ClusterEvent.MemberUp(_) => seenState = Up @@ -65,7 +65,6 @@ private[pekko] object AdapterClusterImpl { case _ => // This is fine. } - } Behaviors .receiveMessage[AnyRef] { @@ -124,7 +123,7 @@ private[pekko] object AdapterClusterImpl { .narrow[ClusterStateSubscription] } - private def managerBehavior(adaptedCluster: pekko.cluster.Cluster): Behavior[ClusterCommand] = { + private def managerBehavior(adaptedCluster: pekko.cluster.Cluster): Behavior[ClusterCommand] = Behaviors.receiveMessage { case Join(address) => adaptedCluster.join(address) @@ -147,7 +146,6 @@ private[pekko] object AdapterClusterImpl { Behaviors.same } - } } diff --git a/cluster-typed/src/main/scala/org/apache/pekko/cluster/typed/internal/AdaptedClusterSingletonImpl.scala b/cluster-typed/src/main/scala/org/apache/pekko/cluster/typed/internal/AdaptedClusterSingletonImpl.scala index 6d67d706711..67c79eaa977 100644 --- a/cluster-typed/src/main/scala/org/apache/pekko/cluster/typed/internal/AdaptedClusterSingletonImpl.scala +++ b/cluster-typed/src/main/scala/org/apache/pekko/cluster/typed/internal/AdaptedClusterSingletonImpl.scala @@ -51,25 +51,24 @@ private[pekko] final class AdaptedClusterSingletonImpl(system: ActorSystem[_]) e case None => ClusterSingletonSettings(system) case Some(s) => s } - def poisonPillInterceptor(behv: Behavior[M]): Behavior[M] = { + def poisonPillInterceptor(behv: Behavior[M]): Behavior[M] = singleton.stopMessage match { case Some(_) => behv case None => Behaviors.intercept(() => new PoisonPillInterceptor[M])(behv) } - } if (settings.shouldRunManager(cluster)) { val managerName = managerNameFor(singleton.name) // start singleton on this node val classicProps = PropsAdapter(poisonPillInterceptor(singleton.behavior), singleton.props) - try { + try classicSystem.systemActorOf( OldSingletonManager.props( classicProps, singleton.stopMessage.getOrElse(PoisonPill), settings.toManagerSettings(singleton.name)), managerName) - } catch { + catch { case ex: InvalidActorNameException if ex.getMessage.endsWith("is not unique!") => // This is fine. We just wanted to make sure it is running and it already is } diff --git a/cluster-typed/src/main/scala/org/apache/pekko/cluster/typed/internal/PekkoClusterTypedSerializer.scala b/cluster-typed/src/main/scala/org/apache/pekko/cluster/typed/internal/PekkoClusterTypedSerializer.scala index f813179af76..177f0db3291 100644 --- a/cluster-typed/src/main/scala/org/apache/pekko/cluster/typed/internal/PekkoClusterTypedSerializer.scala +++ b/cluster-typed/src/main/scala/org/apache/pekko/cluster/typed/internal/PekkoClusterTypedSerializer.scala @@ -63,13 +63,12 @@ private[pekko] final class PekkoClusterTypedSerializer(override val system: Exte s"Unimplemented deserialization of message with manifest [$manifest] in [${getClass.getName}]") } - private def pubSubPublishToBinary(m: TopicImpl.MessagePublished[_]): Array[Byte] = { + private def pubSubPublishToBinary(m: TopicImpl.MessagePublished[_]): Array[Byte] = ClusterMessages.PubSubMessagePublished .newBuilder() .setMessage(payloadSupport.payloadBuilder(m.message)) .build() .toByteArray - } private def receptionistEntryToBinary(e: Entry): Array[Byte] = { val b = ClusterMessages.ReceptionistEntry diff --git a/cluster-typed/src/main/scala/org/apache/pekko/cluster/typed/internal/delivery/ReliableDeliverySerializer.scala b/cluster-typed/src/main/scala/org/apache/pekko/cluster/typed/internal/delivery/ReliableDeliverySerializer.scala index a1b8b5fe906..d06b56ed5b9 100644 --- a/cluster-typed/src/main/scala/org/apache/pekko/cluster/typed/internal/delivery/ReliableDeliverySerializer.scala +++ b/cluster-typed/src/main/scala/org/apache/pekko/cluster/typed/internal/delivery/ReliableDeliverySerializer.scala @@ -140,9 +140,8 @@ import pekko.remote.ByteStringUtils b.build().toByteArray() } - private def durableQueueMessageSentToBinary(m: DurableProducerQueue.MessageSent[_]): Array[Byte] = { + private def durableQueueMessageSentToBinary(m: DurableProducerQueue.MessageSent[_]): Array[Byte] = durableQueueMessageSentToProto(m).toByteArray() - } private def durableQueueMessageSentToProto(m: DurableProducerQueue.MessageSent[_]): ReliableDelivery.MessageSent = { val b = ReliableDelivery.MessageSent.newBuilder() @@ -163,9 +162,8 @@ import pekko.remote.ByteStringUtils b.build() } - private def durableQueueConfirmedToBinary(m: DurableProducerQueue.Confirmed): _root_.scala.Array[Byte] = { + private def durableQueueConfirmedToBinary(m: DurableProducerQueue.Confirmed): _root_.scala.Array[Byte] = durableQueueConfirmedToProto(m.confirmationQualifier, m.seqNr, m.timestampMillis).toByteArray() - } private def durableQueueConfirmedToProto( qualifier: String, diff --git a/cluster-typed/src/main/scala/org/apache/pekko/cluster/typed/internal/receptionist/ClusterReceptionist.scala b/cluster-typed/src/main/scala/org/apache/pekko/cluster/typed/internal/receptionist/ClusterReceptionist.scala index 5eed8a4be7d..167ee1995e8 100644 --- a/cluster-typed/src/main/scala/org/apache/pekko/cluster/typed/internal/receptionist/ClusterReceptionist.scala +++ b/cluster-typed/src/main/scala/org/apache/pekko/cluster/typed/internal/receptionist/ClusterReceptionist.scala @@ -98,11 +98,10 @@ private[typed] object ClusterReceptionist extends ReceptionistBehaviorProvider { subscriptions: SubscriptionRegistry) { /** tombstone all services actor is registered for */ - def addTombstone(actor: ActorRef[_], deadline: Deadline): State = { + def addTombstone(actor: ActorRef[_], deadline: Deadline): State = servicesPerActor.getOrElse(actor, Set.empty).foldLeft(this) { (state, key) => state.addTombstone(actor.asInstanceOf[ActorRef[key.Protocol]], key.asServiceKey, deadline) } - } /** tombstone specific service actor is registered for */ def addTombstone[T](actor: ActorRef[T], serviceKey: ServiceKey[T], deadline: Deadline): State = { @@ -113,7 +112,7 @@ private[typed] object ClusterReceptionist extends ReceptionistBehaviorProvider { def hasTombstone[T](serviceKey: ServiceKey[T])(actorRef: ActorRef[T]): Boolean = tombstones.nonEmpty && tombstones.getOrElse(actorRef, Set.empty).exists { case (key, _) => key == serviceKey } - def pruneTombstones(): State = { + def pruneTombstones(): State = if (tombstones.isEmpty) this else { val newTombstones: Map[ActorRef[_], Set[(AbstractServiceKey, Deadline)]] = @@ -129,7 +128,6 @@ private[typed] object ClusterReceptionist extends ReceptionistBehaviorProvider { if (newTombstones eq tombstones) this else copy(tombstones = newTombstones) } - } /** * @return (reachable-nodes, all) @@ -273,9 +271,8 @@ private[typed] object ClusterReceptionist extends ReceptionistBehaviorProvider { Behaviors.setup { ctx => import setup._ - def isLeader = { + def isLeader = cluster.state.leader.contains(cluster.selfAddress) - } def nodesRemoved(addresses: Set[UniqueAddress], onlyRemoveOldEntries: Boolean): Unit = { // ok to update from several nodes but more efficient to try to do it from one node @@ -286,7 +283,7 @@ private[typed] object ClusterReceptionist extends ReceptionistBehaviorProvider { // it possible that an entry is added before MemberJoined is visible and such entries should not be removed def isOld(entry: Entry): Boolean = (now - entry.createdTimestamp) >= settings.pruneRemovedOlderThan.toMillis - val removals = { + val removals = state.registry.allServices.foldLeft(Map.empty[AbstractServiceKey, Set[Entry]]) { case (acc, (key, entries)) => val removedEntries = @@ -295,7 +292,6 @@ private[typed] object ClusterReceptionist extends ReceptionistBehaviorProvider { if (removedEntries.isEmpty) acc // no change else acc + (key -> removedEntries) } - } if (removals.nonEmpty) { if (ctx.log.isDebugEnabled) @@ -322,14 +318,13 @@ private[typed] object ClusterReceptionist extends ReceptionistBehaviorProvider { } } - def reachabilityChanged(keysForNode: Set[AbstractServiceKey], newState: State): Unit = { + def reachabilityChanged(keysForNode: Set[AbstractServiceKey], newState: State): Unit = notifySubscribers(keysForNode, servicesWereAddedOrRemoved = false, newState) - } def notifySubscribers( changedKeys: Set[AbstractServiceKey], servicesWereAddedOrRemoved: Boolean, - newState: State): Unit = { + newState: State): Unit = changedKeys.foreach { changedKey => val serviceKey = changedKey.asServiceKey @@ -341,7 +336,6 @@ private[typed] object ClusterReceptionist extends ReceptionistBehaviorProvider { subscribers.foreach(_ ! listing) } } - } def onCommand(cmd: Command): Behavior[Command] = cmd match { case ReceptionistMessages.Register(key, serviceInstance, maybeReplyTo) => diff --git a/cluster-typed/src/main/scala/org/apache/pekko/cluster/typed/internal/receptionist/Registry.scala b/cluster-typed/src/main/scala/org/apache/pekko/cluster/typed/internal/receptionist/Registry.scala index 3f96258eade..fdba17a7bb4 100644 --- a/cluster-typed/src/main/scala/org/apache/pekko/cluster/typed/internal/receptionist/Registry.scala +++ b/cluster-typed/src/main/scala/org/apache/pekko/cluster/typed/internal/receptionist/Registry.scala @@ -134,7 +134,7 @@ import pekko.cluster.typed.internal.receptionist.ClusterReceptionist.{ DDataKey, def removeBinding[T](key: ServiceKey[T], value: Entry)(implicit node: SelfUniqueAddress): ServiceRegistry = copy(entries = entries.removeBinding(node, key, value)) - def removeAll(entries: Map[AbstractServiceKey, Set[Entry]])(implicit node: SelfUniqueAddress): ServiceRegistry = { + def removeAll(entries: Map[AbstractServiceKey, Set[Entry]])(implicit node: SelfUniqueAddress): ServiceRegistry = entries.foldLeft(this) { case (acc, (key, entries)) => entries.foldLeft(acc) { @@ -142,7 +142,6 @@ import pekko.cluster.typed.internal.receptionist.ClusterReceptionist.{ DDataKey, innerAcc.removeBinding[key.Protocol](key.asServiceKey, entry) } } - } def toORMultiMap: ORMultiMap[ServiceKey[_], Entry] = entries diff --git a/cluster-typed/src/multi-jvm/scala/org/apache/pekko/cluster/typed/ChunkLargeMessageSpec.scala b/cluster-typed/src/multi-jvm/scala/org/apache/pekko/cluster/typed/ChunkLargeMessageSpec.scala index a1e080680b9..be64a8eca8f 100644 --- a/cluster-typed/src/multi-jvm/scala/org/apache/pekko/cluster/typed/ChunkLargeMessageSpec.scala +++ b/cluster-typed/src/multi-jvm/scala/org/apache/pekko/cluster/typed/ChunkLargeMessageSpec.scala @@ -57,8 +57,7 @@ object ChunkLargeMessageSpec extends MultiNodeConfig { numberOfMessages: Int, large: Boolean, delay: FiniteDuration, - producerController: ActorRef[ProducerController.Command[Consumer.TheMessage]]): Behavior[Command] = { - + producerController: ActorRef[ProducerController.Command[Consumer.TheMessage]]): Behavior[Command] = Behaviors.setup { context => val requestNextAdapter = context.messageAdapter[ProducerController.RequestNext[Consumer.TheMessage]](WrappedRequestNext(_)) @@ -111,7 +110,6 @@ object ChunkLargeMessageSpec extends MultiNodeConfig { } } - } } @@ -125,7 +123,7 @@ object ChunkLargeMessageSpec extends MultiNodeConfig { private final case class WrappedDelivery(d: ConsumerController.Delivery[TheMessage]) extends Command case object Stop extends Command - def apply(consumerController: ActorRef[ConsumerController.Start[TheMessage]]): Behavior[Command] = { + def apply(consumerController: ActorRef[ConsumerController.Start[TheMessage]]): Behavior[Command] = Behaviors.setup { context => val deliveryAdapter = context.messageAdapter[ConsumerController.Delivery[TheMessage]](WrappedDelivery(_)) @@ -140,7 +138,6 @@ object ChunkLargeMessageSpec extends MultiNodeConfig { Behaviors.stopped } } - } } } diff --git a/cluster-typed/src/multi-jvm/scala/org/apache/pekko/cluster/typed/MultiNodeTypedClusterSpec.scala b/cluster-typed/src/multi-jvm/scala/org/apache/pekko/cluster/typed/MultiNodeTypedClusterSpec.scala index 57b2f7b5fbd..2678ea64686 100644 --- a/cluster-typed/src/multi-jvm/scala/org/apache/pekko/cluster/typed/MultiNodeTypedClusterSpec.scala +++ b/cluster-typed/src/multi-jvm/scala/org/apache/pekko/cluster/typed/MultiNodeTypedClusterSpec.scala @@ -69,7 +69,7 @@ trait MultiNodeTypedClusterSpec extends Suite with STMultiNodeSpec with WatchedB * and then restarting a role (jvm) with another address is not * supported. */ - implicit def address(role: RoleName): Address = { + implicit def address(role: RoleName): Address = cachedAddresses.get(role) match { case null => val address = node(role).address @@ -77,7 +77,6 @@ trait MultiNodeTypedClusterSpec extends Suite with STMultiNodeSpec with WatchedB address case address => address } - } def formCluster(first: RoleName, rest: RoleName*): Unit = { runOn(first) { diff --git a/cluster-typed/src/test/scala/docs/org/apache/pekko/cluster/ddata/typed/scaladsl/ReplicatorDocSpec.scala b/cluster-typed/src/test/scala/docs/org/apache/pekko/cluster/ddata/typed/scaladsl/ReplicatorDocSpec.scala index 8b3a4096fa9..b48fd0fe9e9 100644 --- a/cluster-typed/src/test/scala/docs/org/apache/pekko/cluster/ddata/typed/scaladsl/ReplicatorDocSpec.scala +++ b/cluster-typed/src/test/scala/docs/org/apache/pekko/cluster/ddata/typed/scaladsl/ReplicatorDocSpec.scala @@ -68,7 +68,7 @@ object ReplicatorDocSpec { replicatorAdapter.subscribe(key, InternalSubscribeResponse.apply) // #subscribe - def updated(cachedValue: Int): Behavior[Command] = { + def updated(cachedValue: Int): Behavior[Command] = Behaviors.receiveMessage[Command] { case Increment => replicatorAdapter.askUpdate( @@ -115,7 +115,6 @@ object ReplicatorDocSpec { } } - } updated(cachedValue = 0) } diff --git a/cluster-typed/src/test/scala/docs/org/apache/pekko/cluster/typed/DistributedPubSubExample.scala b/cluster-typed/src/test/scala/docs/org/apache/pekko/cluster/typed/DistributedPubSubExample.scala index ca85cb8b58f..469554db773 100644 --- a/cluster-typed/src/test/scala/docs/org/apache/pekko/cluster/typed/DistributedPubSubExample.scala +++ b/cluster-typed/src/test/scala/docs/org/apache/pekko/cluster/typed/DistributedPubSubExample.scala @@ -92,7 +92,7 @@ object Publisher { */ object RegistrationService { - def apply(): Behavior[AnyRef] = { + def apply(): Behavior[AnyRef] = // #publisher Behaviors.setup[AnyRef] { context => import pekko.cluster.pubsub.DistributedPubSub @@ -118,9 +118,8 @@ object Publisher { } } - def validate(schema: Schema): Try[Schema] = { + def validate(schema: Schema): Try[Schema] = Success(schema) // called, stubbed - } Behaviors.receiveMessage { case RegisterDataType(key, schema, replyTo, onBehalfOf) => @@ -131,9 +130,8 @@ object Publisher { Behaviors.unhandled } } - // #publisher + // #publisher - } } } @@ -141,7 +139,7 @@ object Publisher { object Ingestion { import Ontology._ - def apply(dt: DataType, mediator: pekko.actor.ActorRef): Behavior[DataEvent] = { + def apply(dt: DataType, mediator: pekko.actor.ActorRef): Behavior[DataEvent] = // #destination Behaviors.setup { context => // register to the path @@ -150,8 +148,7 @@ object Ingestion { idle(dt, mediator) } - // #destination - } + // #destination private def idle(dt: DataType, mediator: pekko.actor.ActorRef): Behavior[DataEvent] = Behaviors.setup { context => @@ -192,8 +189,7 @@ object Ingestion { object Subscriber { import Ontology._ - def apply(key: DataKey, mediator: pekko.actor.ActorRef): Behavior[DataEvent] = { - + def apply(key: DataKey, mediator: pekko.actor.ActorRef): Behavior[DataEvent] = // #subscriber Behaviors.setup[DataEvent] { context => import pekko.actor.typed.scaladsl.adapter._ @@ -223,12 +219,10 @@ object Subscriber { } } - // #subscriber - } + // #subscriber - private def wonderland(): Behavior[DataEvent] = { + private def wonderland(): Behavior[DataEvent] = Behaviors.same - } private def andThen(key: DataKey, mediator: pekko.actor.ActorRef): Behavior[DataEvent] = { // for the example, shutdown @@ -240,7 +234,7 @@ object Subscriber { object DataService { import Ontology._ - def apply(mediator: pekko.actor.ActorRef): Behavior[DataApi] = { + def apply(mediator: pekko.actor.ActorRef): Behavior[DataApi] = Behaviors.setup { context => val registration = context.spawn(Publisher.RegistrationService(), "data-registration") @@ -262,14 +256,13 @@ object DataService { } } - } } object DataPlatform { import Ontology._ - def apply(): Behavior[ProvisionCommand] = { + def apply(): Behavior[ProvisionCommand] = Behaviors.setup { context => // #mediator val mediator = DistributedPubSub(context.system).mediator @@ -288,7 +281,6 @@ object DataPlatform { } } - } } object DistributedPubSubExample { @@ -313,9 +305,8 @@ object DistributedPubSubExample { } val awaitClusterUp = (nodes: List[ActorSystem[_]], expected: Int) => - while (!clusterUp(nodes, expected)) { + while (!clusterUp(nodes, expected)) Thread.sleep(1000) - } val seed = nodes.head val joinTo = Cluster(seed).selfMember.address diff --git a/cluster-typed/src/test/scala/docs/org/apache/pekko/cluster/typed/PingSerializer.scala b/cluster-typed/src/test/scala/docs/org/apache/pekko/cluster/typed/PingSerializer.scala index 3eb6975a5d9..0d60342c35d 100644 --- a/cluster-typed/src/test/scala/docs/org/apache/pekko/cluster/typed/PingSerializer.scala +++ b/cluster-typed/src/test/scala/docs/org/apache/pekko/cluster/typed/PingSerializer.scala @@ -47,7 +47,7 @@ class PingSerializer(system: ExtendedActorSystem) extends SerializerWithStringMa throw new IllegalArgumentException(s"Can't serialize object of type ${msg.getClass} in [${getClass.getName}]") } - override def fromBinary(bytes: Array[Byte], manifest: String) = { + override def fromBinary(bytes: Array[Byte], manifest: String) = manifest match { case PingManifest => val str = new String(bytes, StandardCharsets.UTF_8) @@ -58,6 +58,5 @@ class PingSerializer(system: ExtendedActorSystem) extends SerializerWithStringMa case _ => throw new IllegalArgumentException(s"Unknown manifest [$manifest]") } - } } //#serializer diff --git a/cluster-typed/src/test/scala/docs/org/apache/pekko/cluster/typed/ReceptionistExample.scala b/cluster-typed/src/test/scala/docs/org/apache/pekko/cluster/typed/ReceptionistExample.scala index 9ba17c39d17..06f4474ca51 100644 --- a/cluster-typed/src/test/scala/docs/org/apache/pekko/cluster/typed/ReceptionistExample.scala +++ b/cluster-typed/src/test/scala/docs/org/apache/pekko/cluster/typed/ReceptionistExample.scala @@ -30,7 +30,7 @@ object PingPongExample { final case class Ping(replyTo: ActorRef[Pong.type]) case object Pong - def apply(): Behavior[Ping] = { + def apply(): Behavior[Ping] = Behaviors.setup { context => context.system.receptionist ! Receptionist.Register(PingServiceKey, context.self) @@ -41,13 +41,12 @@ object PingPongExample { Behaviors.same } } - } } // #ping-service // #pinger object Pinger { - def apply(pingService: ActorRef[PingService.Ping]): Behavior[PingService.Pong.type] = { + def apply(pingService: ActorRef[PingService.Ping]): Behavior[PingService.Pong.type] = Behaviors.setup { context => pingService ! PingService.Ping(context.self) @@ -56,13 +55,12 @@ object PingPongExample { Behaviors.stopped } } - } } // #pinger // #pinger-guardian object Guardian { - def apply(): Behavior[Nothing] = { + def apply(): Behavior[Nothing] = Behaviors .setup[Receptionist.Listing] { context => context.spawnAnonymous(PingService()) @@ -75,7 +73,6 @@ object PingPongExample { } } .narrow - } } // #pinger-guardian @@ -85,7 +82,7 @@ object PingPongExample { case object PingAll extends Command private case class ListingResponse(listing: Receptionist.Listing) extends Command - def apply(): Behavior[Command] = { + def apply(): Behavior[Command] = Behaviors.setup[Command] { context => val listingResponseAdapter = context.messageAdapter[Receptionist.Listing](ListingResponse.apply) @@ -100,7 +97,6 @@ object PingPongExample { Behaviors.same } } - } } // #find diff --git a/cluster-typed/src/test/scala/docs/org/apache/pekko/cluster/typed/SingletonCompileOnlySpec.scala b/cluster-typed/src/test/scala/docs/org/apache/pekko/cluster/typed/SingletonCompileOnlySpec.scala index ecdf6ac82ca..fb07e97b16c 100644 --- a/cluster-typed/src/test/scala/docs/org/apache/pekko/cluster/typed/SingletonCompileOnlySpec.scala +++ b/cluster-typed/src/test/scala/docs/org/apache/pekko/cluster/typed/SingletonCompileOnlySpec.scala @@ -32,7 +32,7 @@ object SingletonCompileOnlySpec { case object GoodByeCounter extends Command def apply(): Behavior[Command] = { - def updated(value: Int): Behavior[Command] = { + def updated(value: Int): Behavior[Command] = Behaviors.receiveMessage[Command] { case Increment => updated(value + 1) @@ -43,7 +43,6 @@ object SingletonCompileOnlySpec { // Possible async action then stop Behaviors.stopped } - } updated(0) } diff --git a/cluster-typed/src/test/scala/org/apache/pekko/cluster/typed/ClusterApiSpec.scala b/cluster-typed/src/test/scala/org/apache/pekko/cluster/typed/ClusterApiSpec.scala index 619fbfaebe4..40070359619 100644 --- a/cluster-typed/src/test/scala/org/apache/pekko/cluster/typed/ClusterApiSpec.scala +++ b/cluster-typed/src/test/scala/org/apache/pekko/cluster/typed/ClusterApiSpec.scala @@ -117,9 +117,8 @@ class ClusterApiSpec extends ScalaTestWithActorTestKit(ClusterApiSpec.config) wi clusterNode2.subscriptions ! Subscribe(node2Probe.ref, classOf[SelfUp]) node2Probe.expectNoMessage() - } finally { + } finally ActorTestKit.shutdown(adaptedSystem2) - } } } diff --git a/cluster-typed/src/test/scala/org/apache/pekko/cluster/typed/RemoteDeployNotAllowedSpec.scala b/cluster-typed/src/test/scala/org/apache/pekko/cluster/typed/RemoteDeployNotAllowedSpec.scala index ed0d7d8e3f4..ebb067086bf 100644 --- a/cluster-typed/src/test/scala/org/apache/pekko/cluster/typed/RemoteDeployNotAllowedSpec.scala +++ b/cluster-typed/src/test/scala/org/apache/pekko/cluster/typed/RemoteDeployNotAllowedSpec.scala @@ -71,22 +71,22 @@ class RemoteDeployNotAllowedSpec msg match { case SpawnChild(name) => // this should throw - try { + try ctx.spawn(Behaviors.setup[AnyRef] { _ => Behaviors.empty }, name) - } catch { + catch { case ex: Exception => probe.ref ! ex } Behaviors.same case SpawnAnonymous => // this should throw - try { + try ctx.spawnAnonymous(Behaviors.setup[AnyRef] { _ => Behaviors.empty }) - } catch { + catch { case ex: Exception => probe.ref ! ex } Behaviors.same @@ -110,9 +110,8 @@ class RemoteDeployNotAllowedSpec system2 ! SpawnAnonymous probe.expectMessageType[Exception].getMessage should ===("Remote deployment not allowed for typed actors") - } finally { + } finally ActorTestKit.shutdown(system2) - } } } diff --git a/cluster-typed/src/test/scala/org/apache/pekko/cluster/typed/RemoteMessageSpec.scala b/cluster-typed/src/test/scala/org/apache/pekko/cluster/typed/RemoteMessageSpec.scala index fb802f2b015..a8b775203a2 100644 --- a/cluster-typed/src/test/scala/org/apache/pekko/cluster/typed/RemoteMessageSpec.scala +++ b/cluster-typed/src/test/scala/org/apache/pekko/cluster/typed/RemoteMessageSpec.scala @@ -86,9 +86,8 @@ class RemoteMessageSpec extends PekkoSpec(RemoteMessageSpec.config) { pingPromise.future.futureValue should ===(Done) pongPromise.future.futureValue should ===(Done) - } finally { + } finally system2.terminate() - } } } diff --git a/cluster-typed/src/test/scala/org/apache/pekko/cluster/typed/internal/PekkoClusterTypedSerializerSpec.scala b/cluster-typed/src/test/scala/org/apache/pekko/cluster/typed/internal/PekkoClusterTypedSerializerSpec.scala index 8b53bcbbf77..dfcb60661f9 100644 --- a/cluster-typed/src/test/scala/org/apache/pekko/cluster/typed/internal/PekkoClusterTypedSerializerSpec.scala +++ b/cluster-typed/src/test/scala/org/apache/pekko/cluster/typed/internal/PekkoClusterTypedSerializerSpec.scala @@ -45,8 +45,7 @@ class PekkoClusterTypedSerializerSpec extends ScalaTestWithActorTestKit with Any } } - def verifySerialization(msg: AnyRef): Unit = { + def verifySerialization(msg: AnyRef): Unit = serializer.fromBinary(serializer.toBinary(msg), serializer.manifest(msg)) should be(msg) - } } diff --git a/cluster-typed/src/test/scala/org/apache/pekko/cluster/typed/internal/delivery/ReliableDeliverySerializerSpec.scala b/cluster-typed/src/test/scala/org/apache/pekko/cluster/typed/internal/delivery/ReliableDeliverySerializerSpec.scala index 23b645c4f77..3cfbea5d65d 100644 --- a/cluster-typed/src/test/scala/org/apache/pekko/cluster/typed/internal/delivery/ReliableDeliverySerializerSpec.scala +++ b/cluster-typed/src/test/scala/org/apache/pekko/cluster/typed/internal/delivery/ReliableDeliverySerializerSpec.scala @@ -88,8 +88,7 @@ class ReliableDeliverySerializerSpec extends ScalaTestWithActorTestKit with AnyW } } - def verifySerialization(msg: AnyRef): Unit = { + def verifySerialization(msg: AnyRef): Unit = serializer.fromBinary(serializer.toBinary(msg), serializer.manifest(msg)) should be(msg) - } } diff --git a/cluster-typed/src/test/scala/org/apache/pekko/cluster/typed/internal/receptionist/ClusterReceptionistSpec.scala b/cluster-typed/src/test/scala/org/apache/pekko/cluster/typed/internal/receptionist/ClusterReceptionistSpec.scala index 03f1ab39523..16dbfbf1775 100644 --- a/cluster-typed/src/test/scala/org/apache/pekko/cluster/typed/internal/receptionist/ClusterReceptionistSpec.scala +++ b/cluster-typed/src/test/scala/org/apache/pekko/cluster/typed/internal/receptionist/ClusterReceptionistSpec.scala @@ -212,10 +212,9 @@ class ClusterReceptionistSpec extends AnyWordSpec with Matchers with LogCapturin clusterNode1.manager ! Leave(clusterNode2.selfMember.address) } - regProbe1.awaitAssert({ - // we will also potentially get an update that the service was unreachable before the expected one - regProbe1.expectMessage(10.seconds, Listing(PingKey, Set(service1))) - }, 10.seconds) + regProbe1.awaitAssert( + // we will also potentially get an update that the service was unreachable before the expected one + regProbe1.expectMessage(10.seconds, Listing(PingKey, Set(service1))), 10.seconds) // register another after removal val service1b = testKit1.spawn(pingPongBehavior) @@ -267,10 +266,9 @@ class ClusterReceptionistSpec extends AnyWordSpec with Matchers with LogCapturin clusterNode2.manager ! Down(clusterNode1.selfMember.address) // service1 removed - regProbe2.awaitAssert({ - // we will also potentially get an update that the service was unreachable before the expected one - regProbe2.expectMessage(10.seconds, Listing(PingKey, Set(service2))) - }, 10.seconds) + regProbe2.awaitAssert( + // we will also potentially get an update that the service was unreachable before the expected one + regProbe2.expectMessage(10.seconds, Listing(PingKey, Set(service2))), 10.seconds) } finally { testKit1.shutdownTestKit() testKit2.shutdownTestKit() @@ -325,11 +323,9 @@ class ClusterReceptionistSpec extends AnyWordSpec with Matchers with LogCapturin system2.terminate() Await.ready(system2.whenTerminated, 10.seconds) clusterNode1.manager ! Down(clusterNode2.selfMember.address) - regProbe1.awaitAssert({ - - // we will also potentially get an update that the service was unreachable before the expected one - regProbe1.expectMessage(10.seconds, Listing(PingKey, Set.empty[ActorRef[PingProtocol]])) - }, 10.seconds) + regProbe1.awaitAssert( + // we will also potentially get an update that the service was unreachable before the expected one + regProbe1.expectMessage(10.seconds, Listing(PingKey, Set.empty[ActorRef[PingProtocol]])), 10.seconds) } finally { testKit1.shutdownTestKit() testKit2.shutdownTestKit() @@ -399,12 +395,10 @@ class ClusterReceptionistSpec extends AnyWordSpec with Matchers with LogCapturin // make sure it joined fine and node1 has upped it regProbe1.awaitAssert( - { - clusterNode1.state.members.exists(m => - m.uniqueAddress == clusterNode3.selfMember.uniqueAddress && - m.status == MemberStatus.Up && - !clusterNode1.state.unreachable(m)) should ===(true) - }, + clusterNode1.state.members.exists(m => + m.uniqueAddress == clusterNode3.selfMember.uniqueAddress && + m.status == MemberStatus.Up && + !clusterNode1.state.unreachable(m)) should ===(true), 10.seconds) // we should get either empty message and then updated with the new incarnation actor @@ -426,9 +420,8 @@ class ClusterReceptionistSpec extends AnyWordSpec with Matchers with LogCapturin ref ! Ping(regProbe1.ref) regProbe1.expectMessage(Pong) - } finally { + } finally testKit3.shutdownTestKit() - } } finally { testKit1.shutdownTestKit() testKit2.shutdownTestKit() @@ -533,9 +526,8 @@ class ClusterReceptionistSpec extends AnyWordSpec with Matchers with LogCapturin system1.receptionist ! Find(PingKey, reply1.ref) (reply1.receiveMessage().serviceInstances(PingKey) should contain).allOf(service1, service1b, service1c) - } finally { + } finally testKit3.shutdownTestKit() - } } finally { testKit1.shutdownTestKit() testKit2.shutdownTestKit() @@ -615,11 +607,10 @@ class ClusterReceptionistSpec extends AnyWordSpec with Matchers with LogCapturin "not conflict with the ClusterClient receptionist default name".taggedAs(LongRunningTest, GHExcludeAeronTest) in { val testKit = ActorTestKit(s"ClusterReceptionistSpec-test-9", ClusterReceptionistSpec.config) - try { + try testKit.system.systemActorOf(Behaviors.ignore, "receptionist") - } finally { + finally testKit.shutdownTestKit() - } } "handle unregistration and re-registration of services".taggedAs(LongRunningTest, GHExcludeAeronTest) in { @@ -875,9 +866,8 @@ class ClusterReceptionistSpec extends AnyWordSpec with Matchers with LogCapturin val durableStorePath = replicatorPath / "durableStore" classicSystem.actorSelection(durableStorePath).resolveOne(testKit.timeout.duration).failed.futureValue - } finally { + } finally testKit.shutdownTestKit() - } } } } diff --git a/cluster/src/main/scala/org/apache/pekko/cluster/Cluster.scala b/cluster/src/main/scala/org/apache/pekko/cluster/Cluster.scala index b8b05df74dc..af0cec298c8 100644 --- a/cluster/src/main/scala/org/apache/pekko/cluster/Cluster.scala +++ b/cluster/src/main/scala/org/apache/pekko/cluster/Cluster.scala @@ -144,14 +144,13 @@ class Cluster(val system: ExtendedActorSystem) extends Extension { DowningProvider.load(settings.DowningProviderClassName, system) } - private def checkAutoDownUsage(): Unit = { + private def checkAutoDownUsage(): Unit = if (settings.DowningProviderClassName == "org.apache.pekko.cluster.AutoDowning" || (settings.config.hasPath("auto-down-unreachable-after") && settings.config.getString( "auto-down-unreachable-after") != "off")) logWarning( "auto-down has been removed in Akka 2.6.0. See " + "https://pekko.apache.org/docs/pekko/current/typed/cluster.html#downing for alternatives.") - } // ======================================================== // ===================== WORK DAEMONS ===================== @@ -160,7 +159,7 @@ class Cluster(val system: ExtendedActorSystem) extends Extension { /** * INTERNAL API */ - private[cluster] val scheduler: Scheduler = { + private[cluster] val scheduler: Scheduler = if (system.scheduler.maxFrequency < 1.second / SchedulerTickDuration) { logInfo( "Using a dedicated scheduler for cluster. Default scheduler can be used if configured " + @@ -199,23 +198,21 @@ class Cluster(val system: ExtendedActorSystem) extends Extension { systemScheduler.scheduleOnce(delay, runnable) } } - } // create supervisor for daemons under path "/system/cluster" - private val clusterDaemons: ActorRef = { + private val clusterDaemons: ActorRef = system.systemActorOf( Props(classOf[ClusterDaemon], joinConfigCompatChecker).withDispatcher(UseDispatcher).withDeploy(Deploy.local), name = "cluster") - } /** * INTERNAL API */ private[cluster] val clusterCore: ActorRef = { implicit val timeout = system.settings.CreationTimeout - try { + try Await.result((clusterDaemons ? InternalClusterAction.GetClusterCoreRef).mapTo[ActorRef], timeout.duration) - } catch { + catch { case NonFatal(e) => log.error(e, "Failed to startup Cluster. You can try to increase 'pekko.actor.creation-timeout'.") shutdown() @@ -334,15 +331,13 @@ class Cluster(val system: ExtendedActorSystem) extends Extension { /** * Change the state of every member in preparation for a full cluster shutdown. */ - def prepareForFullClusterShutdown(): Unit = { + def prepareForFullClusterShutdown(): Unit = clusterCore ! ClusterUserAction.PrepareForShutdown - } - private def fillLocal(address: Address): Address = { + private def fillLocal(address: Address): Address = // local address might be used if grabbed from actorRef.path.address if (address.hasLocalScope && address.system == selfAddress.system) selfAddress else address - } /** * Join the specified seed nodes without defining them in config. @@ -429,12 +424,11 @@ class Cluster(val system: ExtendedActorSystem) extends Extension { * If this is called "at the same time" as `shutdown()` there is a possibility that the the thunk * is not invoked. It's often better to use [[pekko.actor.CoordinatedShutdown]] for this purpose. */ - def registerOnMemberRemoved(callback: Runnable): Unit = { + def registerOnMemberRemoved(callback: Runnable): Unit = if (_isTerminated.get()) callback.run() else clusterDaemons ! InternalClusterAction.AddOnMemberRemovedListener(callback) - } /** * Generate the remote actor path by replacing the Address in the RootActor Path for the given @@ -461,7 +455,7 @@ class Cluster(val system: ExtendedActorSystem) extends Extension { * Should not called by the user. The user can issue a LEAVE command which will tell the node * to go through graceful handoff process `LEAVE -> EXITING -> REMOVED -> SHUTDOWN`. */ - @InternalApi private[cluster] def shutdown(): Unit = { + @InternalApi private[cluster] def shutdown(): Unit = if (_isTerminated.compareAndSet(false, true)) { logInfo("Shutting down...") @@ -473,11 +467,10 @@ class Cluster(val system: ExtendedActorSystem) extends Extension { closeScheduler() - clusterJmx.foreach { _.unregisterMBean() } + clusterJmx.foreach(_.unregisterMBean()) logInfo("Successfully shut down") } - } private def closeScheduler(): Unit = scheduler match { case x: Closeable => x.close() @@ -588,12 +581,11 @@ class Cluster(val system: ExtendedActorSystem) extends Extension { if (log.isErrorEnabled) logAtLevel(Logging.ErrorLevel, log.format(template, arg1, arg2, arg3)) - def logError(cause: Throwable, message: String): Unit = { + def logError(cause: Throwable, message: String): Unit = if (settings.SelfDataCenter == ClusterSettings.DefaultDataCenter) log.error(cause, "Cluster Node [{}] - {}", selfAddress, message) else log.error(cause, "Cluster Node [{}] dc [{}] - {}", selfAddress, settings.SelfDataCenter, message) - } def logError(cause: Throwable, template: String, arg1: Any): Unit = logError(cause, log.format(template, arg1)) @@ -604,14 +596,13 @@ class Cluster(val system: ExtendedActorSystem) extends Extension { def logError(cause: Throwable, template: String, arg1: Any, arg2: Any, arg3: Any): Unit = logError(cause, log.format(template, arg1, arg2, arg3)) - private def logAtLevel(logLevel: LogLevel, message: String): Unit = { + private def logAtLevel(logLevel: LogLevel, message: String): Unit = if (settings.SelfDataCenter == ClusterSettings.DefaultDataCenter) log.log(logLevel, "Cluster Node [{}] - {}", selfAddress, message) else log.log(logLevel, "Cluster Node [{}] dc [{}] - {}", selfAddress, settings.SelfDataCenter, message) - } - private def logAtLevel(marker: LogMarker, logLevel: LogLevel, message: String): Unit = { + private def logAtLevel(marker: LogMarker, logLevel: LogLevel, message: String): Unit = if (settings.SelfDataCenter == ClusterSettings.DefaultDataCenter) log.log(marker, logLevel, log.format("Cluster Node [{}] - {}", selfAddress, message)) else @@ -619,7 +610,6 @@ class Cluster(val system: ExtendedActorSystem) extends Extension { marker, logLevel, log.format("Cluster Node [{}] dc [{}] - {}", selfAddress, settings.SelfDataCenter, message)) - } } diff --git a/cluster/src/main/scala/org/apache/pekko/cluster/ClusterDaemon.scala b/cluster/src/main/scala/org/apache/pekko/cluster/ClusterDaemon.scala index 34320067be1..4283a4352a1 100644 --- a/cluster/src/main/scala/org/apache/pekko/cluster/ClusterDaemon.scala +++ b/cluster/src/main/scala/org/apache/pekko/cluster/ClusterDaemon.scala @@ -469,7 +469,7 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh gossipTask.cancel() failureDetectorReaperTask.cancel() leaderActionsTask.cancel() - publishStatsTask.foreach { _.cancel() } + publishStatsTask.foreach(_.cancel()) selfExiting.trySuccess(Done) } @@ -518,12 +518,11 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh } }: Actor.Receive).orElse(receiveExitingCompleted) - private def resetJoinSeedNodesDeadline(): Unit = { + private def resetJoinSeedNodesDeadline(): Unit = joinSeedNodesDeadline = ShutdownAfterUnsuccessfulJoinSeedNodes match { case d: FiniteDuration => Some(Deadline.now + d) case _ => None // off } - } private def joinSeedNodesWasUnsuccessful(): Unit = { logWarning( @@ -668,7 +667,7 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh } } - def joinSeedNodes(newSeedNodes: immutable.IndexedSeq[Address]): Unit = { + def joinSeedNodes(newSeedNodes: immutable.IndexedSeq[Address]): Unit = if (newSeedNodes.nonEmpty) { stopSeedNodeProcess() @@ -692,7 +691,6 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh } } } - } /** * Try to join this cluster node with the node specified by `address`. @@ -700,7 +698,7 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh * A `Join(selfUniqueAddress)` command is sent to the node to join, * which will reply with a `Welcome` message. */ - def join(address: Address): Unit = { + def join(address: Address): Unit = if (address.protocol != selfAddress.protocol) logWarning( "Trying to join member with wrong protocol, but was ignored, expected [{}] but was [{}]", @@ -730,9 +728,8 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh clusterCore(address) ! Join(selfUniqueAddress, cluster.selfRoles, cluster.settings.AppVersion) } } - } - def stopSeedNodeProcess(): Unit = { + def stopSeedNodeProcess(): Unit = seedNodeProcess match { case Some(s) => // manual join, abort current seedNodeProcess @@ -740,14 +737,13 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh seedNodeProcess = None case None => // no seedNodeProcess in progress } - } /** * State transition to JOINING - new node joining. * Received `Join` message and replies with `Welcome` message, containing * current gossip state, including the new joining member. */ - def joining(joiningNode: UniqueAddress, roles: Set[String], appVersion: Version): Unit = { + def joining(joiningNode: UniqueAddress, roles: Set[String], appVersion: Version): Unit = if (!preparingForShutdown) { val selfStatus = latestGossip.member(selfUniqueAddress).status if (joiningNode.address.protocol != selfAddress.protocol) @@ -833,7 +829,6 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh } else { logInfo("Ignoring join request from [{}] as preparing for shutdown", joiningNode) } - } /** * Accept reply from Join request. @@ -853,7 +848,7 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh } } - def startPrepareForShutdown(): Unit = { + def startPrepareForShutdown(): Unit = if (!preparingForShutdown) { preparingForShutdown = true val changedMembers = latestGossip.members.collect { @@ -872,14 +867,13 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh publishMembershipState() gossip() } - } /** * State transition to LEAVING. * The node will eventually be removed by the leader, after hand-off in EXITING, and only after * removal a new node with same address can join the cluster through the normal joining procedure. */ - def leaving(address: Address): Unit = { + def leaving(address: Address): Unit = // only try to update if the node is available (in the member ring) latestGossip.members.find(_.address == address).foreach { existingMember => if (existingMember.status == Joining || existingMember.status == WeaklyUp || existingMember @@ -900,7 +894,6 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh gossip() } } - } def exitingCompleted() = { logInfo("Exiting completed") @@ -946,11 +939,10 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh exitingConfirmed += node } - def cleanupExitingConfirmed(): Unit = { + def cleanupExitingConfirmed(): Unit = // in case the actual removal was performed by another leader node we if (exitingConfirmed.nonEmpty) exitingConfirmed = exitingConfirmed.filter(n => latestGossip.members.exists(_.uniqueAddress == n)) - } /** * This method is called when a member sees itself as Exiting or Down. @@ -1060,9 +1052,9 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh def receiveGossip(envelope: GossipEnvelope): ReceiveGossipType = { val from = envelope.from val remoteGossip = - try { + try envelope.gossip - } catch { + catch { case NonFatal(t) => gossipLogger.logWarning("Invalid Gossip. This should only happen during a rolling upgrade. {}", t.getMessage) Gossip.empty @@ -1202,7 +1194,7 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh def gossipSpeedupTick(): Unit = if (isGossipSpeedupNeeded) gossip() - def isGossipSpeedupNeeded: Boolean = { + def isGossipSpeedupNeeded: Boolean = if (latestGossip.isMultiDc) { latestGossip.members.exists(m => m.status == Down || m.dataCenter == cluster.selfDataCenter) || latestGossip.overview.seen @@ -1211,16 +1203,14 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh latestGossip.members.exists(m => m.status == Down) || latestGossip.overview.seen.size < latestGossip.members.size / 2 } - } /** * Sends full gossip to `n` other random members. */ - def gossipRandomN(n: Int): Unit = { + def gossipRandomN(n: Int): Unit = if (!isSingletonCluster && n > 0) { gossipTargetSelector.randomNodesForFullGossip(membershipState, n).foreach(gossipTo) } - } /** * Initiates a new round of gossip. @@ -1285,16 +1275,15 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh shutdownSelfWhenDown() } - def checkForPrepareForShutdown(): Unit = { + def checkForPrepareForShutdown(): Unit = if (MembershipState.allowedToPrepareToShutdown( latestGossip.member(selfUniqueAddress).status) && latestGossip.members .exists(m => MembershipState.prepareForShutdownStates(m.status))) { logDebug("Detected full cluster shutdown") self ! ClusterUserAction.PrepareForShutdown } - } - def shutdownSelfWhenDown(): Unit = { + def shutdownSelfWhenDown(): Unit = if (latestGossip.member(selfUniqueAddress).status == Down) { // When all reachable have seen the state this member will shutdown itself when it has // status Down. The down commands should spread before we shutdown. @@ -1313,13 +1302,11 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh selfDownCounter += 1 } } - } - def isMinNrOfMembersFulfilled: Boolean = { + def isMinNrOfMembersFulfilled: Boolean = latestGossip.members.size >= MinNrOfMembers && MinNrOfMembersOfRole.forall { case (role, threshold) => latestGossip.members.count(_.hasRole(role)) >= threshold } - } /** * Leader actions are as follows: @@ -1507,7 +1494,7 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh /** * Reaps the unreachable members according to the failure detector's verdict. */ - def reapUnreachableMembers(): Unit = { + def reapUnreachableMembers(): Unit = if (!isSingletonCluster) { // only scrutinize if we are a non-singleton cluster @@ -1515,10 +1502,9 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh val localOverview = localGossip.overview val localMembers = localGossip.members - def isAvailable(member: Member): Boolean = { + def isAvailable(member: Member): Boolean = if (member.dataCenter == SelfDataCenter) failureDetector.isAvailable(member.address) else crossDcFailureDetector.isAvailable(member.address) - } val newlyDetectedUnreachableMembers = localMembers.filterNot { member => member.uniqueAddress == selfUniqueAddress || @@ -1564,16 +1550,14 @@ private[cluster] class ClusterCoreDaemon(publisher: ActorRef, joinConfigCompatCh } } } - } def isSingletonCluster: Boolean = latestGossip.isSingletonCluster // needed for tests - def sendGossipTo(address: Address): Unit = { + def sendGossipTo(address: Address): Unit = latestGossip.members.foreach(m => if (m.address == address) gossipTo(m.uniqueAddress)) - } /** * Gossips latest gossip to a node. @@ -1674,14 +1658,12 @@ private[cluster] class OnMemberStatusChangedListener(callback: Runnable, status: done() } - private def done(): Unit = { + private def done(): Unit = try callback.run() catch { case NonFatal(e) => logError(e, "[{}] callback failed with [{}]", s"On${to.getSimpleName}", e.getMessage) - } finally { + } finally context.stop(self) - } - } private def isTriggered(m: Member): Boolean = m.uniqueAddress == cluster.selfUniqueAddress && m.status == status @@ -1712,23 +1694,21 @@ private[cluster] final case class GossipStats( def incrementOlderCount(): GossipStats = copy(olderCount = olderCount + 1, receivedGossipCount = receivedGossipCount + 1) - def :+(that: GossipStats): GossipStats = { + def :+(that: GossipStats): GossipStats = GossipStats( this.receivedGossipCount + that.receivedGossipCount, this.mergeCount + that.mergeCount, this.sameCount + that.sameCount, this.newerCount + that.newerCount, this.olderCount + that.olderCount) - } - def :-(that: GossipStats): GossipStats = { + def :-(that: GossipStats): GossipStats = GossipStats( this.receivedGossipCount - that.receivedGossipCount, this.mergeCount - that.mergeCount, this.sameCount - that.sameCount, this.newerCount - that.newerCount, this.olderCount - that.olderCount) - } } diff --git a/cluster/src/main/scala/org/apache/pekko/cluster/ClusterEvent.scala b/cluster/src/main/scala/org/apache/pekko/cluster/ClusterEvent.scala index 9a0f2f9af8f..0e3f14cf9fe 100644 --- a/cluster/src/main/scala/org/apache/pekko/cluster/ClusterEvent.scala +++ b/cluster/src/main/scala/org/apache/pekko/cluster/ClusterEvent.scala @@ -516,7 +516,7 @@ object ClusterEvent { @InternalApi private[cluster] def diffUnreachableDataCenter( oldState: MembershipState, - newState: MembershipState): immutable.Seq[UnreachableDataCenter] = { + newState: MembershipState): immutable.Seq[UnreachableDataCenter] = if (newState eq oldState) Nil else { val otherDcs = (oldState.latestGossip.allDataCenters @@ -527,7 +527,6 @@ object ClusterEvent { currentUnreachableDcs.diff(oldUnreachableDcs).iterator.map(UnreachableDataCenter.apply).to(immutable.IndexedSeq) } - } /** * INTERNAL API @@ -535,7 +534,7 @@ object ClusterEvent { @InternalApi private[cluster] def diffReachableDataCenter( oldState: MembershipState, - newState: MembershipState): immutable.Seq[ReachableDataCenter] = { + newState: MembershipState): immutable.Seq[ReachableDataCenter] = if (newState eq oldState) Nil else { val otherDcs = (oldState.latestGossip.allDataCenters @@ -546,7 +545,6 @@ object ClusterEvent { oldUnreachableDcs.diff(currentUnreachableDcs).iterator.map(ReachableDataCenter.apply).to(immutable.IndexedSeq) } - } /** * INTERNAL API. @@ -600,13 +598,12 @@ object ClusterEvent { * INTERNAL API */ @InternalApi - private[cluster] def diffRolesLeader(oldState: MembershipState, newState: MembershipState): Set[RoleLeaderChanged] = { + private[cluster] def diffRolesLeader(oldState: MembershipState, newState: MembershipState): Set[RoleLeaderChanged] = for { role <- oldState.latestGossip.allRoles.union(newState.latestGossip.allRoles) newLeader = newState.roleLeader(role) if newLeader != oldState.roleLeader(role) } yield RoleLeaderChanged(role, newLeader.map(_.address)) - } /** * INTERNAL API @@ -734,16 +731,15 @@ private[cluster] final class ClusterDomainEventPublisher def subscribe(subscriber: ActorRef, initMode: SubscriptionInitialStateMode, to: Set[Class[_]]): Unit = { initMode match { case InitialStateAsEvents => - def pub(event: AnyRef): Unit = { + def pub(event: AnyRef): Unit = if (to.exists(_.isAssignableFrom(event.getClass))) subscriber ! event - } publishDiff(emptyMembershipState, membershipState, pub) case InitialStateAsSnapshot => sendCurrentClusterState(subscriber) } - to.foreach { eventStream.subscribe(subscriber, _) } + to.foreach(eventStream.subscribe(subscriber, _)) } def unsubscribe(subscriber: ActorRef, to: Option[Class[_]]): Unit = to match { @@ -762,7 +758,6 @@ private[cluster] final class ClusterDomainEventPublisher def publish(event: AnyRef): Unit = eventStream.publish(event) - def clearState(): Unit = { + def clearState(): Unit = membershipState = emptyMembershipState - } } diff --git a/cluster/src/main/scala/org/apache/pekko/cluster/ClusterHeartbeat.scala b/cluster/src/main/scala/org/apache/pekko/cluster/ClusterHeartbeat.scala index 199f1124a57..a5bff910411 100644 --- a/cluster/src/main/scala/org/apache/pekko/cluster/ClusterHeartbeat.scala +++ b/cluster/src/main/scala/org/apache/pekko/cluster/ClusterHeartbeat.scala @@ -151,9 +151,8 @@ private[cluster] class ClusterHeartbeatSender extends Actor { // used for logging warning if actual tick interval is unexpected (e.g. due to starvation) private var tickTimestamp = System.nanoTime() + (PeriodicTasksInitialDelay max HeartbeatInterval).toNanos - override def preStart(): Unit = { + override def preStart(): Unit = cluster.subscribe(self, classOf[MemberEvent], classOf[ReachabilityEvent]) - } override def postStop(): Unit = { state.activeReceivers.foreach(a => failureDetector.remove(a.address)) diff --git a/cluster/src/main/scala/org/apache/pekko/cluster/ClusterJmx.scala b/cluster/src/main/scala/org/apache/pekko/cluster/ClusterJmx.scala index cb79701f1ab..e74222527aa 100644 --- a/cluster/src/main/scala/org/apache/pekko/cluster/ClusterJmx.scala +++ b/cluster/src/main/scala/org/apache/pekko/cluster/ClusterJmx.scala @@ -182,14 +182,13 @@ private[pekko] class ClusterJmx(cluster: Cluster, log: LoggingAdapter) { val unreachable = clusterView.reachability.observersGroupedByUnreachable.toSeq .sortBy(_._1) .map { - case (subject, observers) => { + case (subject, observers) => val observerAddresses = observers.toSeq.sorted.map("\"" + _.address + "\"") s"""{ | "node": "${subject.address}", | "observed-by": [${if (observerAddresses.isEmpty) "" else observerAddresses.mkString("\n ", ",\n ", "\n ")}] | }""".stripMargin - } } .mkString(",\n ") @@ -228,7 +227,7 @@ private[pekko] class ClusterJmx(cluster: Cluster, log: LoggingAdapter) { mBeanServer.registerMBean(mbean, clusterMBeanName) logInfo("Registered cluster JMX MBean [{}]", clusterMBeanName) } catch { - case e: InstanceAlreadyExistsException => { + case e: InstanceAlreadyExistsException => if (cluster.settings.JmxMultiMbeansInSameEnabled) { log.error(e, s"Failed to register Cluster JMX MBean with name=$clusterMBeanName") } else { @@ -236,18 +235,17 @@ private[pekko] class ClusterJmx(cluster: Cluster, log: LoggingAdapter) { s"Could not register Cluster JMX MBean with name=$clusterMBeanName as it is already registered. " + "If you are running multiple clusters in the same JVM, set 'pekko.cluster.jmx.multi-mbeans-in-same-jvm = on' in config") } - } } } /** * Unregisters the cluster JMX MBean from MBean server. */ - def unregisterMBean(): Unit = { - try { + def unregisterMBean(): Unit = + try mBeanServer.unregisterMBean(clusterMBeanName) - } catch { - case e: InstanceNotFoundException => { + catch { + case e: InstanceNotFoundException => if (cluster.settings.JmxMultiMbeansInSameEnabled) { log.error(e, s"Failed to unregister Cluster JMX MBean with name=$clusterMBeanName") } else { @@ -255,8 +253,6 @@ private[pekko] class ClusterJmx(cluster: Cluster, log: LoggingAdapter) { s"Could not unregister Cluster JMX MBean with name=$clusterMBeanName as it was not found. " + "If you are running multiple clusters in the same JVM, set 'pekko.cluster.jmx.multi-mbeans-in-same-jvm = on' in config") } - } } - } } diff --git a/cluster/src/main/scala/org/apache/pekko/cluster/ClusterReadView.scala b/cluster/src/main/scala/org/apache/pekko/cluster/ClusterReadView.scala index 7c79750b828..b103236dae0 100644 --- a/cluster/src/main/scala/org/apache/pekko/cluster/ClusterReadView.scala +++ b/cluster/src/main/scala/org/apache/pekko/cluster/ClusterReadView.scala @@ -66,15 +66,14 @@ import pekko.dispatch.UnboundedMessageQueueSemantics val selfAddress: Address = cluster.selfAddress // create actor that subscribes to the cluster eventBus to update current read view state - private val eventBusListener: ActorRef = { + private val eventBusListener: ActorRef = cluster.system .systemActorOf(Props(new Actor with RequiresMessageQueue[UnboundedMessageQueueSemantics] { override def preStart(): Unit = cluster.subscribe(this.self, classOf[ClusterDomainEvent]) // make sure that final state has member status Removed - override def postStop(): Unit = { + override def postStop(): Unit = selfRemoved() // make sure it ends as Removed even though MemberRemoved message didn't make it - } private def selfRemoved(): Unit = { val oldState = _state.get() @@ -159,7 +158,6 @@ import pekko.dispatch.UnboundedMessageQueueSemantics _state.set(oldState.copy(clusterState = s, selfMember = newSelfMember)) } }).withDispatcher(cluster.settings.UseDispatcher).withDeploy(Deploy.local), name = "clusterEventBusListener") - } def state: CurrentClusterState = _state.get().clusterState @@ -228,7 +226,7 @@ import pekko.dispatch.UnboundedMessageQueueSemantics */ private[cluster] def latestStats: CurrentInternalStats = _state.get().latestStats - private def logInfoVerbose(event: ClusterDomainEvent): Unit = { + private def logInfoVerbose(event: ClusterDomainEvent): Unit = if (cluster.settings.LogInfoVerbose) { event match { case _: SeenChanged | _: CurrentInternalStats => // ignore @@ -250,14 +248,12 @@ import pekko.dispatch.UnboundedMessageQueueSemantics logInfo("event {}", event) } } - } /** * Unsubscribe to cluster events. */ - def close(): Unit = { + def close(): Unit = if (!eventBusListener.isTerminated) eventBusListener ! PoisonPill - } } diff --git a/cluster/src/main/scala/org/apache/pekko/cluster/ClusterRemoteWatcher.scala b/cluster/src/main/scala/org/apache/pekko/cluster/ClusterRemoteWatcher.scala index 7e6696b3488..9276828f1ee 100644 --- a/cluster/src/main/scala/org/apache/pekko/cluster/ClusterRemoteWatcher.scala +++ b/cluster/src/main/scala/org/apache/pekko/cluster/ClusterRemoteWatcher.scala @@ -117,10 +117,9 @@ private[cluster] class ClusterRemoteWatcher( case DelayedQuarantine(m, previousStatus) => delayedQuarantine(m, previousStatus) } - private def memberJoined(m: Member): Unit = { + private def memberJoined(m: Member): Unit = if (m.address != selfAddress) quarantineOldIncarnation(m) - } def memberUp(m: Member): Unit = if (m.address != selfAddress) { @@ -154,7 +153,7 @@ private[cluster] class ClusterRemoteWatcher( publishAddressTerminated(m.address) } - def quarantineOldIncarnation(newIncarnation: Member): Unit = { + def quarantineOldIncarnation(newIncarnation: Member): Unit = // If new incarnation of same host:port is seen then quarantine previous incarnation if (pendingDelayedQuarantine.nonEmpty) pendingDelayedQuarantine.find(_.address == newIncarnation.address).foreach { oldIncarnation => @@ -165,9 +164,8 @@ private[cluster] class ClusterRemoteWatcher( s"Cluster member removed, new incarnation joined", harmless = true) } - } - def delayedQuarantine(m: Member, previousStatus: MemberStatus): Unit = { + def delayedQuarantine(m: Member, previousStatus: MemberStatus): Unit = if (pendingDelayedQuarantine(m.uniqueAddress)) { pendingDelayedQuarantine -= m.uniqueAddress quarantine( @@ -176,7 +174,6 @@ private[cluster] class ClusterRemoteWatcher( s"Cluster member removed, previous status [$previousStatus]", harmless = true) } - } override def addWatch(watchee: InternalActorRef, watcher: InternalActorRef): Unit = { val watcheeNode = watchee.path.address @@ -200,12 +197,11 @@ private[cluster] class ClusterRemoteWatcher( * Needed for ShardCoordinator that has to watch old incarnations of region ActorRef from the * recovered state. */ - private def isWatchOutsideClusterAllowed(watchee: InternalActorRef): Boolean = { + private def isWatchOutsideClusterAllowed(watchee: InternalActorRef): Boolean = context.system.name == watchee.path.address.system && { val pathPrefix = watchee.path.elements.take(2).mkString("/", "/", "/") watchPathAllowList.contains(pathPrefix) } - } /** * When a cluster node is added this class takes over the diff --git a/cluster/src/main/scala/org/apache/pekko/cluster/ClusterSettings.scala b/cluster/src/main/scala/org/apache/pekko/cluster/ClusterSettings.scala index 2056d00f869..a7b6b036590 100644 --- a/cluster/src/main/scala/org/apache/pekko/cluster/ClusterSettings.scala +++ b/cluster/src/main/scala/org/apache/pekko/cluster/ClusterSettings.scala @@ -52,24 +52,24 @@ final class ClusterSettings(val config: Config, val systemName: String) { val LogInfo: Boolean = LogInfoVerbose || cc.getBoolean("log-info") val FailureDetectorConfig: Config = cc.getConfig("failure-detector") val FailureDetectorImplementationClass: String = FailureDetectorConfig.getString("implementation-class") - val HeartbeatInterval: FiniteDuration = { + val HeartbeatInterval: FiniteDuration = FailureDetectorConfig.getMillisDuration("heartbeat-interval") - }.requiring(_ > Duration.Zero, "failure-detector.heartbeat-interval must be > 0") - val HeartbeatExpectedResponseAfter: FiniteDuration = { + .requiring(_ > Duration.Zero, "failure-detector.heartbeat-interval must be > 0") + val HeartbeatExpectedResponseAfter: FiniteDuration = FailureDetectorConfig.getMillisDuration("expected-response-after") - }.requiring(_ > Duration.Zero, "failure-detector.expected-response-after > 0") - val MonitoredByNrOfMembers: Int = { + .requiring(_ > Duration.Zero, "failure-detector.expected-response-after > 0") + val MonitoredByNrOfMembers: Int = FailureDetectorConfig.getInt("monitored-by-nr-of-members") - }.requiring(_ > 0, "failure-detector.monitored-by-nr-of-members must be > 0") + .requiring(_ > 0, "failure-detector.monitored-by-nr-of-members must be > 0") final class CrossDcFailureDetectorSettings(val config: Config) { val ImplementationClass: String = config.getString("implementation-class") - val HeartbeatInterval: FiniteDuration = { + val HeartbeatInterval: FiniteDuration = config.getMillisDuration("heartbeat-interval") - }.requiring(_ > Duration.Zero, "failure-detector.heartbeat-interval must be > 0") - val HeartbeatExpectedResponseAfter: FiniteDuration = { + .requiring(_ > Duration.Zero, "failure-detector.heartbeat-interval must be > 0") + val HeartbeatExpectedResponseAfter: FiniteDuration = config.getMillisDuration("expected-response-after") - }.requiring(_ > Duration.Zero, "failure-detector.expected-response-after > 0") + .requiring(_ > Duration.Zero, "failure-detector.expected-response-after > 0") def NrOfMonitoringActors: Int = MultiDataCenter.CrossDcConnections } @@ -108,9 +108,9 @@ final class ClusterSettings(val config: Config, val systemName: String) { } val PeriodicTasksInitialDelay: FiniteDuration = cc.getMillisDuration("periodic-tasks-initial-delay") val GossipInterval: FiniteDuration = cc.getMillisDuration("gossip-interval") - val GossipTimeToLive: FiniteDuration = { + val GossipTimeToLive: FiniteDuration = cc.getMillisDuration("gossip-time-to-live") - }.requiring(_ > Duration.Zero, "gossip-time-to-live must be > 0") + .requiring(_ > Duration.Zero, "gossip-time-to-live must be > 0") val LeaderActionsInterval: FiniteDuration = cc.getMillisDuration("leader-actions-interval") val UnreachableNodesReaperInterval: FiniteDuration = cc.getMillisDuration("unreachable-nodes-reaper-interval") val PublishStatsInterval: Duration = { @@ -171,9 +171,9 @@ final class ClusterSettings(val config: Config, val systemName: String) { val AppVersion: Version = Version(cc.getString("app-version")) - val MinNrOfMembers: Int = { + val MinNrOfMembers: Int = cc.getInt("min-nr-of-members") - }.requiring(_ > 0, "min-nr-of-members must be > 0") + .requiring(_ > 0, "min-nr-of-members must be > 0") val MinNrOfMembersOfRole: Map[String, Int] = { import pekko.util.ccompat.JavaConverters._ cc.getConfig("role") diff --git a/cluster/src/main/scala/org/apache/pekko/cluster/ConfigUtil.scala b/cluster/src/main/scala/org/apache/pekko/cluster/ConfigUtil.scala index 6c2bd2254e2..361004db61e 100644 --- a/cluster/src/main/scala/org/apache/pekko/cluster/ConfigUtil.scala +++ b/cluster/src/main/scala/org/apache/pekko/cluster/ConfigUtil.scala @@ -38,7 +38,7 @@ private[cluster] object ConfigUtil { newConfig.withValue("akka.version", ConfigValueFactory.fromAnyRef(akkaVersion)) } - private def adjustPackageNameIfNecessary(cv: ConfigValue): ConfigValue = { + private def adjustPackageNameIfNecessary(cv: ConfigValue): ConfigValue = if (cv.valueType() == ConfigValueType.STRING) { val str = cv.unwrapped().toString if (str.startsWith("org.apache.pekko")) { @@ -49,6 +49,5 @@ private[cluster] object ConfigUtil { } else { cv } - } } diff --git a/cluster/src/main/scala/org/apache/pekko/cluster/CoordinatedShutdownLeave.scala b/cluster/src/main/scala/org/apache/pekko/cluster/CoordinatedShutdownLeave.scala index ddb34545e9f..424b218ce46 100644 --- a/cluster/src/main/scala/org/apache/pekko/cluster/CoordinatedShutdownLeave.scala +++ b/cluster/src/main/scala/org/apache/pekko/cluster/CoordinatedShutdownLeave.scala @@ -38,9 +38,8 @@ private[pekko] class CoordinatedShutdownLeave extends Actor { val cluster = Cluster(context.system) - override def postStop(): Unit = { + override def postStop(): Unit = cluster.unsubscribe(self) - } def receive = { case LeaveReq => diff --git a/cluster/src/main/scala/org/apache/pekko/cluster/CrossDcClusterHeartbeat.scala b/cluster/src/main/scala/org/apache/pekko/cluster/CrossDcClusterHeartbeat.scala index 9c786cc899b..76e94630477 100644 --- a/cluster/src/main/scala/org/apache/pekko/cluster/CrossDcClusterHeartbeat.scala +++ b/cluster/src/main/scala/org/apache/pekko/cluster/CrossDcClusterHeartbeat.scala @@ -210,7 +210,7 @@ private[cluster] class CrossDcHeartbeatSender extends Actor { } /** Idempotent, become active if this node is n-th oldest and should monitor other nodes */ - private def becomeActiveIfResponsibleForHeartbeat(): Unit = { + private def becomeActiveIfResponsibleForHeartbeat(): Unit = if (!activelyMonitoring && selfIsResponsibleForCrossDcHeartbeat()) { logInfo( "Cross DC heartbeat becoming ACTIVE on this node (for DC: {}), monitoring other DCs oldest nodes", @@ -220,7 +220,6 @@ private[cluster] class CrossDcHeartbeatSender extends Actor { context.become(active.orElse(introspecting)) } else if (!activelyMonitoring) if (verboseHeartbeat) logInfo("Remaining DORMANT; others in {} handle heartbeating other DCs", selfDataCenter) - } } @@ -345,7 +344,7 @@ private[cluster] object CrossDcHeartbeatingState { selfDataCenter: DataCenter, crossDcFailureDetector: FailureDetectorRegistry[Address], nrOfMonitoredNodesPerDc: Int, - members: immutable.SortedSet[Member]): CrossDcHeartbeatingState = { + members: immutable.SortedSet[Member]): CrossDcHeartbeatingState = new CrossDcHeartbeatingState(selfDataCenter, crossDcFailureDetector, nrOfMonitoredNodesPerDc, state = { // TODO unduplicate this with the logic in MembershipState.ageSortedTopOldestMembersPerDc @@ -362,6 +361,5 @@ private[cluster] object CrossDcHeartbeatingState { } } }) - } } diff --git a/cluster/src/main/scala/org/apache/pekko/cluster/Gossip.scala b/cluster/src/main/scala/org/apache/pekko/cluster/Gossip.scala index 1f5ff051da9..8285de1198f 100644 --- a/cluster/src/main/scala/org/apache/pekko/cluster/Gossip.scala +++ b/cluster/src/main/scala/org/apache/pekko/cluster/Gossip.scala @@ -128,32 +128,28 @@ private[cluster] final case class Gossip( /** * Adds a member to the member node ring. */ - def :+(member: Member): Gossip = { + def :+(member: Member): Gossip = if (members contains member) this else this.copy(members = members + member) - } /** * Marks the gossip as seen by this node (address) by updating the address entry in the 'gossip.overview.seen' */ - def seen(node: UniqueAddress): Gossip = { + def seen(node: UniqueAddress): Gossip = if (seenByNode(node)) this else this.copy(overview = overview.copy(seen = overview.seen + node)) - } /** * Marks the gossip as seen by only this node (address) by replacing the 'gossip.overview.seen' */ - def onlySeen(node: UniqueAddress): Gossip = { + def onlySeen(node: UniqueAddress): Gossip = this.copy(overview = overview.copy(seen = Set(node))) - } /** * Remove all seen entries */ - def clearSeen(): Gossip = { + def clearSeen(): Gossip = this.copy(overview = overview.copy(seen = Set.empty)) - } /** * The nodes that have seen the current version of the Gossip. @@ -220,19 +216,16 @@ private[cluster] final case class Gossip( overview.reachability.isReachable(fromAddress, toAddress) } - def member(node: UniqueAddress): Member = { + def member(node: UniqueAddress): Member = membersMap.getOrElse(node, Member.removed(node)) // placeholder for removed member - } def hasMember(node: UniqueAddress): Boolean = membersMap.contains(node) - def removeAll(nodes: Iterable[UniqueAddress], removalTimestamp: Long): Gossip = { + def removeAll(nodes: Iterable[UniqueAddress], removalTimestamp: Long): Gossip = nodes.foldLeft(this)((gossip, node) => gossip.remove(node, removalTimestamp)) - } - def update(updatedMembers: immutable.SortedSet[Member]): Gossip = { + def update(updatedMembers: immutable.SortedSet[Member]): Gossip = copy(members = updatedMembers.union(members.diff(updatedMembers))) - } /** * Remove the given member from the set of members and mark it's removal with a tombstone to avoid having it @@ -333,7 +326,7 @@ private[cluster] class GossipEnvelope private ( g } - private def deserialize(): Unit = { + private def deserialize(): Unit = if ((g eq null) && (ser ne null)) { if (serDeadline.hasTimeLeft()) g = ser() @@ -341,7 +334,6 @@ private[cluster] class GossipEnvelope private ( g = Gossip.empty ser = null } - } } /** @@ -354,13 +346,12 @@ private[cluster] class GossipEnvelope private ( @SerialVersionUID(1L) private[cluster] final case class GossipStatus(from: UniqueAddress, version: VectorClock, seenDigest: Array[Byte]) extends ClusterMessage { - override def equals(obj: Any): Boolean = { + override def equals(obj: Any): Boolean = obj match { case other: GossipStatus => from == other.from && version == other.version && java.util.Arrays.equals(seenDigest, other.seenDigest) case _ => false } - } override def toString: DataCenter = f"GossipStatus($from,$version,${seenDigest.map(byte => f"$byte%02x").mkString("")})" diff --git a/cluster/src/main/scala/org/apache/pekko/cluster/JoinConfigCompatChecker.scala b/cluster/src/main/scala/org/apache/pekko/cluster/JoinConfigCompatChecker.scala index d92b2ebb2fa..602bca91752 100644 --- a/cluster/src/main/scala/org/apache/pekko/cluster/JoinConfigCompatChecker.scala +++ b/cluster/src/main/scala/org/apache/pekko/cluster/JoinConfigCompatChecker.scala @@ -69,9 +69,8 @@ object JoinConfigCompatChecker { * @param toCheck - the Config instance to be checked * @param actualConfig - the Config instance containing the expected values */ - def fullMatch(requiredKeys: im.Seq[String], toCheck: Config, actualConfig: Config): ConfigValidation = { + def fullMatch(requiredKeys: im.Seq[String], toCheck: Config, actualConfig: Config): ConfigValidation = exists(requiredKeys, toCheck) ++ checkEquality(requiredKeys, toCheck, actualConfig) - } /** * INTERNAL API @@ -81,9 +80,8 @@ object JoinConfigCompatChecker { toCheck: Config, actualConfig: Config): ConfigValidation = { - def checkCompat(key: String, value: ConfigValue) = { + def checkCompat(key: String, value: ConfigValue) = actualConfig.hasPath(key) && actualConfig.getValue(key) == value - } // retrieve all incompatible keys // NOTE: we only check the key if effectively required @@ -125,11 +123,10 @@ object JoinConfigCompatChecker { @InternalApi private[cluster] def removeSensitiveKeys( requiredKeys: im.Seq[String], - clusterSettings: ClusterSettings): im.Seq[String] = { + clusterSettings: ClusterSettings): im.Seq[String] = requiredKeys.filter { key => !clusterSettings.SensitiveConfigPaths.exists(s => key.startsWith(s)) } - } /** * INTERNAL API @@ -160,10 +157,9 @@ object JoinConfigCompatChecker { // composite checker new JoinConfigCompatChecker { - override val requiredKeys: im.Seq[String] = { + override val requiredKeys: im.Seq[String] = // Always include pekko.version (used in join logging) "pekko.version" +: checkers.flatMap(_.requiredKeys).to(im.Seq) - } override def check(toValidate: Config, clusterConfig: Config): ConfigValidation = checkers.foldLeft(Valid: ConfigValidation) { (acc, checker) => acc ++ checker.check(toValidate, clusterConfig) @@ -177,14 +173,13 @@ sealed trait ConfigValidation { def ++(that: ConfigValidation) = concat(that) - def concat(that: ConfigValidation) = { + def concat(that: ConfigValidation) = (this, that) match { case (Invalid(a), Invalid(b)) => Invalid(a ++ b) case (_, i @ Invalid(_)) => i case (i @ Invalid(_), _) => i case _ => Valid } - } } case object Valid extends ConfigValidation { diff --git a/cluster/src/main/scala/org/apache/pekko/cluster/Member.scala b/cluster/src/main/scala/org/apache/pekko/cluster/Member.scala index b1ef58e2a11..7c27a963bf6 100644 --- a/cluster/src/main/scala/org/apache/pekko/cluster/Member.scala +++ b/cluster/src/main/scala/org/apache/pekko/cluster/Member.scala @@ -51,10 +51,9 @@ class Member private[cluster] ( case m: Member => uniqueAddress == m.uniqueAddress case _ => false } - override def toString: String = { + override def toString: String = s"Member($address, $status${if (dataCenter == ClusterSettings.DefaultDataCenter) "" else s", $dataCenter"}${if (appVersion == Version.Zero) "" else s", $appVersion"})" - } def hasRole(role: String): Boolean = roles.contains(role) @@ -98,9 +97,8 @@ class Member private[cluster] ( } } - def copyUp(upNumber: Int): Member = { + def copyUp(upNumber: Int): Member = new Member(uniqueAddress, upNumber, status, roles, appVersion).copy(Up) - } } /** @@ -159,9 +157,8 @@ object Member { * `Member` ordering type class, sorts members by host and port. */ implicit val ordering: Ordering[Member] = new Ordering[Member] { - def compare(a: Member, b: Member): Int = { + def compare(a: Member, b: Member): Int = a.uniqueAddress.compare(b.uniqueAddress) - } } /** @@ -207,7 +204,7 @@ object Member { * Picks the Member with the highest "priority" MemberStatus. * Where highest priority is furthest along the membership state machine */ - def highestPriorityOf(m1: Member, m2: Member): Member = { + def highestPriorityOf(m1: Member, m2: Member): Member = if (m1.status == m2.status) // preserve the oldest in case of different upNumber if (m1.isOlderThan(m2)) m1 else m2 @@ -231,7 +228,6 @@ object Member { case (_, PreparingForShutdown) => m2 case (Up, Up) => m1 } - } } diff --git a/cluster/src/main/scala/org/apache/pekko/cluster/MembershipState.scala b/cluster/src/main/scala/org/apache/pekko/cluster/MembershipState.scala index ccedacf7624..44b176adaa2 100644 --- a/cluster/src/main/scala/org/apache/pekko/cluster/MembershipState.scala +++ b/cluster/src/main/scala/org/apache/pekko/cluster/MembershipState.scala @@ -129,7 +129,7 @@ import pekko.util.ccompat._ /** * @return Up to `crossDcConnections` oldest members for each DC */ - lazy val ageSortedTopOldestMembersPerDc: Map[DataCenter, immutable.SortedSet[Member]] = { + lazy val ageSortedTopOldestMembersPerDc: Map[DataCenter, immutable.SortedSet[Member]] = latestGossip.members.foldLeft(Map.empty[DataCenter, immutable.SortedSet[Member]]) { (acc, member) => acc.get(member.dataCenter) match { case Some(set) => @@ -146,7 +146,6 @@ import pekko.util.ccompat._ acc + (member.dataCenter -> (immutable.SortedSet.empty(Member.ageOrdering) + member)) } } - } /** * @return true if toAddress should be reachable from the fromDc in general, within a data center @@ -215,7 +214,7 @@ import pekko.util.ccompat._ /** * The Exiting change is gossiped to the two oldest nodes for quick dissemination to potential Singleton nodes */ - def gossipTargetsForExitingMembers(exitingMembers: Set[Member]): Set[Member] = { + def gossipTargetsForExitingMembers(exitingMembers: Set[Member]): Set[Member] = if (exitingMembers.nonEmpty) { val roles = exitingMembers.flatten(_.roles).filterNot(_.startsWith(ClusterSettings.DcRolePrefix)) val membersSortedByAge = latestGossip.members.toList.filter(_.dataCenter == selfDc).sorted(Member.ageOrdering) @@ -236,7 +235,6 @@ import pekko.util.ccompat._ targets } else Set.empty - } } @@ -247,9 +245,8 @@ import pekko.util.ccompat._ reduceGossipDifferentViewProbability: Double, crossDcGossipProbability: Double) { - final def gossipTarget(state: MembershipState): Option[UniqueAddress] = { + final def gossipTarget(state: MembershipState): Option[UniqueAddress] = selectRandomNode(gossipTargets(state)) - } final def gossipTargets(state: MembershipState): Vector[UniqueAddress] = if (state.latestGossip.isMultiDc) multiDcGossipTargets(state) @@ -327,7 +324,7 @@ import pekko.util.ccompat._ /** * Choose cross-dc nodes if this one of the N oldest nodes, and if not fall back to gossip locally in the dc */ - protected def multiDcGossipTargets(state: MembershipState): Vector[UniqueAddress] = { + protected def multiDcGossipTargets(state: MembershipState): Vector[UniqueAddress] = // only a fraction of the time across data centers if (selectDcLocalNodes(state)) localDcGossipTargets(state) @@ -362,7 +359,6 @@ import pekko.util.ccompat._ else localDcGossipTargets(state) } } - } /** * For large clusters we should avoid shooting down individual diff --git a/cluster/src/main/scala/org/apache/pekko/cluster/Reachability.scala b/cluster/src/main/scala/org/apache/pekko/cluster/Reachability.scala index 4be7bc88f87..68f7b66a855 100644 --- a/cluster/src/main/scala/org/apache/pekko/cluster/Reachability.scala +++ b/cluster/src/main/scala/org/apache/pekko/cluster/Reachability.scala @@ -76,7 +76,7 @@ private[cluster] class Reachability private ( private class Cache { // `allUnreachable` contains all nodes that have been observed as Unreachable by at least one other node // `allTerminated` contains all nodes that have been observed as Terminated by at least one other node - val (observerRowsMap, allUnreachable, allTerminated) = { + val (observerRowsMap, allUnreachable, allTerminated) = if (records.isEmpty) { val observerRowsMap = Map.empty[UniqueAddress, Map[UniqueAddress, Reachability.Record]] val allTerminated = Set.empty[UniqueAddress] @@ -102,7 +102,6 @@ private[cluster] class Reachability private ( (observerRowsMap, allUnreachable.diff(allTerminated), allTerminated) } - } val allUnreachableOrTerminated: Set[UniqueAddress] = if (allTerminated.isEmpty) allUnreachable @@ -283,23 +282,21 @@ private[cluster] class Reachability private ( .to(immutable.Set) } - def observersGroupedByUnreachable: Map[UniqueAddress, Set[UniqueAddress]] = { + def observersGroupedByUnreachable: Map[UniqueAddress, Set[UniqueAddress]] = records.groupBy(_.subject).collect { case (subject, records) if records.exists(_.status == Unreachable) => val observers: Set[UniqueAddress] = records.iterator.collect { case r if r.status == Unreachable => r.observer }.to(immutable.Set) subject -> observers } - } def allObservers: Set[UniqueAddress] = records.iterator.map(_.observer).toSet - def recordsFrom(observer: UniqueAddress): immutable.IndexedSeq[Record] = { + def recordsFrom(observer: UniqueAddress): immutable.IndexedSeq[Record] = observerRows(observer) match { case None => Vector.empty case Some(rows) => rows.valuesIterator.toVector } - } // only used for testing override def hashCode: Int = versions.hashCode diff --git a/cluster/src/main/scala/org/apache/pekko/cluster/SeedNodeProcess.scala b/cluster/src/main/scala/org/apache/pekko/cluster/SeedNodeProcess.scala index 67a60b81896..fc431f32b32 100644 --- a/cluster/src/main/scala/org/apache/pekko/cluster/SeedNodeProcess.scala +++ b/cluster/src/main/scala/org/apache/pekko/cluster/SeedNodeProcess.scala @@ -47,11 +47,10 @@ private[cluster] abstract class SeedNodeProcess(joinConfigCompatChecker: JoinCon "Note that disabling it will allow the formation of a cluster with nodes having incompatible configuration settings. " + "This node will be shutdown!" - private lazy val needsAkkaConfig: Boolean = { + private lazy val needsAkkaConfig: Boolean = context.system.settings.config .getStringList("pekko.remote.accept-protocol-names") .contains("akka") - } private lazy val akkaVersion: String = { val cfg = context.system.settings.config @@ -102,8 +101,7 @@ private[cluster] abstract class SeedNodeProcess(joinConfigCompatChecker: JoinCon final def receiveInitJoinAckIncompatibleConfig( joinTo: Address, origin: ActorRef, - behavior: Option[Actor.Receive]): Unit = { - + behavior: Option[Actor.Receive]): Unit = // first InitJoinAck reply, but incompatible if (ByPassConfigCompatCheck) { logInitJoinAckReceived(origin) @@ -120,7 +118,6 @@ private[cluster] abstract class SeedNodeProcess(joinConfigCompatChecker: JoinCon context.stop(self) CoordinatedShutdown(context.system).run(CoordinatedShutdown.IncompatibleConfigurationDetectedReason) } - } final def receiveInitJoinAckCompatibleConfig( joinTo: Address, diff --git a/cluster/src/main/scala/org/apache/pekko/cluster/VectorClock.scala b/cluster/src/main/scala/org/apache/pekko/cluster/VectorClock.scala index 06e2efcd3b4..e260bff541a 100644 --- a/cluster/src/main/scala/org/apache/pekko/cluster/VectorClock.scala +++ b/cluster/src/main/scala/org/apache/pekko/cluster/VectorClock.scala @@ -182,9 +182,8 @@ final case class VectorClock(versions: TreeMap[VectorClock.Node, Long] = TreeMap * 4. Clock 1 is CONCURRENT (<>) to Clock 2 otherwise. * }}} */ - def compareTo(that: VectorClock): Ordering = { + def compareTo(that: VectorClock): Ordering = compareOnlyTo(that, FullOrder) - } /** * Merges this VectorClock with another VectorClock. E.g. merges its versioned history. diff --git a/cluster/src/main/scala/org/apache/pekko/cluster/protobuf/ClusterMessageSerializer.scala b/cluster/src/main/scala/org/apache/pekko/cluster/protobuf/ClusterMessageSerializer.scala index 3199896ae75..ae57358fc9c 100644 --- a/cluster/src/main/scala/org/apache/pekko/cluster/protobuf/ClusterMessageSerializer.scala +++ b/cluster/src/main/scala/org/apache/pekko/cluster/protobuf/ClusterMessageSerializer.scala @@ -181,7 +181,7 @@ final class ClusterMessageSerializer(val system: ExtendedActorSystem) out.toByteArray } - private def heartbeatToProtoByteArray(hb: ClusterHeartbeatSender.Heartbeat): Array[Byte] = { + private def heartbeatToProtoByteArray(hb: ClusterHeartbeatSender.Heartbeat): Array[Byte] = cm.Heartbeat .newBuilder() .setFrom(addressToProto(hb.from)) @@ -189,9 +189,8 @@ final class ClusterMessageSerializer(val system: ExtendedActorSystem) .setCreationTime(hb.creationTimeNanos) .build .toByteArray - } - private def heartbeatRspToProtoByteArray(hbr: ClusterHeartbeatSender.HeartbeatRsp): Array[Byte] = { + private def heartbeatRspToProtoByteArray(hbr: ClusterHeartbeatSender.HeartbeatRsp): Array[Byte] = cm.HeartBeatResponse .newBuilder() .setFrom(uniqueAddressToProto(hbr.from)) @@ -199,7 +198,6 @@ final class ClusterMessageSerializer(val system: ExtendedActorSystem) .setCreationTime(hbr.creationTimeNanos) .build .toByteArray - } private def addressFromBinary(bytes: Array[Byte]): Address = addressFromProto(cm.Address.parseFrom(bytes)) @@ -215,13 +213,12 @@ final class ClusterMessageSerializer(val system: ExtendedActorSystem) private[pekko] def addressToProtoByteArray(address: Address): Array[Byte] = addressToProto(address).build.toByteArray - private[pekko] def uniqueAddressToProto(uniqueAddress: UniqueAddress): cm.UniqueAddress.Builder = { + private[pekko] def uniqueAddressToProto(uniqueAddress: UniqueAddress): cm.UniqueAddress.Builder = cm.UniqueAddress .newBuilder() .setAddress(addressToProto(uniqueAddress.address)) .setUid(uniqueAddress.longUid.toInt) .setUid2((uniqueAddress.longUid >> 32).toInt) - } private def uniqueAddressToProtoByteArray(uniqueAddress: UniqueAddress): Array[Byte] = uniqueAddressToProto(uniqueAddress).build.toByteArray @@ -302,13 +299,11 @@ final class ClusterMessageSerializer(val system: ExtendedActorSystem) InternalClusterAction.Welcome(uniqueAddressFromProto(m.getFrom), gossipFromProto(m.getGossip)) } - private def deserializeLeave(bytes: Array[Byte]): ClusterUserAction.Leave = { + private def deserializeLeave(bytes: Array[Byte]): ClusterUserAction.Leave = ClusterUserAction.Leave(addressFromBinary(bytes)) - } - private def deserializeDown(bytes: Array[Byte]): ClusterUserAction.Down = { + private def deserializeDown(bytes: Array[Byte]): ClusterUserAction.Down = ClusterUserAction.Down(addressFromBinary(bytes)) - } private def deserializeInitJoin(bytes: Array[Byte]): InternalClusterAction.InitJoin = { val m = cm.InitJoin.parseFrom(bytes) @@ -318,7 +313,7 @@ final class ClusterMessageSerializer(val system: ExtendedActorSystem) InternalClusterAction.InitJoin(ConfigFactory.empty) } - private def deserializeInitJoinAck(bytes: Array[Byte]): InternalClusterAction.InitJoinAck = { + private def deserializeInitJoinAck(bytes: Array[Byte]): InternalClusterAction.InitJoinAck = try { val i = cm.InitJoinAck.parseFrom(bytes) val configCheck = @@ -335,19 +330,15 @@ final class ClusterMessageSerializer(val system: ExtendedActorSystem) // nodes previous to 2.5.9 sends just an address InternalClusterAction.InitJoinAck(addressFromBinary(bytes), UncheckedConfig) } - } - private def deserializeExitingConfirmed(bytes: Array[Byte]): InternalClusterAction.ExitingConfirmed = { + private def deserializeExitingConfirmed(bytes: Array[Byte]): InternalClusterAction.ExitingConfirmed = InternalClusterAction.ExitingConfirmed(uniqueAddressFromBinary(bytes)) - } - private def deserializeHeartBeatRspAsUniqueAddress(bytes: Array[Byte]): ClusterHeartbeatSender.HeartbeatRsp = { + private def deserializeHeartBeatRspAsUniqueAddress(bytes: Array[Byte]): ClusterHeartbeatSender.HeartbeatRsp = ClusterHeartbeatSender.HeartbeatRsp(uniqueAddressFromBinary(bytes), -1, -1) - } - private def deserializeHeartBeatAsAddress(bytes: Array[Byte]): ClusterHeartbeatSender.Heartbeat = { + private def deserializeHeartBeatAsAddress(bytes: Array[Byte]): ClusterHeartbeatSender.Heartbeat = ClusterHeartbeatSender.Heartbeat(addressFromBinary(bytes), -1, -1) - } def deserializeHeartBeat(bytes: Array[Byte]): ClusterHeartbeatSender.Heartbeat = { val hb = cm.Heartbeat.parseFrom(bytes) @@ -359,15 +350,13 @@ final class ClusterMessageSerializer(val system: ExtendedActorSystem) ClusterHeartbeatSender.HeartbeatRsp(uniqueAddressFromProto(hbr.getFrom), hbr.getSequenceNr, hbr.getCreationTime) } - private def deserializeInitJoinNack(bytes: Array[Byte]): InternalClusterAction.InitJoinNack = { + private def deserializeInitJoinNack(bytes: Array[Byte]): InternalClusterAction.InitJoinNack = InternalClusterAction.InitJoinNack(addressFromBinary(bytes)) - } private def addressFromProto(address: cm.Address): Address = Address(getProtocol(address), getSystem(address), address.getHostname, address.getPort) - private def uniqueAddressFromProto(uniqueAddress: cm.UniqueAddress): UniqueAddress = { - + private def uniqueAddressFromProto(uniqueAddress: cm.UniqueAddress): UniqueAddress = UniqueAddress(addressFromProto(uniqueAddress.getAddress), if (uniqueAddress.hasUid2) { // new remote node join the two parts of the long uid back @@ -376,7 +365,6 @@ final class ClusterMessageSerializer(val system: ExtendedActorSystem) // old remote node uniqueAddress.getUid.toLong }) - } private val memberStatusToInt = scala.collection.immutable.HashMap[MemberStatus, Int]( MemberStatus.Joining -> cm.MemberStatus.Joining_VALUE, @@ -411,16 +399,14 @@ final class ClusterMessageSerializer(val system: ExtendedActorSystem) .setAppVersion(appVersion.version) .build() - private def initJoinToProto(currentConfig: Config): cm.InitJoin = { + private def initJoinToProto(currentConfig: Config): cm.InitJoin = cm.InitJoin.newBuilder().setCurrentConfig(currentConfig.root.render(ConfigRenderOptions.concise)).build() - } - private def initJoinAckToByteArray(address: Address, configCheck: ConfigCheck): Array[Byte] = { + private def initJoinAckToByteArray(address: Address, configCheck: ConfigCheck): Array[Byte] = if (configCheck == ConfigCheckUnsupportedByJoiningNode) addressToProtoByteArray(address) // plain Address in Akka 2.5.9 or earlier else initJoinAckToProto(address, configCheck).toByteArray - } private def initJoinAckToProto(address: Address, configCheck: ConfigCheck): cm.InitJoinAck = { @@ -475,7 +461,7 @@ final class ClusterMessageSerializer(val system: ExtendedActorSystem) .addAllRolesIndexes(member.roles.map(mapRole).asJava) .setAppVersionIndex(mapAppVersion(member.appVersion)) - def reachabilityToProto(reachability: Reachability): Iterable[cm.ObserverReachability.Builder] = { + def reachabilityToProto(reachability: Reachability): Iterable[cm.ObserverReachability.Builder] = reachability.versions.map { case (observer, version) => val subjectReachability = reachability @@ -492,7 +478,6 @@ final class ClusterMessageSerializer(val system: ExtendedActorSystem) .setVersion(version) .addAllSubjectReachability(subjectReachability.map(_.build).asJava) } - } def tombstoneToProto(t: (UniqueAddress, Long)): cm.Tombstone = cm.Tombstone.newBuilder().setAddressIndex(mapUniqueAddress(t._1)).setTimestamp(t._2).build() @@ -614,10 +599,9 @@ final class ClusterMessageSerializer(val system: ExtendedActorSystem) Gossip(members, overview, vectorClockFromProto(gossip.getVersion, hashMapping), tombstones) } - private def vectorClockFromProto(version: cm.VectorClock, hashMapping: immutable.Seq[String]) = { + private def vectorClockFromProto(version: cm.VectorClock, hashMapping: immutable.Seq[String]) = VectorClock(scala.collection.immutable.TreeMap.from(version.getVersionsList.asScala.iterator.map(v => (VectorClock.Node.fromHash(hashMapping(v.getHashIndex)), v.getTimestamp)))) - } private def gossipEnvelopeFromProto(envelope: cm.GossipEnvelope): GossipEnvelope = { val serializedGossip = envelope.getSerializedGossip @@ -644,11 +628,10 @@ final class ClusterMessageSerializer(val system: ExtendedActorSystem) ClusterRouterPool(poolFromProto(crp.getPool), clusterRouterPoolSettingsFromProto(crp.getSettings)) } - private def poolFromProto(pool: cm.Pool): Pool = { + private def poolFromProto(pool: cm.Pool): Pool = serialization.deserialize(pool.getData.toByteArray, pool.getSerializerId, pool.getManifest).get.asInstanceOf[Pool] - } - private def clusterRouterPoolSettingsFromProto(crps: cm.ClusterRouterPoolSettings): ClusterRouterPoolSettings = { + private def clusterRouterPoolSettingsFromProto(crps: cm.ClusterRouterPoolSettings): ClusterRouterPoolSettings = // For backwards compatibility, useRoles is the combination of getUseRole and getUseRolesList ClusterRouterPoolSettings( totalInstances = crps.getTotalInstances, @@ -659,6 +642,5 @@ final class ClusterMessageSerializer(val system: ExtendedActorSystem) } else { crps.getUseRolesList.asScala.toSet }) - } } diff --git a/cluster/src/main/scala/org/apache/pekko/cluster/sbr/DowningStrategy.scala b/cluster/src/main/scala/org/apache/pekko/cluster/sbr/DowningStrategy.scala index 6269a6fa3a1..83d7d5fa157 100644 --- a/cluster/src/main/scala/org/apache/pekko/cluster/sbr/DowningStrategy.scala +++ b/cluster/src/main/scala/org/apache/pekko/cluster/sbr/DowningStrategy.scala @@ -154,10 +154,9 @@ import pekko.coordination.lease.scaladsl.Lease def unreachableMembers( includingPossiblyUp: Boolean, - excludingPossiblyExiting: Boolean): immutable.SortedSet[Member] = { + excludingPossiblyExiting: Boolean): immutable.SortedSet[Member] = if (unreachable.isEmpty) immutable.SortedSet.empty else members(includingPossiblyUp, excludingPossiblyExiting).filter(unreachable) - } def unreachableMembersWithRole: immutable.SortedSet[Member] = unreachableMembersWithRole(includingPossiblyUp = false, excludingPossiblyExiting = false) @@ -198,7 +197,7 @@ import pekko.coordination.lease.scaladsl.Lease _unreachable -= m.uniqueAddress } - private def removeFromAllMembers(m: Member): Unit = { + private def removeFromAllMembers(m: Member): Unit = if (ordering eq Member.ordering) { _allMembers -= m } else { @@ -206,22 +205,19 @@ import pekko.coordination.lease.scaladsl.Lease // ageOrdering is using upNumber and that will change when Joining -> Up _allMembers = _allMembers.filterNot(_.uniqueAddress == m.uniqueAddress) } - } @InternalStableApi def reachability: Reachability = _reachability - private def isInSelfDc(node: UniqueAddress): Boolean = { + private def isInSelfDc(node: UniqueAddress): Boolean = _allMembers.exists(m => m.uniqueAddress == node && m.dataCenter == selfDc) - } - private[sbr] def setReachability(r: Reachability): Unit = { + private[sbr] def setReachability(r: Reachability): Unit = // skip records with Reachability.Reachable, and skip records related to other DC _reachability = r.filterRecords(record => (record.status == Reachability.Unreachable || record.status == Reachability.Terminated) && isInSelfDc(record.observer) && isInSelfDc(record.subject)) - } def seenBy: Set[Address] = _seenBy @@ -241,9 +237,8 @@ import pekko.coordination.lease.scaladsl.Lease * * Those cases will not happen for clean splits and crashed nodes. */ - def indirectlyConnected: Set[UniqueAddress] = { + def indirectlyConnected: Set[UniqueAddress] = indirectlyConnectedFromIntersectionOfObserversAndSubjects.union(indirectlyConnectedFromSeenCurrentGossip) - } private def indirectlyConnectedFromIntersectionOfObserversAndSubjects: Set[UniqueAddress] = { // cycle in unreachability graph @@ -251,12 +246,11 @@ import pekko.coordination.lease.scaladsl.Lease observers.intersect(reachability.allUnreachableOrTerminated) } - private def indirectlyConnectedFromSeenCurrentGossip: Set[UniqueAddress] = { + private def indirectlyConnectedFromSeenCurrentGossip: Set[UniqueAddress] = reachability.records.flatMap { r => if (seenBy(r.subject.address)) r.observer :: r.subject :: Nil else Nil }.toSet - } def hasIndirectlyConnected: Boolean = indirectlyConnected.nonEmpty @@ -290,7 +284,7 @@ import pekko.coordination.lease.scaladsl.Lease } } - private def additionalNodesToDownWhenIndirectlyConnected(downable: Set[UniqueAddress]): Set[UniqueAddress] = { + private def additionalNodesToDownWhenIndirectlyConnected(downable: Set[UniqueAddress]): Set[UniqueAddress] = if (unreachableButNotIndirectlyConnected.isEmpty) Set.empty else { @@ -324,19 +318,16 @@ import pekko.coordination.lease.scaladsl.Lease _reachability = originalReachability } } - } - def isAllUnreachableDownOrExiting: Boolean = { + def isAllUnreachableDownOrExiting: Boolean = _unreachable.isEmpty || unreachableMembers.forall(m => m.status == MemberStatus.Down || m.status == MemberStatus.Exiting) - } - def reverseDecision(decision: AcquireLeaseDecision): Decision = { + def reverseDecision(decision: AcquireLeaseDecision): Decision = decision match { case AcquireLeaseAndDownUnreachable(_) => DownReachable case AcquireLeaseAndDownIndirectlyConnected(_) => ReverseDownIndirectlyConnected } - } def decide(): Decision @@ -372,7 +363,7 @@ import pekko.coordination.lease.scaladsl.Lease extends DowningStrategy(selfDc, selfUniqueAddress) { import DowningStrategy._ - override def decide(): Decision = { + override def decide(): Decision = if (isTooManyMembers) DownAll else if (hasIndirectlyConnected) @@ -381,7 +372,6 @@ import pekko.coordination.lease.scaladsl.Lease DownUnreachable else DownReachable - } def isTooManyMembers: Boolean = membersWithRole.size > (quorumSize * 2 - 1) @@ -408,7 +398,7 @@ import pekko.coordination.lease.scaladsl.Lease extends DowningStrategy(selfDc, selfUniqueAddress) { import DowningStrategy._ - override def decide(): Decision = { + override def decide(): Decision = if (hasIndirectlyConnected) DownIndirectlyConnected else { @@ -430,9 +420,8 @@ import pekko.coordination.lease.scaladsl.Lease } } - } - private def majorityDecision(thisSide: Int, otherSide: Int, lowest: Member): Decision = { + private def majorityDecision(thisSide: Int, otherSide: Int, lowest: Member): Decision = if (thisSide == otherSide) { // equal size, keep the side with the lowest address (first in members) if (unreachable(lowest)) DownReachable else DownUnreachable @@ -443,7 +432,6 @@ import pekko.coordination.lease.scaladsl.Lease // we are in minority DownReachable } - } /** * Check for edge case when membership change happens at the same time as partition. @@ -501,7 +489,7 @@ import pekko.coordination.lease.scaladsl.Lease // sort by age, oldest first override def ordering: Ordering[Member] = Member.ageOrdering - override def decide(): Decision = { + override def decide(): Decision = if (hasIndirectlyConnected) DownIndirectlyConnected else { @@ -525,9 +513,8 @@ import pekko.coordination.lease.scaladsl.Lease } } - } - private def oldestDecision(oldestIsOnThisSide: Boolean, thisSide: Int, otherSide: Int): Decision = { + private def oldestDecision(oldestIsOnThisSide: Boolean, thisSide: Int, otherSide: Int): Decision = if (oldestIsOnThisSide) { // if there are only 2 nodes in the cluster it is better to keep the oldest, even though it is alone // E.g. 2 nodes: thisSide=1, otherSide=1 => DownUnreachable, i.e. keep the oldest @@ -540,7 +527,6 @@ import pekko.coordination.lease.scaladsl.Lease if (downIfAlone && otherSide == 1 && thisSide >= 2) DownUnreachable else DownReachable } - } /** * Check for edge case when membership change happens at the same time as partition. @@ -605,12 +591,11 @@ import pekko.coordination.lease.scaladsl.Lease override val lease: Option[Lease] = Some(_lease) - override def decide(): Decision = { + override def decide(): Decision = if (hasIndirectlyConnected) AcquireLeaseAndDownIndirectlyConnected(Duration.Zero) else AcquireLeaseAndDownUnreachable(acquireLeaseDelay) - } private def acquireLeaseDelay: FiniteDuration = if (isInMinority) acquireLeaseDelayForMinority else Duration.Zero diff --git a/cluster/src/main/scala/org/apache/pekko/cluster/sbr/SplitBrainResolver.scala b/cluster/src/main/scala/org/apache/pekko/cluster/sbr/SplitBrainResolver.scala index 0fed30518c4..ea535eef712 100644 --- a/cluster/src/main/scala/org/apache/pekko/cluster/sbr/SplitBrainResolver.scala +++ b/cluster/src/main/scala/org/apache/pekko/cluster/sbr/SplitBrainResolver.scala @@ -82,7 +82,7 @@ import pekko.remote.artery.ThisActorSystemQuarantinedEvent def isEmpty: Boolean = changeCount == 0 - override def toString: String = { + override def toString: String = if (isEmpty) "reachability unchanged" else { @@ -90,7 +90,6 @@ import pekko.remote.artery.ThisActorSystemQuarantinedEvent s"reachability changed $changeCount times since ${(now - firstChangeTimestamp).nanos.toMillis} ms ago, " + s"latest change was ${(now - latestChangeTimestamp).nanos.toMillis} ms ago" } - } } } @@ -191,9 +190,8 @@ import pekko.remote.artery.ThisActorSystemQuarantinedEvent // overridden in tests protected def newStableDeadline(): Deadline = Deadline.now + stableAfter var stableDeadline: Deadline = _ - def resetStableDeadline(): Unit = { + def resetStableDeadline(): Unit = stableDeadline = newStableDeadline() - } resetStableDeadline() @@ -205,12 +203,11 @@ import pekko.remote.artery.ThisActorSystemQuarantinedEvent reachabilityChangedStats = ReachabilityChangedStats(now, now, 0) } - private def resetReachabilityChangedStatsIfAllUnreachableDowned(): Unit = { + private def resetReachabilityChangedStatsIfAllUnreachableDowned(): Unit = if (!reachabilityChangedStats.isEmpty && strategy.isAllUnreachableDownOrExiting) { log.debug("SBR resetting reachability stats, after all unreachable healed, downed or removed") resetReachabilityChangedStats() } - } private var releaseLeaseCondition: ReleaseLeaseCondition = NoLease @@ -299,11 +296,10 @@ import pekko.remote.artery.ThisActorSystemQuarantinedEvent case _: ClusterDomainEvent => // not interested in other events } - private def leaderChanged(leaderOption: Option[Address]): Unit = { + private def leaderChanged(leaderOption: Option[Address]): Unit = mutateResponsibilityInfo { () => leader = leaderOption.contains(selfUniqueAddress.address) } - } private def tick(): Unit = { // note the DownAll due to instability is running on all nodes to make that decision as quickly and @@ -425,7 +421,7 @@ import pekko.remote.artery.ThisActorSystemQuarantinedEvent stash() } - private def releaseLeaseResult(released: Boolean): Unit = { + private def releaseLeaseResult(released: Boolean): Unit = releaseLeaseCondition match { case ReleaseLeaseCondition.WhenTimeElapsed(deadline) => if (released && deadline.isOverdue()) { @@ -435,16 +431,15 @@ import pekko.remote.artery.ThisActorSystemQuarantinedEvent case _ => // no lease or first waiting for downed nodes to be removed } - } /** * @return the nodes that were downed */ def actOnDecision(decision: Decision): Set[UniqueAddress] = { val nodesToDown = - try { + try strategy.nodesToDown(decision) - } catch { + catch { case e: IllegalStateException => log.warning(e.getMessage) strategy.nodesToDown(DownAll) @@ -494,7 +489,7 @@ import pekko.remote.artery.ThisActorSystemQuarantinedEvent def isResponsible: Boolean = leader && selfMemberAdded - def unreachableMember(m: Member): Unit = { + def unreachableMember(m: Member): Unit = if (m.uniqueAddress != selfUniqueAddress && m.dataCenter == selfDc) { log.debug("SBR unreachableMember [{}]", m) mutateMemberInfo(resetStable = true) { () => @@ -505,9 +500,8 @@ import pekko.remote.artery.ThisActorSystemQuarantinedEvent log.debug("SBR noticed {}", reachabilityChangedStats) } } - } - def reachableMember(m: Member): Unit = { + def reachableMember(m: Member): Unit = if (m.uniqueAddress != selfUniqueAddress && m.dataCenter == selfDc) { log.debug("SBR reachableMember [{}]", m) mutateMemberInfo(resetStable = true) { () => @@ -518,11 +512,9 @@ import pekko.remote.artery.ThisActorSystemQuarantinedEvent log.debug("SBR noticed {}", reachabilityChangedStats) } } - } - private[sbr] def reachabilityChanged(r: Reachability): Unit = { + private[sbr] def reachabilityChanged(r: Reachability): Unit = strategy.setReachability(r) - } private def updateReachabilityChangedStats(): Unit = { val now = System.nanoTime() @@ -548,11 +540,10 @@ import pekko.remote.artery.ThisActorSystemQuarantinedEvent log.info("Data center [{}] observed as reachable again", dc) } - def seenChanged(seenBy: Set[Address]): Unit = { + def seenChanged(seenBy: Set[Address]): Unit = strategy.setSeenBy(seenBy) - } - def addUp(m: Member): Unit = { + def addUp(m: Member): Unit = if (selfDc == m.dataCenter) { log.debug("SBR add Up [{}]", m) mutateMemberInfo(resetStable = true) { () => @@ -574,32 +565,28 @@ import pekko.remote.artery.ThisActorSystemQuarantinedEvent case _ => // ok } } - } - def leaving(m: Member): Unit = { + def leaving(m: Member): Unit = if (selfDc == m.dataCenter) { log.debug("SBR leaving [{}]", m) mutateMemberInfo(resetStable = false) { () => strategy.add(m) } } - } - def exited(m: Member): Unit = { + def exited(m: Member): Unit = if (selfDc == m.dataCenter) { log.debug("SBR exited [{}]", m) mutateMemberInfo(resetStable = true) { () => strategy.add(m) } } - } - def addJoining(m: Member): Unit = { + def addJoining(m: Member): Unit = if (selfDc == m.dataCenter) { log.debug("SBR add Joining/WeaklyUp [{}]", m) strategy.add(m) } - } def addWeaklyUp(m: Member): Unit = { if (m.uniqueAddress == selfUniqueAddress) mutateResponsibilityInfo { () => @@ -609,7 +596,7 @@ import pekko.remote.artery.ThisActorSystemQuarantinedEvent addJoining(m) } - def remove(m: Member): Unit = { + def remove(m: Member): Unit = if (selfDc == m.dataCenter) { if (m.uniqueAddress == selfUniqueAddress) context.stop(self) @@ -633,7 +620,6 @@ import pekko.remote.artery.ThisActorSystemQuarantinedEvent } } } - } private def releaseLease(): Unit = { implicit val ec: ExecutionContext = internalDispatcher diff --git a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/ClusterDeathWatchSpec.scala b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/ClusterDeathWatchSpec.scala index dd5147d0f1a..22f2ee882d2 100644 --- a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/ClusterDeathWatchSpec.scala +++ b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/ClusterDeathWatchSpec.scala @@ -297,9 +297,8 @@ abstract class ClusterDeathWatchSpec endActor ! EndActor.SendEnd endProbe.expectMsg(EndActor.EndAck) - } finally { + } finally shutdown(endSystem, 10 seconds) - } // no barrier here, because it is not part of testConductor roles any more } diff --git a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/ClusterShutdownSpec.scala b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/ClusterShutdownSpec.scala index 029f8bc6078..d6f55212b2f 100644 --- a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/ClusterShutdownSpec.scala +++ b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/ClusterShutdownSpec.scala @@ -51,10 +51,9 @@ abstract class ClusterShutdownSpec extends MultiNodeClusterSpec(ClusterShutdownS } runOn(first, second, third) { - awaitAssert({ - withClue("members: " + Cluster(system).readView.members) { - Cluster(system).selfMember.status shouldEqual MemberStatus.ReadyForShutdown - } + awaitAssert( + withClue("members: " + Cluster(system).readView.members) { + Cluster(system).selfMember.status shouldEqual MemberStatus.ReadyForShutdown }, 10.seconds) } } @@ -83,14 +82,12 @@ abstract class ClusterShutdownSpec extends MultiNodeClusterSpec(ClusterShutdownS Cluster(system).leave(address(first)) } awaitAssert( - { - withClue("members: " + Cluster(system).readView.members) { - runOn(second, third) { - Cluster(system).readView.members.size shouldEqual 2 - } - runOn(first) { - Cluster(system).selfMember.status shouldEqual Removed - } + withClue("members: " + Cluster(system).readView.members) { + runOn(second, third) { + Cluster(system).readView.members.size shouldEqual 2 + } + runOn(first) { + Cluster(system).selfMember.status shouldEqual Removed } }, 10.seconds) enterBarrier("first-gone") @@ -98,10 +95,9 @@ abstract class ClusterShutdownSpec extends MultiNodeClusterSpec(ClusterShutdownS Cluster(system).leave(address(second)) Cluster(system).leave(address(third)) } - awaitAssert({ - withClue("self member: " + Cluster(system).selfMember) { - Cluster(system).selfMember.status shouldEqual Removed - } + awaitAssert( + withClue("self member: " + Cluster(system).selfMember) { + Cluster(system).selfMember.status shouldEqual Removed }, 10.seconds) enterBarrier("all-gone") } diff --git a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/LargeMessageClusterSpec.scala b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/LargeMessageClusterSpec.scala index 812d5f1bf17..8a5455a0ab7 100644 --- a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/LargeMessageClusterSpec.scala +++ b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/LargeMessageClusterSpec.scala @@ -85,9 +85,8 @@ object LargeMessageClusterMultiJvmSpec extends MultiNodeConfig { payload case _ => throw new NotSerializableException() } - override def fromBinary(bytes: Array[Byte], manifest: String) = { + override def fromBinary(bytes: Array[Byte], manifest: String) = Slow(bytes) - } } } @@ -147,9 +146,8 @@ abstract class LargeMessageClusterSpec val repeat = 15 for (n <- 1 to repeat) { val startTime = System.nanoTime() - for (_ <- 1 to largeMsgBurst) { + for (_ <- 1 to largeMsgBurst) largeEcho3.tell(largeMsg, largeEchoProbe.ref) - } val ordinaryProbe = TestProbe() echo3.tell(("0" * 1000).getBytes(StandardCharsets.UTF_8), ordinaryProbe.ref) diff --git a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/MemberWeaklyUpSpec.scala b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/MemberWeaklyUpSpec.scala index 83736605b2f..07fe046c193 100644 --- a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/MemberWeaklyUpSpec.scala +++ b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/MemberWeaklyUpSpec.scala @@ -66,9 +66,8 @@ abstract class MemberWeaklyUpSpec extends MultiNodeClusterSpec(MemberWeaklyUpSpe 20 seconds) { runOn(first) { // split the cluster in two parts (first, second) / (third, fourth, fifth) - for (role1 <- side1; role2 <- side2) { + for (role1 <- side1; role2 <- side2) testConductor.blackhole(role1, role2, Direction.Both).await - } } enterBarrier("after-split") @@ -115,9 +114,8 @@ abstract class MemberWeaklyUpSpec extends MultiNodeClusterSpec(MemberWeaklyUpSpe "change status to Up after healed network partition" taggedAs LongRunningTest in within(20 seconds) { runOn(first) { - for (role1 <- side1; role2 <- side2) { + for (role1 <- side1; role2 <- side2) testConductor.passThrough(role1, role2, Direction.Both).await - } } enterBarrier("after-passThrough") diff --git a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/MultiDcSplitBrainSpec.scala b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/MultiDcSplitBrainSpec.scala index 95c38aa013d..047f1ddf668 100644 --- a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/MultiDcSplitBrainSpec.scala +++ b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/MultiDcSplitBrainSpec.scala @@ -88,9 +88,8 @@ abstract class MultiDcSplitBrainSpec extends MultiNodeClusterSpec(MultiDcSplitBr enterBarrier(s"split-$splits") runOn(first) { - for (dc1Node <- dc1; dc2Node <- dc2) { + for (dc1Node <- dc1; dc2Node <- dc2) testConductor.blackhole(dc1Node, dc2Node, Direction.Both).await - } } enterBarrier(s"after-split-$splits") @@ -120,9 +119,8 @@ abstract class MultiDcSplitBrainSpec extends MultiNodeClusterSpec(MultiDcSplitBr enterBarrier(s"unsplit-$unsplits") runOn(first) { - for (dc1Node <- dc1; dc2Node <- dc2) { + for (dc1Node <- dc1; dc2Node <- dc2) testConductor.passThrough(dc1Node, dc2Node, Direction.Both).await - } } enterBarrier(s"after-unsplit-$unsplits") @@ -283,9 +281,8 @@ abstract class MultiDcSplitBrainSpec extends MultiNodeClusterSpec(MultiDcSplitBr } runOn(first) { - for (dc1Node <- dc1; dc2Node <- dc2) { + for (dc1Node <- dc1; dc2Node <- dc2) testConductor.passThrough(dc1Node, dc2Node, Direction.Both).await - } testConductor.shutdown(fifth) } diff --git a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/MultiNodeClusterSpec.scala b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/MultiNodeClusterSpec.scala index 37eb80f67bd..5d3ec87f546 100644 --- a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/MultiNodeClusterSpec.scala +++ b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/MultiNodeClusterSpec.scala @@ -126,7 +126,7 @@ abstract class MultiNodeClusterSpec(multiNodeconfig: MultiNodeConfig) override def expectedTestDuration = 60.seconds - def muteLog(sys: ActorSystem = system): Unit = { + def muteLog(sys: ActorSystem = system): Unit = if (!sys.log.isDebugEnabled) { Seq( ".*Cluster Node.* - registered cluster JMX MBean.*", @@ -152,7 +152,6 @@ abstract class MultiNodeClusterSpec(multiNodeconfig: MultiNodeConfig) classOf[pekko.remote.transport.AssociationHandle.InboundPayload])(sys) } - } def muteMarkingAsUnreachable(sys: ActorSystem = system): Unit = if (!sys.log.isDebugEnabled) @@ -179,7 +178,7 @@ abstract class MultiNodeClusterSpec(multiNodeconfig: MultiNodeConfig) * and then restarting a role (jvm) with another address is not * supported. */ - implicit def address(role: RoleName): Address = { + implicit def address(role: RoleName): Address = cachedAddresses.get(role) match { case null => val address = node(role).address @@ -187,7 +186,6 @@ abstract class MultiNodeClusterSpec(multiNodeconfig: MultiNodeConfig) address case address => address } - } // Cluster tests are written so that if previous step (test method) failed // it will most likely not be possible to run next step. This ensures @@ -213,13 +211,12 @@ abstract class MultiNodeClusterSpec(multiNodeconfig: MultiNodeConfig) /** * Use this method for the initial startup of the cluster node. */ - def startClusterNode(): Unit = { + def startClusterNode(): Unit = if (clusterView.members.isEmpty) { cluster.join(myself) awaitAssert(clusterView.members.map(_.address) should contain(address(myself))) } else clusterView.self - } /** * Initialize the cluster of the specified member @@ -254,14 +251,12 @@ abstract class MultiNodeClusterSpec(multiNodeconfig: MultiNodeConfig) cluster.join(joinNode) awaitCond( - { - if (memberInState(joinNode, List(MemberStatus.Up)) && - memberInState(myself, List(MemberStatus.Joining, MemberStatus.Up))) - true - else { - cluster.join(joinNode) - false - } + if (memberInState(joinNode, List(MemberStatus.Up)) && + memberInState(myself, List(MemberStatus.Joining, MemberStatus.Up))) + true + else { + cluster.join(joinNode) + false }, max, interval) @@ -318,7 +313,7 @@ abstract class MultiNodeClusterSpec(multiNodeconfig: MultiNodeConfig) def awaitMembersUp( numberOfMembers: Int, canNotBePartOfMemberRing: Set[Address] = Set.empty, - timeout: FiniteDuration = 25.seconds): Unit = { + timeout: FiniteDuration = 25.seconds): Unit = within(timeout) { if (!canNotBePartOfMemberRing.isEmpty) // don't run this on an empty set awaitAssert(canNotBePartOfMemberRing.foreach(a => clusterView.members.map(_.address) should not contain a)) @@ -330,7 +325,6 @@ abstract class MultiNodeClusterSpec(multiNodeconfig: MultiNodeConfig) } awaitAssert(clusterView.leader should ===(expectedLeader)) } - } def awaitMemberRemoved(toBeRemovedAddress: Address, timeout: FiniteDuration = 25.seconds): Unit = within(timeout) { if (toBeRemovedAddress == cluster.selfAddress) { @@ -418,14 +412,13 @@ abstract class MultiNodeClusterSpec(multiNodeconfig: MultiNodeConfig) * [[pekko.cluster.FailureDetectorPuppet]] is used as * failure detector. */ - def markNodeAsUnavailable(address: Address): Unit = { + def markNodeAsUnavailable(address: Address): Unit = if (isFailureDetectorPuppet) { // before marking it as unavailable there should be at least one heartbeat // to create the FailureDetectorPuppet in the FailureDetectorRegistry cluster.failureDetector.heartbeat(address) failureDetectorPuppet(address).foreach(_.markNodeAsUnavailable()) } - } private def isFailureDetectorPuppet: Boolean = cluster.settings.FailureDetectorImplementationClass == classOf[FailureDetectorPuppet].getName diff --git a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/NodeChurnSpec.scala b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/NodeChurnSpec.scala index be2416303ab..a75bcbad53f 100644 --- a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/NodeChurnSpec.scala +++ b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/NodeChurnSpec.scala @@ -79,10 +79,9 @@ abstract class NodeChurnSpec } Runtime.getRuntime.addShutdownHook(new Thread { - override def run(): Unit = { + override def run(): Unit = if (SharedMediaDriverSupport.isMediaDriverRunningByThisNode) println("Abrupt exit of JVM without closing media driver. This should not happen and may cause test failure.") - } }) val rounds = 5 diff --git a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/RemoteFeaturesWithClusterSpec.scala b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/RemoteFeaturesWithClusterSpec.scala index 6e0d89b5b91..5f22b6c61e3 100644 --- a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/RemoteFeaturesWithClusterSpec.scala +++ b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/RemoteFeaturesWithClusterSpec.scala @@ -36,14 +36,13 @@ class ClusterRemoteFeaturesConfig(artery: Boolean) extends MultiNodeConfig { val second = role("second") val third = role("third") - private val baseConfig = { + private val baseConfig = ConfigFactory.parseString(s""" pekko.remote.log-remote-lifecycle-events = off pekko.remote.artery.enabled = $artery pekko.remote.artery.canonical.port = ${MultiNodeSpec.selfPort} pekko.log-dead-letters-during-shutdown = off """).withFallback(MultiNodeClusterSpec.clusterConfig) - } commonConfig(debugConfig(on = false).withFallback(baseConfig)) diff --git a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/SharedMediaDriverSupport.scala b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/SharedMediaDriverSupport.scala index 5450717b7d2..44723d33ac3 100644 --- a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/SharedMediaDriverSupport.scala +++ b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/SharedMediaDriverSupport.scala @@ -50,15 +50,14 @@ object SharedMediaDriverSupport { // Check if the media driver is already started by another multi-node jvm. // It checks more than one time with a sleep in-between. The number of checks // depends on the multi-node index (i). - @tailrec def isDriverInactive(i: Int): Boolean = { + @tailrec def isDriverInactive(i: Int): Boolean = if (i < 0) true else { val active = try CommonContext.isDriverActive(new File(aeronDir), 5000, new Consumer[String] { - override def accept(msg: String): Unit = { + override def accept(msg: String): Unit = println(msg) - } }) catch { case NonFatal(e) => @@ -71,9 +70,8 @@ object SharedMediaDriverSupport { isDriverInactive(i - 1) } } - } - try { + try if (isDriverInactive(MultiNodeSpec.selfIndex)) { val driverContext = new MediaDriver.Context driverContext.aeronDirectoryName(aeronDir) @@ -92,7 +90,7 @@ object SharedMediaDriverSupport { throw new IllegalStateException("media driver started more than once") } } - } catch { + catch { case NonFatal(e) => println(s"Failed to start media driver in [$aeronDir]: ${e.getMessage}") } @@ -111,11 +109,11 @@ object SharedMediaDriverSupport { driver.close() - try { + try if (arterySettings.Advanced.Aeron.DeleteAeronDirectory) { IoUtil.delete(new File(driver.aeronDirectoryName), false) } - } catch { + catch { case NonFatal(e) => println( s"Couldn't delete Aeron embedded media driver files in [${driver.aeronDirectoryName}] " + diff --git a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/SplitBrainSpec.scala b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/SplitBrainSpec.scala index 51b5f41e29d..4eb78bcf094 100644 --- a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/SplitBrainSpec.scala +++ b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/SplitBrainSpec.scala @@ -82,9 +82,8 @@ abstract class SplitBrainSpec(multiNodeConfig: SplitBrainMultiNodeConfig) runOn(first) { // split the cluster in two parts (first, second) / (third, fourth, fifth) - for (role1 <- side1; role2 <- side2) { + for (role1 <- side1; role2 <- side2) testConductor.blackhole(role1, role2, Direction.Both).await - } } enterBarrier("after-split") diff --git a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/StressSpec.scala b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/StressSpec.scala index 6ad2db7aa63..ca359d3f9e6 100644 --- a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/StressSpec.scala +++ b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/StressSpec.scala @@ -179,9 +179,8 @@ private[cluster] object StressMultiJvmSpec extends MultiNodeConfig { numberOfNodesJoinRemove <= totalNumberOfNodes, s"nr-of-nodes-join-remove should be <= $totalNumberOfNodes") - override def toString: String = { + override def toString: String = testConfig.withFallback(ConfigFactory.parseString(s"nrOfNodes=$totalNumberOfNodes")).root.render - } } implicit class FormattedDouble(val d: Double) extends AnyVal { @@ -226,7 +225,7 @@ private[cluster] object StressMultiJvmSpec extends MultiNodeConfig { if (infolog) log.info( s"[$title] completed in [${aggregated.duration.toMillis}] ms\n${aggregated.clusterStats}\n\n$formatPhi\n\n$formatStats") - reportTo.foreach { _ ! aggregated } + reportTo.foreach(_ ! aggregated) context.stop(self) } case _: CurrentClusterState => @@ -235,14 +234,14 @@ private[cluster] object StressMultiJvmSpec extends MultiNodeConfig { def maxDuration = results.map(_.duration).max - def totalGossipStats = results.foldLeft(GossipStats()) { _ :+ _.clusterStats } + def totalGossipStats = results.foldLeft(GossipStats())(_ :+ _.clusterStats) def format(opt: Option[Double]) = opt match { case None => "N/A" case Some(x) => x.form } - def formatPhi: String = { + def formatPhi: String = if (phiValuesObservedByNode.isEmpty) "" else { val lines = @@ -253,7 +252,6 @@ private[cluster] object StressMultiJvmSpec extends MultiNodeConfig { lines.mkString(formatPhiHeader + "\n", "\n", "") } - } def formatPhiHeader: String = "[Monitor]\t[Subject]\t[count]\t[count phi > 1.0]\t[max phi]" @@ -344,7 +342,7 @@ private[cluster] object StressMultiJvmSpec extends MultiNodeConfig { } } val phiSet = immutable.SortedSet.empty[PhiValue] ++ phiByNode.values - reportTo.foreach { _ ! PhiResult(cluster.selfAddress, phiSet) } + reportTo.foreach(_ ! PhiResult(cluster.selfAddress, phiSet)) case state: CurrentClusterState => nodes = state.members.map(_.address) case memberEvent: MemberEvent => nodes += memberEvent.member.address case ReportTo(ref) => @@ -376,11 +374,11 @@ private[cluster] object StressMultiJvmSpec extends MultiNodeConfig { def receive = { case CurrentInternalStats(gossipStats, vclockStats) => val diff = startStats match { - case None => { startStats = Some(gossipStats); gossipStats } + case None => startStats = Some(gossipStats); gossipStats case Some(start) => gossipStats :- start } val res = StatsResult(cluster.selfAddress, CurrentInternalStats(diff, vclockStats)) - reportTo.foreach { _ ! res } + reportTo.foreach(_ ! res) case ReportTo(ref) => reportTo.foreach(context.unwatch) reportTo = ref @@ -455,7 +453,7 @@ abstract class StressSpec extends MultiNodeClusterSpec(StressMultiJvmSpec) with var step = 0 var nbrUsedRoles = 0 - override def beforeEach(): Unit = { step += 1 } + override def beforeEach(): Unit = step += 1 override def expectedTestDuration: FiniteDuration = settings.expectedTestDuration @@ -475,10 +473,9 @@ abstract class StressSpec extends MultiNodeClusterSpec(StressMultiJvmSpec) with } Runtime.getRuntime.addShutdownHook(new Thread { - override def run(): Unit = { + override def run(): Unit = if (SharedMediaDriverSupport.isMediaDriverRunningByThisNode) println("Abrupt exit of JVM without closing media driver. This should not happen and may cause test failure.") - } }) def isArteryEnabled: Boolean = RARP(system).provider.remoteSettings.Artery.Enabled @@ -540,9 +537,8 @@ abstract class StressSpec extends MultiNodeClusterSpec(StressMultiJvmSpec) with def latestGossipStats = cluster.readView.latestStats.gossipStats - override def cluster: Cluster = { + override def cluster: Cluster = super.cluster - } def createResultAggregator(title: String, expectedResults: Int, includeInHistory: Boolean): Unit = { runOn(roles.head) { @@ -587,13 +583,12 @@ abstract class StressSpec extends MultiNodeClusterSpec(StressMultiJvmSpec) with enterBarrier("cluster-result-done-" + step) } - def joinOneByOne(numberOfNodes: Int): Unit = { + def joinOneByOne(numberOfNodes: Int): Unit = (0 until numberOfNodes).foreach { _ => joinOne() nbrUsedRoles += 1 step += 1 } - } def convergenceWithin(base: FiniteDuration, nodes: Int): FiniteDuration = (base.toMillis * convergenceWithinFactor * nodes).millis @@ -636,13 +631,12 @@ abstract class StressSpec extends MultiNodeClusterSpec(StressMultiJvmSpec) with enterBarrier("join-several-" + step) } - def removeOneByOne(numberOfNodes: Int, shutdown: Boolean): Unit = { + def removeOneByOne(numberOfNodes: Int, shutdown: Boolean): Unit = (0 until numberOfNodes).foreach { _ => removeOne(shutdown) nbrUsedRoles -= 1 step += 1 } - } def removeOne(shutdown: Boolean): Unit = within(25.seconds + convergenceWithin(3.seconds, nbrUsedRoles - 1)) { val currentRoles = roles.take(nbrUsedRoles - 1) @@ -722,9 +716,8 @@ abstract class StressSpec extends MultiNodeClusterSpec(StressMultiJvmSpec) with createResultAggregator(title, expectedResults = currentRoles.size, includeInHistory = true) runOn(roles.head) { - for (x <- currentRoles; y <- removeRoles) { + for (x <- currentRoles; y <- removeRoles) testConductor.blackhole(x, y, ThrottlerTransportAdapter.Direction.Both).await - } } enterBarrier("partition-several-blackhole") @@ -772,7 +765,7 @@ abstract class StressSpec extends MultiNodeClusterSpec(StressMultiJvmSpec) with @tailrec def loop( counter: Int, previousAS: Option[ActorSystem], - allPreviousAddresses: Set[Address]): Option[ActorSystem] = { + allPreviousAddresses: Set[Address]): Option[ActorSystem] = if (counter > rounds) previousAS else { val t = title + " round " + counter @@ -814,7 +807,6 @@ abstract class StressSpec extends MultiNodeClusterSpec(StressMultiJvmSpec) with step += 1 loop(counter + 1, nextAS, nextAddresses) } - } loop(1, None, Set.empty).foreach { as => TestKit.shutdownActorSystem(as) diff --git a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/SurviveNetworkInstabilitySpec.scala b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/SurviveNetworkInstabilitySpec.scala index 724c35c2a16..24086bc0581 100644 --- a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/SurviveNetworkInstabilitySpec.scala +++ b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/SurviveNetworkInstabilitySpec.scala @@ -110,14 +110,12 @@ abstract class SurviveNetworkInstabilitySpec classOf[pekko.remote.QuarantinedEvent] @nowarn - def quarantinedEventFrom(event: Any): Address = { + def quarantinedEventFrom(event: Any): Address = event match { case QuarantinedEvent(uniqueAddress) => uniqueAddress.address case pekko.remote.QuarantinedEvent(address, _) => address } - } - @nowarn def sysMsgBufferSize: Int = if (RARP(system).provider.remoteSettings.Artery.Enabled) @@ -168,8 +166,8 @@ abstract class SurviveNetworkInstabilitySpec } enterBarrier("blackhole-2") - runOn(first) { assertUnreachable(second) } - runOn(second) { assertUnreachable(first) } + runOn(first)(assertUnreachable(second)) + runOn(second)(assertUnreachable(first)) runOn(third, fourth, fifth) { assertUnreachable(first, second) } @@ -193,13 +191,12 @@ abstract class SurviveNetworkInstabilitySpec "heal after one isolated node" taggedAs LongRunningTest in within(45.seconds) { val others = Vector(second, third, fourth, fifth) runOn(first) { - for (other <- others) { + for (other <- others) testConductor.blackhole(first, other, Direction.Both).await - } } enterBarrier("blackhole-3") - runOn(first) { assertUnreachable(others: _*) } + runOn(first)(assertUnreachable(others: _*)) runOn(others: _*) { assertUnreachable(first) } @@ -207,9 +204,8 @@ abstract class SurviveNetworkInstabilitySpec enterBarrier("unreachable-3") runOn(first) { - for (other <- others) { + for (other <- others) testConductor.passThrough(first, other, Direction.Both).await - } } enterBarrier("repair-3") assertCanTalk((others :+ first): _*) @@ -220,9 +216,8 @@ abstract class SurviveNetworkInstabilitySpec val island2 = Vector(third, fourth, fifth) runOn(first) { // split the cluster in two parts (first, second) / (third, fourth, fifth) - for (role1 <- island1; role2 <- island2) { + for (role1 <- island1; role2 <- island2) testConductor.blackhole(role1, role2, Direction.Both).await - } } enterBarrier("blackhole-4") @@ -236,9 +231,8 @@ abstract class SurviveNetworkInstabilitySpec enterBarrier("unreachable-4") runOn(first) { - for (role1 <- island1; role2 <- island2) { + for (role1 <- island1; role2 <- island2) testConductor.passThrough(role1, role2, Direction.Both).await - } } enterBarrier("repair-4") assertCanTalk((island1 ++ island2): _*) @@ -248,14 +242,13 @@ abstract class SurviveNetworkInstabilitySpec val joining = Vector(sixth, seventh) val others = Vector(second, third, fourth, fifth) runOn(first) { - for (role1 <- joining :+ first; role2 <- others) { + for (role1 <- joining :+ first; role2 <- others) testConductor.blackhole(role1, role2, Direction.Both).await - } } enterBarrier("blackhole-5") - runOn(first) { assertUnreachable(others: _*) } - runOn(others: _*) { assertUnreachable(first) } + runOn(first)(assertUnreachable(others: _*)) + runOn(others: _*)(assertUnreachable(first)) enterBarrier("unreachable-5") @@ -268,16 +261,15 @@ abstract class SurviveNetworkInstabilitySpec enterBarrier("joined-5") - runOn((joining :+ first): _*) { assertUnreachable(others: _*) } + runOn((joining :+ first): _*)(assertUnreachable(others: _*)) // others doesn't know about the joining nodes yet, no gossip passed through - runOn(others: _*) { assertUnreachable(first) } + runOn(others: _*)(assertUnreachable(first)) enterBarrier("more-unreachable-5") runOn(first) { - for (role1 <- joining :+ first; role2 <- others) { + for (role1 <- joining :+ first; role2 <- others) testConductor.passThrough(role1, role2, Direction.Both).await - } } enterBarrier("repair-5") @@ -361,14 +353,13 @@ abstract class SurviveNetworkInstabilitySpec val side1AfterJoin = side1 :+ eighth val side2 = Vector(fifth, sixth, seventh) runOn(first) { - for (role1 <- side1AfterJoin; role2 <- side2) { + for (role1 <- side1AfterJoin; role2 <- side2) testConductor.blackhole(role1, role2, Direction.Both).await - } } enterBarrier("blackhole-7") - runOn(side1: _*) { assertUnreachable(side2: _*) } - runOn(side2: _*) { assertUnreachable(side1: _*) } + runOn(side1: _*)(assertUnreachable(side2: _*)) + runOn(side2: _*)(assertUnreachable(side1: _*)) enterBarrier("unreachable-7") @@ -376,9 +367,8 @@ abstract class SurviveNetworkInstabilitySpec cluster.join(third) } runOn(fourth) { - for (role2 <- side2) { + for (role2 <- side2) cluster.down(role2) - } } enterBarrier("downed-7") @@ -390,9 +380,8 @@ abstract class SurviveNetworkInstabilitySpec // repeat the downing in case it was not successful, which may // happen if the removal was reverted due to gossip merge, see issue #18767 runOn(fourth) { - for (role2 <- side2) { + for (role2 <- side2) cluster.down(role2) - } } clusterView.members.map(_.address) should ===(expected) @@ -404,9 +393,8 @@ abstract class SurviveNetworkInstabilitySpec enterBarrier("side2-removed") runOn(first) { - for (role1 <- side1AfterJoin; role2 <- side2) { + for (role1 <- side1AfterJoin; role2 <- side2) testConductor.passThrough(role1, role2, Direction.Both).await - } } enterBarrier("repair-7") diff --git a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/UnreachableNodeJoinsAgainSpec.scala b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/UnreachableNodeJoinsAgainSpec.scala index 3bfe0beda35..9490b1d0da8 100644 --- a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/UnreachableNodeJoinsAgainSpec.scala +++ b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/UnreachableNodeJoinsAgainSpec.scala @@ -58,9 +58,8 @@ abstract class UnreachableNodeJoinsAgainSpec extends MultiNodeClusterSpec(Unreac muteMarkingAsUnreachable() - def allBut(role: RoleName, roles: immutable.Seq[RoleName] = roles): immutable.Seq[RoleName] = { + def allBut(role: RoleName, roles: immutable.Seq[RoleName] = roles): immutable.Seq[RoleName] = roles.filterNot(_ == role) - } lazy val master = second lazy val victim = fourth @@ -203,9 +202,8 @@ abstract class UnreachableNodeJoinsAgainSpec extends MultiNodeClusterSpec(Unreac endActor ! EndActor.SendEnd endProbe.expectMsg(EndActor.EndAck) - } finally { + } finally shutdown(freshSystem) - } // no barrier here, because it is not part of testConductor roles any more } diff --git a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/routing/ClusterConsistentHashingGroupSpec.scala b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/routing/ClusterConsistentHashingGroupSpec.scala index 088a79b18d1..bf931ad4ef8 100644 --- a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/routing/ClusterConsistentHashingGroupSpec.scala +++ b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/routing/ClusterConsistentHashingGroupSpec.scala @@ -77,9 +77,9 @@ abstract class ClusterConsistentHashingGroupSpec settings = ClusterRouterGroupSettings(totalInstances = 10, paths, allowLocalRoutees = true)).props(), "router") // it may take some time until router receives cluster member events - awaitAssert { currentRoutees(router).size should ===(3) } + awaitAssert(currentRoutees(router).size should ===(3)) val keys = List("A", "B", "C", "D", "E", "F", "G") - for (_ <- 1 to 10; k <- keys) { router ! k } + for (_ <- 1 to 10; k <- keys) router ! k enterBarrier("messages-sent") router ! Broadcast(Get) val a = expectMsgType[ClusterConsistentHashingGroupMultiJvmSpec.Collected].messages diff --git a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/routing/ClusterConsistentHashingRouterSpec.scala b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/routing/ClusterConsistentHashingRouterSpec.scala index 506be433a31..8a1a24deb45 100644 --- a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/routing/ClusterConsistentHashingRouterSpec.scala +++ b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/routing/ClusterConsistentHashingRouterSpec.scala @@ -97,7 +97,7 @@ abstract class ClusterConsistentHashingRouterSpec "create routees from configuration" in { runOn(first) { // it may take some time until router receives cluster member events - awaitAssert { currentRoutees(router1).size should ===(4) } + awaitAssert(currentRoutees(router1).size should ===(4)) val routees = currentRoutees(router1) routees.collect { case ActorRefRoutee(ref) => fullAddress(ref) }.toSet should ===( Set(address(first), address(second))) @@ -121,7 +121,7 @@ abstract class ClusterConsistentHashingRouterSpec runOn(first) { // it may take some time until router receives cluster member events - awaitAssert { currentRoutees(router1).size should ===(6) } + awaitAssert(currentRoutees(router1).size should ===(6)) val routees = currentRoutees(router1) routees.collect { case ActorRefRoutee(ref) => fullAddress(ref) }.toSet should ===(roles.map(address).toSet) } @@ -139,7 +139,7 @@ abstract class ClusterConsistentHashingRouterSpec .props(Props[Echo]()), "router2") // it may take some time until router receives cluster member events - awaitAssert { currentRoutees(router2).size should ===(6) } + awaitAssert(currentRoutees(router2).size should ===(6)) val routees = currentRoutees(router2) routees.collect { case ActorRefRoutee(ref) => fullAddress(ref) }.toSet should ===(roles.map(address).toSet) } @@ -187,7 +187,7 @@ abstract class ClusterConsistentHashingRouterSpec def assertHashMapping(router: ActorRef): Unit = { // it may take some time until router receives cluster member events - awaitAssert { currentRoutees(router).size should ===(6) } + awaitAssert(currentRoutees(router).size should ===(6)) val routees = currentRoutees(router) routees.collect { case ActorRefRoutee(ref) => fullAddress(ref) }.toSet should ===(roles.map(address).toSet) diff --git a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/routing/ClusterRoundRobinSpec.scala b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/routing/ClusterRoundRobinSpec.scala index e49c82e0e60..6d3da658578 100644 --- a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/routing/ClusterRoundRobinSpec.scala +++ b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/routing/ClusterRoundRobinSpec.scala @@ -165,9 +165,8 @@ abstract class ClusterRoundRobinSpec awaitAssert(currentRoutees(router1).size should ===(4)) val iterationCount = 10 - for (_ <- 0 until iterationCount) { + for (_ <- 0 until iterationCount) router1 ! "hit" - } val replies = receiveReplies(PoolRoutee, iterationCount) @@ -196,9 +195,8 @@ abstract class ClusterRoundRobinSpec } val iterationCount = 10 - for (_ <- 0 until iterationCount) { + for (_ <- 0 until iterationCount) router4 ! "hit" - } val replies = receiveReplies(GroupRoutee, iterationCount) @@ -222,13 +220,12 @@ abstract class ClusterRoundRobinSpec awaitAssert(currentRoutees(router1).size should ===(8)) val iterationCount = 10 - for (_ <- 0 until iterationCount) { + for (_ <- 0 until iterationCount) router1 ! "hit" - } val replies = receiveReplies(PoolRoutee, iterationCount) - replies.values.foreach { _ should be > 0 } + replies.values.foreach(_ should be > 0) replies.values.sum should ===(iterationCount) } @@ -244,13 +241,12 @@ abstract class ClusterRoundRobinSpec awaitAssert(currentRoutees(router4).size should ===(8)) val iterationCount = 10 - for (_ <- 0 until iterationCount) { + for (_ <- 0 until iterationCount) router4 ! "hit" - } val replies = receiveReplies(GroupRoutee, iterationCount) - replies.values.foreach { _ should be > 0 } + replies.values.foreach(_ should be > 0) replies.values.sum should ===(iterationCount) } @@ -264,9 +260,8 @@ abstract class ClusterRoundRobinSpec awaitAssert(currentRoutees(router3).size should ===(3)) val iterationCount = 10 - for (_ <- 0 until iterationCount) { + for (_ <- 0 until iterationCount) router3 ! "hit" - } val replies = receiveReplies(PoolRoutee, iterationCount) @@ -286,9 +281,8 @@ abstract class ClusterRoundRobinSpec awaitAssert(currentRoutees(router5).size should ===(2)) val iterationCount = 10 - for (_ <- 0 until iterationCount) { + for (_ <- 0 until iterationCount) router5 ! "hit" - } val replies = receiveReplies(PoolRoutee, iterationCount) @@ -311,9 +305,8 @@ abstract class ClusterRoundRobinSpec awaitAssert(currentRoutees(router2).size should ===(3)) val iterationCount = 10 - for (_ <- 0 until iterationCount) { + for (_ <- 0 until iterationCount) router2 ! "hit" - } val replies = receiveReplies(PoolRoutee, iterationCount) @@ -378,9 +371,8 @@ abstract class ClusterRoundRobinSpec } val iterationCount = 10 - for (_ <- 0 until iterationCount) { + for (_ <- 0 until iterationCount) router2 ! "hit" - } val replies = receiveReplies(PoolRoutee, iterationCount) diff --git a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/routing/UseRoleIgnoredSpec.scala b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/routing/UseRoleIgnoredSpec.scala index d0dec303a13..90975db83e2 100644 --- a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/routing/UseRoleIgnoredSpec.scala +++ b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/routing/UseRoleIgnoredSpec.scala @@ -96,9 +96,9 @@ abstract class UseRoleIgnoredSpec "A cluster" must { "start cluster" taggedAs LongRunningTest in { awaitClusterUp(first, second, third) - runOn(first) { info("first, roles: " + cluster.selfRoles) } - runOn(second) { info("second, roles: " + cluster.selfRoles) } - runOn(third) { info("third, roles: " + cluster.selfRoles) } + runOn(first)(info("first, roles: " + cluster.selfRoles)) + runOn(second)(info("second, roles: " + cluster.selfRoles)) + runOn(third)(info("third, roles: " + cluster.selfRoles)) // routees for the group routers system.actorOf(Props(classOf[SomeActor], GroupRoutee), "foo") @@ -125,9 +125,8 @@ abstract class UseRoleIgnoredSpec awaitAssert(currentRoutees(router).size should ===(4)) val iterationCount = 10 - for (i <- 0 until iterationCount) { + for (i <- 0 until iterationCount) router ! s"hit-$i" - } val replies = receiveReplies(PoolRoutee, iterationCount) @@ -158,9 +157,8 @@ abstract class UseRoleIgnoredSpec awaitAssert(currentRoutees(router).size should ===(4)) val iterationCount = 10 - for (i <- 0 until iterationCount) { + for (i <- 0 until iterationCount) router ! s"hit-$i" - } val replies = receiveReplies(GroupRoutee, iterationCount) @@ -191,9 +189,8 @@ abstract class UseRoleIgnoredSpec awaitAssert(currentRoutees(router).size should ===(4)) val iterationCount = 10 - for (i <- 0 until iterationCount) { + for (i <- 0 until iterationCount) router ! s"hit-$i" - } val replies = receiveReplies(PoolRoutee, iterationCount) @@ -224,9 +221,8 @@ abstract class UseRoleIgnoredSpec awaitAssert(currentRoutees(router).size should ===(4)) val iterationCount = 10 - for (i <- 0 until iterationCount) { + for (i <- 0 until iterationCount) router ! s"hit-$i" - } val replies = receiveReplies(GroupRoutee, iterationCount) @@ -257,9 +253,8 @@ abstract class UseRoleIgnoredSpec awaitAssert(currentRoutees(router).size should ===(2)) val iterationCount = 10 - for (i <- 0 until iterationCount) { + for (i <- 0 until iterationCount) router ! s"hit-$i" - } val replies = receiveReplies(PoolRoutee, iterationCount) @@ -290,9 +285,8 @@ abstract class UseRoleIgnoredSpec awaitAssert(currentRoutees(router).size should ===(2)) val iterationCount = 10 - for (i <- 0 until iterationCount) { + for (i <- 0 until iterationCount) router ! s"hit-$i" - } val replies = receiveReplies(GroupRoutee, iterationCount) @@ -323,9 +317,8 @@ abstract class UseRoleIgnoredSpec awaitAssert(currentRoutees(router).size should ===(6)) val iterationCount = 10 - for (i <- 0 until iterationCount) { + for (i <- 0 until iterationCount) router ! s"hit-$i" - } val replies = receiveReplies(PoolRoutee, iterationCount) @@ -356,9 +349,8 @@ abstract class UseRoleIgnoredSpec awaitAssert(currentRoutees(router).size should ===(6)) val iterationCount = 10 - for (i <- 0 until iterationCount) { + for (i <- 0 until iterationCount) router ! s"hit-$i" - } val replies = receiveReplies(GroupRoutee, iterationCount) diff --git a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/sbr/DownAllIndirectlyConnected5NodeSpec.scala b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/sbr/DownAllIndirectlyConnected5NodeSpec.scala index 3080c4676ad..53e47d12acb 100644 --- a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/sbr/DownAllIndirectlyConnected5NodeSpec.scala +++ b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/sbr/DownAllIndirectlyConnected5NodeSpec.scala @@ -82,9 +82,8 @@ class DownAllIndirectlyConnected5NodeSpec extends MultiNodeClusterSpec(DownAllIn enterBarrier("Cluster formed") runOn(node1) { - for (x <- List(node1, node2, node3); y <- List(node4, node5)) { + for (x <- List(node1, node2, node3); y <- List(node4, node5)) testConductor.blackhole(x, y, ThrottlerTransportAdapter.Direction.Both).await - } } enterBarrier("blackholed-clean-partition") diff --git a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/sbr/DownAllUnstable5NodeSpec.scala b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/sbr/DownAllUnstable5NodeSpec.scala index f7db6ad718b..5e8ea5cbcaa 100644 --- a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/sbr/DownAllUnstable5NodeSpec.scala +++ b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/sbr/DownAllUnstable5NodeSpec.scala @@ -92,9 +92,8 @@ class DownAllUnstable5NodeSpec extends MultiNodeClusterSpec(DownAllUnstable5Node // down-all-when-unstable = 7s runOn(node1) { - for (x <- List(node1, node2, node3); y <- List(node4, node5)) { + for (x <- List(node1, node2, node3); y <- List(node4, node5)) testConductor.blackhole(x, y, ThrottlerTransportAdapter.Direction.Both).await - } } enterBarrier("blackholed-clean-partition") diff --git a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/sbr/IndirectlyConnected5NodeSpec.scala b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/sbr/IndirectlyConnected5NodeSpec.scala index f566116f67b..927bc03173f 100644 --- a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/sbr/IndirectlyConnected5NodeSpec.scala +++ b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/sbr/IndirectlyConnected5NodeSpec.scala @@ -82,9 +82,8 @@ class IndirectlyConnected5NodeSpec extends MultiNodeClusterSpec(IndirectlyConnec enterBarrier("Cluster formed") runOn(node1) { - for (x <- List(node1, node2, node3); y <- List(node4, node5)) { + for (x <- List(node1, node2, node3); y <- List(node4, node5)) testConductor.blackhole(x, y, ThrottlerTransportAdapter.Direction.Both).await - } } enterBarrier("blackholed-clean-partition") diff --git a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/sbr/LeaseMajority5NodeSpec.scala b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/sbr/LeaseMajority5NodeSpec.scala index ef44ce59484..a71846adb94 100644 --- a/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/sbr/LeaseMajority5NodeSpec.scala +++ b/cluster/src/multi-jvm/scala/org/apache/pekko/cluster/sbr/LeaseMajority5NodeSpec.scala @@ -131,9 +131,8 @@ class LeaseMajority5NodeSpec extends MultiNodeClusterSpec(LeaseMajority5NodeSpec } enterBarrier("lease-in-place") runOn(node1) { - for (x <- List(node1, node2, node3); y <- List(node4, node5)) { + for (x <- List(node1, node2, node3); y <- List(node4, node5)) testConductor.blackhole(x, y, ThrottlerTransportAdapter.Direction.Both).await - } } enterBarrier("blackholed-clean-partition") @@ -177,9 +176,8 @@ class LeaseMajority5NodeSpec extends MultiNodeClusterSpec(LeaseMajority5NodeSpec } enterBarrier("lease-in-place-2") runOn(node1) { - for (x <- List(node1); y <- List(node2, node3)) { + for (x <- List(node1); y <- List(node2, node3)) testConductor.blackhole(x, y, ThrottlerTransportAdapter.Direction.Both).await - } } enterBarrier("blackholed-clean-partition-2") diff --git a/cluster/src/test/scala/org/apache/pekko/cluster/ClusterDeathWatchNotificationSpec.scala b/cluster/src/test/scala/org/apache/pekko/cluster/ClusterDeathWatchNotificationSpec.scala index 397ab77a149..ac9c0a1039f 100644 --- a/cluster/src/test/scala/org/apache/pekko/cluster/ClusterDeathWatchNotificationSpec.scala +++ b/cluster/src/test/scala/org/apache/pekko/cluster/ClusterDeathWatchNotificationSpec.scala @@ -46,9 +46,8 @@ object ClusterDeathWatchNotificationSpec { case msg => sender() ! msg } - override def postStop(): Unit = { + override def postStop(): Unit = sendOnStop.foreach(receiver ! _) - } } } diff --git a/cluster/src/test/scala/org/apache/pekko/cluster/ClusterDomainEventSpec.scala b/cluster/src/test/scala/org/apache/pekko/cluster/ClusterDomainEventSpec.scala index b2cb1308d84..382b65dbb0d 100644 --- a/cluster/src/test/scala/org/apache/pekko/cluster/ClusterDomainEventSpec.scala +++ b/cluster/src/test/scala/org/apache/pekko/cluster/ClusterDomainEventSpec.scala @@ -46,13 +46,11 @@ class ClusterDomainEventSpec extends AnyWordSpec with Matchers with BeforeAndAft val selfDummyAddress = UniqueAddress(Address("pekko", "sys", "selfDummy", 7355), 17L) private val originalClusterAssert = sys.props.get("pekko.cluster.assert").getOrElse("false") - override protected def beforeAll(): Unit = { + override protected def beforeAll(): Unit = System.setProperty("pekko.cluster.assert", "on") - } - override protected def afterAll(): Unit = { + override protected def afterAll(): Unit = System.setProperty("pekko.cluster.assert", originalClusterAssert) - } private[cluster] def converge(gossip: Gossip): (Gossip, Set[UniqueAddress]) = gossip.members.foldLeft((gossip, Set.empty[UniqueAddress])) { diff --git a/cluster/src/test/scala/org/apache/pekko/cluster/ClusterHeartbeatSenderSpec.scala b/cluster/src/test/scala/org/apache/pekko/cluster/ClusterHeartbeatSenderSpec.scala index c5c6b6ecb42..92633d9cb70 100644 --- a/cluster/src/test/scala/org/apache/pekko/cluster/ClusterHeartbeatSenderSpec.scala +++ b/cluster/src/test/scala/org/apache/pekko/cluster/ClusterHeartbeatSenderSpec.scala @@ -27,9 +27,8 @@ object ClusterHeartbeatSenderSpec { override def preStart(): Unit = {} // override where the heart beats go to - override def heartbeatReceiver(address: Address): ActorSelection = { + override def heartbeatReceiver(address: Address): ActorSelection = context.actorSelection(probe.ref.path) - } } } diff --git a/cluster/src/test/scala/org/apache/pekko/cluster/ClusterHeartbeatSenderStateSpec.scala b/cluster/src/test/scala/org/apache/pekko/cluster/ClusterHeartbeatSenderStateSpec.scala index 936ed353580..88ab1d2ce17 100644 --- a/cluster/src/test/scala/org/apache/pekko/cluster/ClusterHeartbeatSenderStateSpec.scala +++ b/cluster/src/test/scala/org/apache/pekko/cluster/ClusterHeartbeatSenderStateSpec.scala @@ -175,7 +175,7 @@ class ClusterHeartbeatSenderStateSpec extends AnyWordSpec with Matchers { for (i <- 1 to 100000) { val operation = rnd.nextInt(Add, HeartbeatRsp + 1) val node = rndNode() - try { + try operation match { case Add => if (node != selfUniqueAddress && !state.ring.nodes.contains(node)) { @@ -232,7 +232,7 @@ class ClusterHeartbeatSenderStateSpec extends AnyWordSpec with Matchers { case _ => throw new RuntimeException() } - } catch { + catch { case e: Throwable => println( s"Failure context: i=$i, node=$node, op=$operation, " + diff --git a/cluster/src/test/scala/org/apache/pekko/cluster/ClusterSpec.scala b/cluster/src/test/scala/org/apache/pekko/cluster/ClusterSpec.scala index 8dd0cdf01e9..4d89e1d5462 100644 --- a/cluster/src/test/scala/org/apache/pekko/cluster/ClusterSpec.scala +++ b/cluster/src/test/scala/org/apache/pekko/cluster/ClusterSpec.scala @@ -126,18 +126,16 @@ class ClusterSpec extends PekkoSpec(ClusterSpec.config) with ImplicitSender { try { cluster.subscribe(testActor, ClusterEvent.InitialStateAsSnapshot, classOf[ClusterEvent.MemberEvent]) expectMsgClass(classOf[ClusterEvent.CurrentClusterState]) - } finally { + } finally cluster.unsubscribe(testActor) - } } "publish initial state as events to subscribers" in { try { cluster.subscribe(testActor, ClusterEvent.InitialStateAsEvents, classOf[ClusterEvent.MemberEvent]) expectMsgClass(classOf[ClusterEvent.MemberUp]) - } finally { + } finally cluster.unsubscribe(testActor) - } } "send CurrentClusterState to one receiver when requested" in { @@ -178,9 +176,8 @@ class ClusterSpec extends PekkoSpec(ClusterSpec.config) with ImplicitSender { Cluster(sys2).isTerminated should ===(true) } } - } finally { + } finally shutdown(sys2) - } } "allow to resolve remotePathOf any actor" in { @@ -214,9 +211,8 @@ class ClusterSpec extends PekkoSpec(ClusterSpec.config) with ImplicitSender { } .asInstanceOf[MemberRemoved] removed.previousStatus should ===(MemberStatus.Exiting) - } finally { + } finally shutdown(sys2) - } } "terminate ActorSystem via CoordinatedShutdown.run when a stream involving StreamRefs is running" in { @@ -252,9 +248,8 @@ class ClusterSpec extends PekkoSpec(ClusterSpec.config) with ImplicitSender { Await.result(sys2.whenTerminated, 10.seconds) Cluster(sys2).isTerminated should ===(true) CoordinatedShutdown(sys2).shutdownReason() should ===(Some(CoordinatedShutdown.UnknownReason)) - } finally { + } finally shutdown(sys2) - } } "leave via CoordinatedShutdown.run when member status is Joining" in { @@ -283,9 +278,8 @@ class ClusterSpec extends PekkoSpec(ClusterSpec.config) with ImplicitSender { } .asInstanceOf[MemberRemoved] removed.previousStatus should ===(MemberStatus.Exiting) - } finally { + } finally shutdown(sys2) - } } "terminate ActorSystem via leave (CoordinatedShutdown)" in { @@ -317,9 +311,8 @@ class ClusterSpec extends PekkoSpec(ClusterSpec.config) with ImplicitSender { Await.result(sys2.whenTerminated, 10.seconds) Cluster(sys2).isTerminated should ===(true) CoordinatedShutdown(sys2).shutdownReason() should ===(Some(CoordinatedShutdown.ClusterLeavingReason)) - } finally { + } finally shutdown(sys2) - } } "terminate ActorSystem via down (CoordinatedShutdown)" in { @@ -345,9 +338,8 @@ class ClusterSpec extends PekkoSpec(ClusterSpec.config) with ImplicitSender { Await.result(sys3.whenTerminated, 10.seconds) Cluster(sys3).isTerminated should ===(true) CoordinatedShutdown(sys3).shutdownReason() should ===(Some(CoordinatedShutdown.ClusterDowningReason)) - } finally { + } finally shutdown(sys3) - } } "register multiple cluster JMX MBeans with pekko.cluster.jmx.multi-mbeans-in-same-jvm = on" in { diff --git a/cluster/src/test/scala/org/apache/pekko/cluster/ClusterTestKit.scala b/cluster/src/test/scala/org/apache/pekko/cluster/ClusterTestKit.scala index 2c501712297..0b012e3f710 100644 --- a/cluster/src/test/scala/org/apache/pekko/cluster/ClusterTestKit.scala +++ b/cluster/src/test/scala/org/apache/pekko/cluster/ClusterTestKit.scala @@ -225,13 +225,12 @@ abstract class RollingUpgradeClusterSpec(config: Config) extends PekkoSpec(confi val rolling = Random.shuffle(nodes) - for (restarting <- rolling.tail) { + for (restarting <- rolling.tail) within(timeout) { val restarted = util.quitAndRestart(restarting, config(upgradeConfig)) util.joinCluster(restarted) awaitCond(if (shouldRejoin) util.isMemberUp(restarted) else util.isTerminated(restarted)) } - } awaitCond(Cluster(rolling.head).readView.members.size == (if (shouldRejoin) rolling.size else 1), awaitAll) } finally util.shutdownAll() diff --git a/cluster/src/test/scala/org/apache/pekko/cluster/CrossDcHeartbeatSenderSpec.scala b/cluster/src/test/scala/org/apache/pekko/cluster/CrossDcHeartbeatSenderSpec.scala index 7b2fff218b7..1d06a32cad9 100644 --- a/cluster/src/test/scala/org/apache/pekko/cluster/CrossDcHeartbeatSenderSpec.scala +++ b/cluster/src/test/scala/org/apache/pekko/cluster/CrossDcHeartbeatSenderSpec.scala @@ -33,9 +33,8 @@ object CrossDcHeartbeatSenderSpec { // disable register for cluster events override def preStart(): Unit = {} - override def heartbeatReceiver(address: Address): ActorSelection = { + override def heartbeatReceiver(address: Address): ActorSelection = context.actorSelection(heartbeatProbe.ref.path) - } } } diff --git a/cluster/src/test/scala/org/apache/pekko/cluster/DowningProviderSpec.scala b/cluster/src/test/scala/org/apache/pekko/cluster/DowningProviderSpec.scala index 3619fb2488f..7c2617ac8a3 100644 --- a/cluster/src/test/scala/org/apache/pekko/cluster/DowningProviderSpec.scala +++ b/cluster/src/test/scala/org/apache/pekko/cluster/DowningProviderSpec.scala @@ -30,9 +30,8 @@ import scala.util.control.NonFatal class FailingDowningProvider(@unused system: ActorSystem) extends DowningProvider { override val downRemovalMargin: FiniteDuration = 20.seconds - override def downingActorProps: Option[Props] = { + override def downingActorProps: Option[Props] = throw new ConfigurationException("this provider never works") - } } class DummyDowningProvider(@unused system: ActorSystem) extends DowningProvider { @@ -89,14 +88,14 @@ class DowningProviderSpec extends AnyWordSpec with Matchers { // graceful shutdown fast enough that creating the actor system throws on constructing // thread (or slow enough that we have time to try join the cluster before noticing) val maybeSystem = - try { + try Some( ActorSystem( "auto-downing", ConfigFactory.parseString(""" pekko.cluster.downing-provider-class="org.apache.pekko.cluster.FailingDowningProvider" """).withFallback(baseConf))) - } catch { + catch { case NonFatal(_) => // expected to sometimes happen None diff --git a/cluster/src/test/scala/org/apache/pekko/cluster/JoinConfigCompatCheckerRollingUpdateSpec.scala b/cluster/src/test/scala/org/apache/pekko/cluster/JoinConfigCompatCheckerRollingUpdateSpec.scala index 67e62ae1acb..d95c567d115 100644 --- a/cluster/src/test/scala/org/apache/pekko/cluster/JoinConfigCompatCheckerRollingUpdateSpec.scala +++ b/cluster/src/test/scala/org/apache/pekko/cluster/JoinConfigCompatCheckerRollingUpdateSpec.scala @@ -81,9 +81,8 @@ class JoinConfigCompatCheckerRollingUpdateSpec class JoinConfigCompatRollingUpdateChecker extends JoinConfigCompatChecker { override def requiredKeys: im.Seq[String] = im.Seq("pekko.cluster.new-configuration") - override def check(toCheck: Config, actualConfig: Config): ConfigValidation = { + override def check(toCheck: Config, actualConfig: Config): ConfigValidation = if (toCheck.hasPath(requiredKeys.head)) JoinConfigCompatChecker.fullMatch(requiredKeys, toCheck, actualConfig) else Valid - } } diff --git a/cluster/src/test/scala/org/apache/pekko/cluster/JoinConfigCompatCheckerSpec.scala b/cluster/src/test/scala/org/apache/pekko/cluster/JoinConfigCompatCheckerSpec.scala index 3fdff1a557a..52d153f7427 100644 --- a/cluster/src/test/scala/org/apache/pekko/cluster/JoinConfigCompatCheckerSpec.scala +++ b/cluster/src/test/scala/org/apache/pekko/cluster/JoinConfigCompatCheckerSpec.scala @@ -67,11 +67,10 @@ class JoinConfigCompatCheckerSpec extends PekkoSpec with ClusterTestKit { val joiningNode = clusterTestUtil.newActorSystem(configWithChecker) clusterTestUtil.formCluster() - try { + try awaitCond(clusterTestUtil.isMemberUp(joiningNode), message = "awaiting joining node to be 'Up'") - } finally { + finally clusterTestUtil.shutdownAll() - } } @@ -99,16 +98,14 @@ class JoinConfigCompatCheckerSpec extends PekkoSpec with ClusterTestKit { clusterTestUtil.formCluster() - try { - + try // node will shutdown after unsuccessful join attempt within(5.seconds) { awaitCond(clusterTestUtil.isTerminated(joiningNode)) } - } finally { + finally clusterTestUtil.shutdownAll() - } } @@ -141,15 +138,14 @@ class JoinConfigCompatCheckerSpec extends PekkoSpec with ClusterTestKit { clusterTestUtil.formCluster() - try { + try // node will shutdown after unsuccessful join attempt within(5.seconds) { awaitCond(clusterTestUtil.isTerminated(joiningNode)) } - } finally { + finally clusterTestUtil.shutdownAll() - } } @@ -178,15 +174,14 @@ class JoinConfigCompatCheckerSpec extends PekkoSpec with ClusterTestKit { clusterTestUtil.formCluster() - try { + try // node will shutdown after unsuccessful join attempt within(5.seconds) { awaitCond(clusterTestUtil.isTerminated(joiningNode)) } - } finally { + finally clusterTestUtil.shutdownAll() - } } @@ -219,12 +214,11 @@ class JoinConfigCompatCheckerSpec extends PekkoSpec with ClusterTestKit { clusterTestUtil.formCluster() - try { + try // join with compatible node awaitCond(clusterTestUtil.isMemberUp(joiningNode), message = "awaiting joining node to be 'Up'") - } finally { + finally clusterTestUtil.shutdownAll() - } } @@ -254,12 +248,11 @@ class JoinConfigCompatCheckerSpec extends PekkoSpec with ClusterTestKit { clusterTestUtil.formCluster() - try { + try // join with compatible node awaitCond(clusterTestUtil.isMemberUp(joiningNode), message = "awaiting joining node to be 'Up'") - } finally { + finally clusterTestUtil.shutdownAll() - } } /** This test verifies the built-in JoinConfigCompatCheckerPekkoCluster */ @@ -286,15 +279,14 @@ class JoinConfigCompatCheckerSpec extends PekkoSpec with ClusterTestKit { clusterTestUtil.formCluster() - try { + try // node will shutdown after unsuccessful join attempt within(5.seconds) { awaitCond(clusterTestUtil.isTerminated(joiningNode)) } - } finally { + finally clusterTestUtil.shutdownAll() - } } @@ -312,7 +304,7 @@ class JoinConfigCompatCheckerSpec extends PekkoSpec with ClusterTestKit { clusterTestUtil.formCluster() - try { + try within(25.seconds) { // we must wait second node to join the cluster before shutting down the first node awaitCond(clusterTestUtil.isMemberUp(secondNode), message = "awaiting second node to be 'Up'") @@ -323,9 +315,8 @@ class JoinConfigCompatCheckerSpec extends PekkoSpec with ClusterTestKit { awaitCond(clusterTestUtil.isMemberUp(restartedNode), message = "awaiting restarted first node to be 'Up'") } - } finally { + finally clusterTestUtil.shutdownAll() - } } @@ -354,7 +345,7 @@ class JoinConfigCompatCheckerSpec extends PekkoSpec with ClusterTestKit { clusterTestUtil.formCluster() - try { + try within(25.seconds) { // we must wait second node to join the cluster before shutting down the first node awaitCond(clusterTestUtil.isMemberUp(secondNode), message = "awaiting second node to be 'Up'") @@ -366,9 +357,8 @@ class JoinConfigCompatCheckerSpec extends PekkoSpec with ClusterTestKit { awaitCond(clusterTestUtil.isTerminated(restartedNode)) } - } finally { + finally clusterTestUtil.shutdownAll() - } } @@ -402,7 +392,7 @@ class JoinConfigCompatCheckerSpec extends PekkoSpec with ClusterTestKit { clusterTestUtil.formCluster() - try { + try within(25.seconds) { // we must wait second node to join the cluster before shutting down the first node awaitCond(clusterTestUtil.isMemberUp(secondNode), message = "awaiting second node to be 'Up'") @@ -414,9 +404,8 @@ class JoinConfigCompatCheckerSpec extends PekkoSpec with ClusterTestKit { awaitCond(clusterTestUtil.isTerminated(restartedNode)) } - } finally { + finally clusterTestUtil.shutdownAll() - } } @@ -446,7 +435,7 @@ class JoinConfigCompatCheckerSpec extends PekkoSpec with ClusterTestKit { clusterTestUtil.formCluster() - try { + try within(25.seconds) { // we must wait second node to join the cluster before shutting down the first node awaitCond(clusterTestUtil.isMemberUp(secondNode), message = "awaiting second node to be 'Up'") @@ -458,9 +447,8 @@ class JoinConfigCompatCheckerSpec extends PekkoSpec with ClusterTestKit { awaitCond(clusterTestUtil.isTerminated(restartedNode)) } - } finally { + finally clusterTestUtil.shutdownAll() - } } @@ -494,7 +482,7 @@ class JoinConfigCompatCheckerSpec extends PekkoSpec with ClusterTestKit { clusterTestUtil.formCluster() - try { + try within(25.seconds) { // join with compatible node // we must wait second node to join the cluster before shutting down the first node @@ -506,9 +494,8 @@ class JoinConfigCompatCheckerSpec extends PekkoSpec with ClusterTestKit { // node will will have joined the cluster awaitCond(clusterTestUtil.isMemberUp(restartedNode), message = "awaiting restarted node to be 'Up'") } - } finally { + finally clusterTestUtil.shutdownAll() - } } @@ -539,7 +526,7 @@ class JoinConfigCompatCheckerSpec extends PekkoSpec with ClusterTestKit { clusterTestUtil.formCluster() - try { + try within(25.seconds) { // join with compatible node // we must wait second node to join the cluster before shutting down the first node @@ -551,9 +538,8 @@ class JoinConfigCompatCheckerSpec extends PekkoSpec with ClusterTestKit { // node will will have joined the cluster awaitCond(clusterTestUtil.isMemberUp(restartedNode), message = "awaiting restarted node to be 'Up'") } - } finally { + finally clusterTestUtil.shutdownAll() - } } } @@ -599,14 +585,13 @@ class JoinConfigCompatCheckerSpec extends PekkoSpec with ClusterTestKit { clusterTestUtil.formCluster() - try { + try // node will shutdown after unsuccessful join attempt within(5.seconds) { awaitCond(clusterTestUtil.isTerminated(joiningNode)) } - } finally { + finally clusterTestUtil.shutdownAll() - } } "be allowed to disable a check" taggedAs LongRunningTest in { @@ -631,9 +616,8 @@ class JoinConfigCompatCheckerSpec extends PekkoSpec with ClusterTestKit { try { val sys = clusterTestUtil.newActorSystem(joinNodeConfig.withFallback(configWithChecker)) Cluster(sys).settings.ConfigCompatCheckers should ===(Set.empty[String]) - } finally { + } finally clusterTestUtil.shutdownAll() - } } } } diff --git a/cluster/src/test/scala/org/apache/pekko/cluster/ReachabilityPerfSpec.scala b/cluster/src/test/scala/org/apache/pekko/cluster/ReachabilityPerfSpec.scala index f8f096c3141..ff9bbeb3272 100644 --- a/cluster/src/test/scala/org/apache/pekko/cluster/ReachabilityPerfSpec.scala +++ b/cluster/src/test/scala/org/apache/pekko/cluster/ReachabilityPerfSpec.scala @@ -56,21 +56,16 @@ class ReachabilityPerfSpec extends AnyWordSpec with Matchers { r1: Reachability, r2: Reachability, thunk: (Reachability, Reachability) => Unit, - times: Int): Unit = { - for (_ <- 1 to times) { + times: Int): Unit = + for (_ <- 1 to times) thunk(Reachability(r1.records, r1.versions), Reachability(r2.records, r2.versions)) - } - } - private def checkThunkFor(r1: Reachability, thunk: Reachability => Unit, times: Int): Unit = { - for (_ <- 1 to times) { + private def checkThunkFor(r1: Reachability, thunk: Reachability => Unit, times: Int): Unit = + for (_ <- 1 to times) thunk(Reachability(r1.records, r1.versions)) - } - } - private def merge(expectedRecords: Int)(r1: Reachability, r2: Reachability): Unit = { + private def merge(expectedRecords: Int)(r1: Reachability, r2: Reachability): Unit = r1.merge(allowed, r2).records.size should ===(expectedRecords) - } private def checkStatus(r1: Reachability): Unit = { val record = r1.records.head @@ -82,19 +77,16 @@ class ReachabilityPerfSpec extends AnyWordSpec with Matchers { r1.status(record.subject) should ===(record.status) } - private def allUnreachableOrTerminated(r1: Reachability): Unit = { + private def allUnreachableOrTerminated(r1: Reachability): Unit = r1.allUnreachableOrTerminated.isEmpty should ===(false) - } - private def allUnreachable(r1: Reachability): Unit = { + private def allUnreachable(r1: Reachability): Unit = r1.allUnreachable.isEmpty should ===(false) - } - private def recordsFrom(r1: Reachability): Unit = { + private def recordsFrom(r1: Reachability): Unit = r1.allObservers.foreach { o => r1.recordsFrom(o) should not be be(null) } - } s"Reachability of size $nodesSize" must { diff --git a/cluster/src/test/scala/org/apache/pekko/cluster/VectorClockPerfSpec.scala b/cluster/src/test/scala/org/apache/pekko/cluster/VectorClockPerfSpec.scala index 350aacb33fe..7410b90a68c 100644 --- a/cluster/src/test/scala/org/apache/pekko/cluster/VectorClockPerfSpec.scala +++ b/cluster/src/test/scala/org/apache/pekko/cluster/VectorClockPerfSpec.scala @@ -59,18 +59,15 @@ class VectorClockPerfSpec extends AnyWordSpec with Matchers { def checkThunkFor(vc1: VectorClock, vc2: VectorClock, thunk: (VectorClock, VectorClock) => Unit, times: Int): Unit = { val vcc1 = copyVectorClock(vc1) val vcc2 = copyVectorClock(vc2) - for (_ <- 1 to times) { + for (_ <- 1 to times) thunk(vcc1, vcc2) - } } - def compareTo(order: Ordering)(vc1: VectorClock, vc2: VectorClock): Unit = { + def compareTo(order: Ordering)(vc1: VectorClock, vc2: VectorClock): Unit = vc1.compareTo(vc2) should ===(order) - } - def notEqual(vc1: VectorClock, vc2: VectorClock): Unit = { + def notEqual(vc1: VectorClock, vc2: VectorClock): Unit = vc1 == vc2 should ===(false) - } s"VectorClock comparisons of size $clockSize" must { diff --git a/cluster/src/test/scala/org/apache/pekko/cluster/protobuf/ClusterMessageSerializerSpec.scala b/cluster/src/test/scala/org/apache/pekko/cluster/protobuf/ClusterMessageSerializerSpec.scala index 7615de9585c..96cbd58e363 100644 --- a/cluster/src/test/scala/org/apache/pekko/cluster/protobuf/ClusterMessageSerializerSpec.scala +++ b/cluster/src/test/scala/org/apache/pekko/cluster/protobuf/ClusterMessageSerializerSpec.scala @@ -38,7 +38,7 @@ class ClusterMessageSerializerSpec extends PekkoSpec("pekko.actor.provider = clu serializer.fromBinary(blob, manifest).asInstanceOf[T] } - def checkSerialization(obj: AnyRef): Unit = { + def checkSerialization(obj: AnyRef): Unit = (obj, roundtrip(obj)) match { case (env: GossipEnvelope, env2: GossipEnvelope) => env2.from should ===(env.from) @@ -47,14 +47,13 @@ class ClusterMessageSerializerSpec extends PekkoSpec("pekko.actor.provider = clu case (_, ref) => ref should ===(obj) } - } private def roundtripWithManifest[T <: AnyRef](obj: T, manifest: String): T = { val blob = serializer.toBinary(obj) serializer.fromBinary(blob, manifest).asInstanceOf[T] } - private def checkDeserializationWithManifest(obj: AnyRef, deserializationManifest: String): Unit = { + private def checkDeserializationWithManifest(obj: AnyRef, deserializationManifest: String): Unit = (obj, roundtripWithManifest(obj, deserializationManifest)) match { case (env: GossipEnvelope, env2: GossipEnvelope) => env2.from should ===(env.from) @@ -67,7 +66,6 @@ class ClusterMessageSerializerSpec extends PekkoSpec("pekko.actor.provider = clu case (_, ref) => ref should ===(obj) } - } private def checkSameMember(m1: Member, m2: Member): Unit = { m1.uniqueAddress should ===(m2.uniqueAddress) diff --git a/cluster/src/test/scala/org/apache/pekko/cluster/sbr/SplitBrainResolverSpec.scala b/cluster/src/test/scala/org/apache/pekko/cluster/sbr/SplitBrainResolverSpec.scala index 93a1c5344d7..3b0873dd922 100644 --- a/cluster/src/test/scala/org/apache/pekko/cluster/sbr/SplitBrainResolverSpec.scala +++ b/cluster/src/test/scala/org/apache/pekko/cluster/sbr/SplitBrainResolverSpec.scala @@ -86,13 +86,12 @@ object SplitBrainResolverSpec { var downed = Set.empty[Address] - override def down(node: UniqueAddress, decision: DowningStrategy.Decision): Unit = { + override def down(node: UniqueAddress, decision: DowningStrategy.Decision): Unit = if (leader && !downed(node.address)) { downed += node.address probe ! DownCalled(node.address) } else if (!leader) probe ! "down must only be done by leader" - } override def receive: Receive = ({ @@ -128,7 +127,7 @@ class SplitBrainResolverSpec private val testLeaseSettings = new LeaseSettings("pekko-sbr", "test", new TimeoutSettings(1.second, 2.minutes, 3.seconds), ConfigFactory.empty) - def createReachability(unreachability: Seq[(Member, Member)]): Reachability = { + def createReachability(unreachability: Seq[(Member, Member)]): Reachability = Reachability( unreachability.map { case (from, to) => Reachability.Record(from.uniqueAddress, to.uniqueAddress, Reachability.Unreachable, 1) @@ -136,7 +135,6 @@ class SplitBrainResolverSpec unreachability.map { case (from, _) => from.uniqueAddress -> 1L }.toMap) - } def extSystem: ExtendedActorSystem = system.asInstanceOf[ExtendedActorSystem] @@ -165,10 +163,9 @@ class SplitBrainResolverSpec assertDowningSide(side3, members) } - def assertDowningSide(side: Set[Member], members: Set[Member]): Unit = { + def assertDowningSide(side: Set[Member], members: Set[Member]): Unit = if (side.nonEmpty) strategy(side).nodesToDown() should be(members.map(_.uniqueAddress)) - } def strategy(side: Set[Member]): DowningStrategy = { val others = side1 ++ side2 ++ side3 -- side diff --git a/cluster/src/test/scala/org/apache/pekko/cluster/testkit/AutoDown.scala b/cluster/src/test/scala/org/apache/pekko/cluster/testkit/AutoDown.scala index 80a25fea996..ea645f0a0d4 100644 --- a/cluster/src/test/scala/org/apache/pekko/cluster/testkit/AutoDown.scala +++ b/cluster/src/test/scala/org/apache/pekko/cluster/testkit/AutoDown.scala @@ -164,9 +164,8 @@ private[cluster] abstract class AutoDownBase(autoDownUnreachableAfter: FiniteDur var pendingUnreachable: Set[UniqueAddress] = Set.empty var leader = false - override def postStop(): Unit = { - scheduledUnreachable.values.foreach { _.cancel() } - } + override def postStop(): Unit = + scheduledUnreachable.values.foreach(_.cancel()) def receive = { case state: CurrentClusterState => @@ -198,16 +197,15 @@ private[cluster] abstract class AutoDownBase(autoDownUnreachableAfter: FiniteDur if (!skipMemberStatus(m.status) && !scheduledUnreachable.contains(m.uniqueAddress)) scheduleUnreachable(m.uniqueAddress) - def scheduleUnreachable(node: UniqueAddress): Unit = { + def scheduleUnreachable(node: UniqueAddress): Unit = if (autoDownUnreachableAfter == Duration.Zero) { downOrAddPending(node) } else { val task = scheduler.scheduleOnce(autoDownUnreachableAfter, self, UnreachableTimeout(node)) scheduledUnreachable += (node -> task) } - } - def downOrAddPending(node: UniqueAddress): Unit = { + def downOrAddPending(node: UniqueAddress): Unit = if (leader) { down(node.address) } else { @@ -215,10 +213,9 @@ private[cluster] abstract class AutoDownBase(autoDownUnreachableAfter: FiniteDur // a new leader must pick up these pendingUnreachable += node } - } def remove(node: UniqueAddress): Unit = { - scheduledUnreachable.get(node).foreach { _.cancel() } + scheduledUnreachable.get(node).foreach(_.cancel()) scheduledUnreachable -= node pendingUnreachable -= node } diff --git a/cluster/src/test/scala/org/apache/pekko/cluster/testkit/AutoDownSpec.scala b/cluster/src/test/scala/org/apache/pekko/cluster/testkit/AutoDownSpec.scala index d8fd36f4241..98d31afcf3f 100644 --- a/cluster/src/test/scala/org/apache/pekko/cluster/testkit/AutoDownSpec.scala +++ b/cluster/src/test/scala/org/apache/pekko/cluster/testkit/AutoDownSpec.scala @@ -37,12 +37,11 @@ object AutoDownSpec { override def selfAddress = memberA.address override def scheduler: Scheduler = context.system.scheduler - override def down(node: Address): Unit = { + override def down(node: Address): Unit = if (leader) probe ! DownCalled(node) else probe ! "down must only be done by leader" - } } diff --git a/coordination/src/main/scala/org/apache/pekko/coordination/lease/LeaseSettings.scala b/coordination/src/main/scala/org/apache/pekko/coordination/lease/LeaseSettings.scala index 9ad86826aa6..fbcf894c183 100644 --- a/coordination/src/main/scala/org/apache/pekko/coordination/lease/LeaseSettings.scala +++ b/coordination/src/main/scala/org/apache/pekko/coordination/lease/LeaseSettings.scala @@ -16,9 +16,8 @@ package org.apache.pekko.coordination.lease import com.typesafe.config.Config object LeaseSettings { - def apply(config: Config, leaseName: String, ownerName: String): LeaseSettings = { + def apply(config: Config, leaseName: String, ownerName: String): LeaseSettings = new LeaseSettings(leaseName, ownerName, TimeoutSettings(config), config) - } } final class LeaseSettings( diff --git a/coordination/src/main/scala/org/apache/pekko/coordination/lease/TimeoutSettings.scala b/coordination/src/main/scala/org/apache/pekko/coordination/lease/TimeoutSettings.scala index fe21bb6a5dc..4741da3af65 100644 --- a/coordination/src/main/scala/org/apache/pekko/coordination/lease/TimeoutSettings.scala +++ b/coordination/src/main/scala/org/apache/pekko/coordination/lease/TimeoutSettings.scala @@ -56,40 +56,33 @@ final class TimeoutSettings( /** * Java API */ - def withHeartbeatInterval(heartbeatInterval: java.time.Duration): TimeoutSettings = { + def withHeartbeatInterval(heartbeatInterval: java.time.Duration): TimeoutSettings = copy(heartbeatInterval = heartbeatInterval.asScala) - } /** * Java API */ - def withHeartbeatTimeout(heartbeatTimeout: java.time.Duration): TimeoutSettings = { + def withHeartbeatTimeout(heartbeatTimeout: java.time.Duration): TimeoutSettings = copy(heartbeatTimeout = heartbeatTimeout.asScala) - } /** * Java API */ - def withOperationTimeout(operationTimeout: java.time.Duration): TimeoutSettings = { + def withOperationTimeout(operationTimeout: java.time.Duration): TimeoutSettings = copy(operationTimeout = operationTimeout.asScala) - } - def withHeartbeatInterval(heartbeatInterval: FiniteDuration): TimeoutSettings = { + def withHeartbeatInterval(heartbeatInterval: FiniteDuration): TimeoutSettings = copy(heartbeatInterval = heartbeatInterval) - } - def withHeartbeatTimeout(heartbeatTimeout: FiniteDuration): TimeoutSettings = { + def withHeartbeatTimeout(heartbeatTimeout: FiniteDuration): TimeoutSettings = copy(heartbeatTimeout = heartbeatTimeout) - } - def withOperationTimeout(operationTimeout: FiniteDuration): TimeoutSettings = { + def withOperationTimeout(operationTimeout: FiniteDuration): TimeoutSettings = copy(operationTimeout = operationTimeout) - } private def copy( heartbeatInterval: FiniteDuration = heartbeatInterval, heartbeatTimeout: FiniteDuration = heartbeatTimeout, - operationTimeout: FiniteDuration = operationTimeout): TimeoutSettings = { + operationTimeout: FiniteDuration = operationTimeout): TimeoutSettings = new TimeoutSettings(heartbeatInterval, heartbeatTimeout, operationTimeout) - } override def toString = s"TimeoutSettings($heartbeatInterval, $heartbeatTimeout, $operationTimeout)" } diff --git a/coordination/src/main/scala/org/apache/pekko/coordination/lease/internal/LeaseAdapter.scala b/coordination/src/main/scala/org/apache/pekko/coordination/lease/internal/LeaseAdapter.scala index a7af9fc6764..ce62644d822 100644 --- a/coordination/src/main/scala/org/apache/pekko/coordination/lease/internal/LeaseAdapter.scala +++ b/coordination/src/main/scala/org/apache/pekko/coordination/lease/internal/LeaseAdapter.scala @@ -36,9 +36,8 @@ final private[pekko] class LeaseAdapter(delegate: ScalaLease)(implicit val ec: E override def acquire(): CompletionStage[java.lang.Boolean] = delegate.acquire().map(Boolean.box).asJava - override def acquire(leaseLostCallback: Consumer[Optional[Throwable]]): CompletionStage[java.lang.Boolean] = { + override def acquire(leaseLostCallback: Consumer[Optional[Throwable]]): CompletionStage[java.lang.Boolean] = delegate.acquire(o => leaseLostCallback.accept(o.toJava)).map(Boolean.box).asJava - } override def release(): CompletionStage[java.lang.Boolean] = delegate.release().map(Boolean.box).asJava override def checkLease(): Boolean = delegate.checkLease() diff --git a/coordination/src/main/scala/org/apache/pekko/coordination/lease/scaladsl/LeaseProvider.scala b/coordination/src/main/scala/org/apache/pekko/coordination/lease/scaladsl/LeaseProvider.scala index 3e2ef3eb139..ba4bc34e4b1 100644 --- a/coordination/src/main/scala/org/apache/pekko/coordination/lease/scaladsl/LeaseProvider.scala +++ b/coordination/src/main/scala/org/apache/pekko/coordination/lease/scaladsl/LeaseProvider.scala @@ -58,9 +58,8 @@ final class LeaseProvider(system: ExtendedActorSystem) extends Extension { * @param configPath the path of configuration for the lease * @param ownerName the owner that will `acquire` the lease, e.g. hostname and port of the ActorSystem */ - def getLease(leaseName: String, configPath: String, ownerName: String): Lease = { + def getLease(leaseName: String, configPath: String, ownerName: String): Lease = internalGetLease(leaseName, configPath, ownerName) - } private[pekko] def internalGetLease(leaseName: String, configPath: String, ownerName: String): Lease = { val leaseKey = LeaseKey(leaseName, configPath, ownerName) diff --git a/coordination/src/test/scala/org/apache/pekko/coordination/lease/TestLeaseActor.scala b/coordination/src/test/scala/org/apache/pekko/coordination/lease/TestLeaseActor.scala index 9eda263a8c4..5c942988057 100644 --- a/coordination/src/test/scala/org/apache/pekko/coordination/lease/TestLeaseActor.scala +++ b/coordination/src/test/scala/org/apache/pekko/coordination/lease/TestLeaseActor.scala @@ -116,13 +116,11 @@ class TestLeaseActorClient(settings: LeaseSettings, system: ExtendedActorSystem) private implicit val timeout: Timeout = Timeout(100.seconds) - override def acquire(): Future[Boolean] = { + override def acquire(): Future[Boolean] = (leaseActor ? Acquire(settings.ownerName)).mapTo[Boolean] - } - override def release(): Future[Boolean] = { + override def release(): Future[Boolean] = (leaseActor ? Release(settings.ownerName)).mapTo[Boolean] - } override def checkLease(): Boolean = false diff --git a/discovery/src/main/scala/org/apache/pekko/discovery/Discovery.scala b/discovery/src/main/scala/org/apache/pekko/discovery/Discovery.scala index bbe48f59b3b..9c70d6ff13a 100644 --- a/discovery/src/main/scala/org/apache/pekko/discovery/Discovery.scala +++ b/discovery/src/main/scala/org/apache/pekko/discovery/Discovery.scala @@ -55,9 +55,8 @@ final class Discovery(implicit system: ExtendedActorSystem) extends Extension { * The `ServiceDiscovery` instance for a given `method` will be created * once and subsequent requests for the same `method` will return the same instance. */ - def loadServiceDiscovery(method: String): ServiceDiscovery = { + def loadServiceDiscovery(method: String): ServiceDiscovery = implementations.computeIfAbsent(method, factory) - } /** * INTERNAL API @@ -67,15 +66,14 @@ final class Discovery(implicit system: ExtendedActorSystem) extends Extension { val config = system.settings.config val dynamic = system.dynamicAccess - def classNameFromConfig(path: String): String = { + def classNameFromConfig(path: String): String = if (config.hasPath(path)) config.getString(path) else throw new IllegalArgumentException( s"$path must point to a FQN of a `org.apache.pekko.discovery.ServiceDiscovery` implementation") - } - def create(clazzName: String): Try[ServiceDiscovery] = { + def create(clazzName: String): Try[ServiceDiscovery] = dynamic .createInstanceFor[ServiceDiscovery](clazzName, (classOf[ExtendedActorSystem] -> system) :: Nil) .recoverWith { @@ -86,7 +84,6 @@ final class Discovery(implicit system: ExtendedActorSystem) extends Extension { case _: ClassNotFoundException | _: NoSuchMethodException => dynamic.createInstanceFor[ServiceDiscovery](clazzName, Nil) } - } val configName = s"pekko.discovery.$method.class" val instanceTry = create(classNameFromConfig(configName)) diff --git a/discovery/src/main/scala/org/apache/pekko/discovery/aggregate/AggregateServiceDiscovery.scala b/discovery/src/main/scala/org/apache/pekko/discovery/aggregate/AggregateServiceDiscovery.scala index d6d293a9a3c..6ca718f6965 100644 --- a/discovery/src/main/scala/org/apache/pekko/discovery/aggregate/AggregateServiceDiscovery.scala +++ b/discovery/src/main/scala/org/apache/pekko/discovery/aggregate/AggregateServiceDiscovery.scala @@ -75,7 +75,7 @@ private[pekko] final class AggregateServiceDiscovery(system: ExtendedActorSystem override def lookup(lookup: Lookup, resolveTimeout: FiniteDuration): Future[Resolved] = resolve(methods, lookup, resolveTimeout) - private def resolve(sds: Methods, query: Lookup, resolveTimeout: FiniteDuration): Future[Resolved] = { + private def resolve(sds: Methods, query: Lookup, resolveTimeout: FiniteDuration): Future[Resolved] = sds match { case (method, next) :: Nil => log.debug("Looking up [{}] with [{}]", query, method) @@ -101,5 +101,4 @@ private[pekko] final class AggregateServiceDiscovery(system: ExtendedActorSystem // this is checked in `discoveryMethods`, but silence compiler warning throw new IllegalStateException("At least one discovery method should be specified") } - } } diff --git a/discovery/src/main/scala/org/apache/pekko/discovery/config/ConfigServiceDiscovery.scala b/discovery/src/main/scala/org/apache/pekko/discovery/config/ConfigServiceDiscovery.scala index b4ccd90c307..0bdd13d50db 100644 --- a/discovery/src/main/scala/org/apache/pekko/discovery/config/ConfigServiceDiscovery.scala +++ b/discovery/src/main/scala/org/apache/pekko/discovery/config/ConfigServiceDiscovery.scala @@ -67,8 +67,7 @@ private[pekko] class ConfigServiceDiscovery(system: ExtendedActorSystem) extends log.debug("Config discovery serving: {}", resolvedServices) - override def lookup(lookup: Lookup, resolveTimeout: FiniteDuration): Future[Resolved] = { + override def lookup(lookup: Lookup, resolveTimeout: FiniteDuration): Future[Resolved] = Future.successful(resolvedServices.getOrElse(lookup.serviceName, Resolved(lookup.serviceName, Nil))) - } } diff --git a/discovery/src/main/scala/org/apache/pekko/discovery/dns/DnsServiceDiscovery.scala b/discovery/src/main/scala/org/apache/pekko/discovery/dns/DnsServiceDiscovery.scala index 77823417cbb..44acc0526d6 100644 --- a/discovery/src/main/scala/org/apache/pekko/discovery/dns/DnsServiceDiscovery.scala +++ b/discovery/src/main/scala/org/apache/pekko/discovery/dns/DnsServiceDiscovery.scala @@ -85,7 +85,7 @@ private[pekko] class DnsServiceDiscovery(system: ExtendedActorSystem) extends Se private val dns = initializeDns() // exposed for testing - private[dns] def initializeDns(): ActorRef = { + private[dns] def initializeDns(): ActorRef = if (system.settings.config.getString("pekko.io.dns.resolver") == "async-dns") { log.debug("using system resolver as it is set to async-dns") IO(Dns)(system) @@ -93,7 +93,6 @@ private[pekko] class DnsServiceDiscovery(system: ExtendedActorSystem) extends Se log.debug("system resolver is not async-dns. Loading isolated resolver") Dns(system).loadAsyncDns("SD-DNS") } - } // updated from ask AsyncDnsManager.GetCache, but doesn't have to volatile since will still work when unset // (eventually visible) @@ -113,19 +112,18 @@ private[pekko] class DnsServiceDiscovery(system: ExtendedActorSystem) extends Se private def cleanIpString(ipString: String): String = if (ipString.startsWith("/")) ipString.tail else ipString - override def lookup(lookup: Lookup, resolveTimeout: FiniteDuration): Future[Resolved] = { + override def lookup(lookup: Lookup, resolveTimeout: FiniteDuration): Future[Resolved] = if (lookup.portName.isDefined && lookup.protocol.isDefined) lookupSrv(lookup, resolveTimeout) else lookupIp(lookup, resolveTimeout) - } private def lookupSrv(lookup: Lookup, resolveTimeout: FiniteDuration) = { val srvRequest = s"_${lookup.portName.get}._${lookup.protocol.get}.${lookup.serviceName}" log.debug("Lookup [{}] translated to SRV query [{}] as contains portName and protocol", lookup, srvRequest) val mode = Srv - def askResolve(): Future[Resolved] = { + def askResolve(): Future[Resolved] = dns .ask(DnsProtocol.Resolve(srvRequest, mode))(resolveTimeout) .map { @@ -137,7 +135,6 @@ private[pekko] class DnsServiceDiscovery(system: ExtendedActorSystem) extends Se Resolved(srvRequest, Nil) } .recoverWith(convertToTimeout(resolveTimeout)) - } asyncDnsCache match { case OptionVal.Some(cache) => @@ -172,7 +169,7 @@ private[pekko] class DnsServiceDiscovery(system: ExtendedActorSystem) extends Se Resolved(lookup.serviceName, addresses) } - def askResolve(): Future[Resolved] = { + def askResolve(): Future[Resolved] = dns .ask(DnsProtocol.Resolve(lookup.serviceName, mode))(resolveTimeout) .map { @@ -184,7 +181,6 @@ private[pekko] class DnsServiceDiscovery(system: ExtendedActorSystem) extends Se Resolved(lookup.serviceName, Nil) } .recoverWith(convertToTimeout(resolveTimeout)) - } asyncDnsCache match { case OptionVal.Some(cache) => diff --git a/discovery/src/test/scala/org/apache/pekko/discovery/DiscoveryConfigurationSpec.scala b/discovery/src/test/scala/org/apache/pekko/discovery/DiscoveryConfigurationSpec.scala index 1e0224248bb..6fdd8d74f87 100644 --- a/discovery/src/test/scala/org/apache/pekko/discovery/DiscoveryConfigurationSpec.scala +++ b/discovery/src/test/scala/org/apache/pekko/discovery/DiscoveryConfigurationSpec.scala @@ -123,9 +123,9 @@ class DiscoveryConfigurationSpec extends AnyWordSpec with Matchers { } """).withFallback(ConfigFactory.load())) - try { + try an[DiscoveryException] should be thrownBy Discovery(sys).discovery - } finally TestKit.shutdownActorSystem(sys) + finally TestKit.shutdownActorSystem(sys) } "throw an illegal argument exception for not existing method" in { @@ -139,9 +139,9 @@ class DiscoveryConfigurationSpec extends AnyWordSpec with Matchers { } """).withFallback(ConfigFactory.load())) - try { + try an[IllegalArgumentException] should be thrownBy Discovery(sys).discovery - } finally TestKit.shutdownActorSystem(sys) + finally TestKit.shutdownActorSystem(sys) } } @@ -159,7 +159,6 @@ class DiscoveryException(message: String) extends Exception(message) class ExceptionThrowingDiscovery extends FakeTestDiscovery { bad() - def bad(): Unit = { + def bad(): Unit = throw new DiscoveryException("oh no") - } } diff --git a/discovery/src/test/scala/org/apache/pekko/discovery/aggregate/AggregateServiceDiscoverySpec.scala b/discovery/src/test/scala/org/apache/pekko/discovery/aggregate/AggregateServiceDiscoverySpec.scala index c89928d8852..0f891d407e4 100644 --- a/discovery/src/test/scala/org/apache/pekko/discovery/aggregate/AggregateServiceDiscoverySpec.scala +++ b/discovery/src/test/scala/org/apache/pekko/discovery/aggregate/AggregateServiceDiscoverySpec.scala @@ -32,7 +32,7 @@ import pekko.util.unused class StubbedServiceDiscovery(@unused system: ExtendedActorSystem) extends ServiceDiscovery { - override def lookup(query: Lookup, resolveTimeout: FiniteDuration): Future[Resolved] = { + override def lookup(query: Lookup, resolveTimeout: FiniteDuration): Future[Resolved] = if (query.serviceName == "stubbed") { Future.successful( Resolved( @@ -43,7 +43,6 @@ class StubbedServiceDiscovery(@unused system: ExtendedActorSystem) extends Servi } else { Future.successful(Resolved(query.serviceName, immutable.Seq.empty)) } - } } object AggregateServiceDiscoverySpec { @@ -94,9 +93,8 @@ class AggregateServiceDiscoverySpec with BeforeAndAfterAll with ScalaFutures { - override protected def afterAll(): Unit = { + override protected def afterAll(): Unit = TestKit.shutdownActorSystem(system) - } val discovery: ServiceDiscovery = Discovery(system).discovery diff --git a/discovery/src/test/scala/org/apache/pekko/discovery/config/ConfigServiceDiscoverySpec.scala b/discovery/src/test/scala/org/apache/pekko/discovery/config/ConfigServiceDiscoverySpec.scala index 5b2a4184445..95424a50dd5 100644 --- a/discovery/src/test/scala/org/apache/pekko/discovery/config/ConfigServiceDiscoverySpec.scala +++ b/discovery/src/test/scala/org/apache/pekko/discovery/config/ConfigServiceDiscoverySpec.scala @@ -65,9 +65,8 @@ class ConfigServiceDiscoverySpec with BeforeAndAfterAll with ScalaFutures { - override protected def afterAll(): Unit = { + override protected def afterAll(): Unit = TestKit.shutdownActorSystem(system) - } val discovery = Discovery(system).discovery diff --git a/discovery/src/test/scala/org/apache/pekko/discovery/dns/DnsDiscoverySpec.scala b/discovery/src/test/scala/org/apache/pekko/discovery/dns/DnsDiscoverySpec.scala index 01e82576584..31025c50cd5 100644 --- a/discovery/src/test/scala/org/apache/pekko/discovery/dns/DnsDiscoverySpec.scala +++ b/discovery/src/test/scala/org/apache/pekko/discovery/dns/DnsDiscoverySpec.scala @@ -142,11 +142,9 @@ class DnsDiscoverySpec extends DockerBindDnsService(DnsDiscoverySpec.config) { } - override def afterTermination(): Unit = { - try { + override def afterTermination(): Unit = + try TestKit.shutdownActorSystem(systemWithAsyncDnsAsResolver) - } finally { + finally super.afterTermination() - } - } } diff --git a/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/DeltaPropagationSelector.scala b/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/DeltaPropagationSelector.scala index c6f6c68fe62..702c3281ec8 100644 --- a/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/DeltaPropagationSelector.scala +++ b/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/DeltaPropagationSelector.scala @@ -73,10 +73,9 @@ private[pekko] trait DeltaPropagationSelector { deltaSentToNode -= key } - def nodesSliceSize(allNodesSize: Int): Int = { + def nodesSliceSize(allNodesSize: Int): Int = // 2 - 10 nodes math.min(math.max((allNodesSize / gossipIntervalDivisor) + 1, 2), math.min(allNodesSize, 10)) - } def collectPropagations(): Map[UniqueAddress, DeltaPropagation] = { _propagationCount += 1 @@ -88,7 +87,7 @@ private[pekko] trait DeltaPropagationSelector { // Normally the delta is propagated to all nodes within the gossip tick, so that // full state gossip is not needed. val sliceSize = nodesSliceSize(all.size) - val slice = { + val slice = if (all.size <= sliceSize) all else { @@ -97,7 +96,6 @@ private[pekko] trait DeltaPropagationSelector { if (first.size == sliceSize) first else first ++ all.take(sliceSize - first.size) } - } deltaNodeRoundRobinCounter += sliceSize var result = Map.empty[UniqueAddress, DeltaPropagation] @@ -163,14 +161,13 @@ private[pekko] trait DeltaPropagationSelector { case ntrs => ntrs } - def hasDeltaEntries(key: KeyId): Boolean = { + def hasDeltaEntries(key: KeyId): Boolean = deltaEntries.get(key) match { case Some(m) => m.nonEmpty case None => false } - } - private def findSmallestVersionPropagatedToAllNodes(key: KeyId, all: Vector[UniqueAddress]): Long = { + private def findSmallestVersionPropagatedToAllNodes(key: KeyId, all: Vector[UniqueAddress]): Long = deltaSentToNode.get(key) match { case None => 0L case Some(deltaSentToNodeForKey) => @@ -178,7 +175,6 @@ private[pekko] trait DeltaPropagationSelector { else if (all.exists(node => !deltaSentToNodeForKey.contains(node))) 0L else deltaSentToNodeForKey.valuesIterator.min } - } def cleanupDeltaEntries(): Unit = { val all = allNodes @@ -198,10 +194,9 @@ private[pekko] trait DeltaPropagationSelector { } } - def cleanupRemovedNode(address: UniqueAddress): Unit = { + def cleanupRemovedNode(address: UniqueAddress): Unit = deltaSentToNode = deltaSentToNode.map { case (key, deltaSentToNodeForKey) => key -> (deltaSentToNodeForKey - address) } - } } diff --git a/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/DurableStore.scala b/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/DurableStore.scala index 17489eb7ded..e30d28c724f 100644 --- a/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/DurableStore.scala +++ b/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/DurableStore.scala @@ -230,15 +230,13 @@ final class LmdbDurableStore(config: Config) extends Actor with ActorLogging { if (log.isDebugEnabled) log.debug("load all of [{}] entries took [{} ms]", n, TimeUnit.NANOSECONDS.toMillis(System.nanoTime - t0)) context.become(active) - } finally { + } finally Try(iter.close()) - } } catch { case NonFatal(e) => throw new LoadFailed("failed to load durable distributed-data", e) - } finally { + } finally Try(tx.close()) - } } else { // no files to load sender() ! LoadAllCompleted @@ -276,7 +274,7 @@ final class LmdbDurableStore(config: Config) extends Actor with ActorLogging { writeBehind() } - def dbPut(tx: OptionVal[Txn[ByteBuffer]], key: KeyId, data: DurableDataEnvelope): Unit = { + def dbPut(tx: OptionVal[Txn[ByteBuffer]], key: KeyId, data: DurableDataEnvelope): Unit = try { val value = serializer.toBinary(data) ensureValueBufferSize(value.length) @@ -292,9 +290,8 @@ final class LmdbDurableStore(config: Config) extends Actor with ActorLogging { l.keyBuffer.clear() l.valueBuffer.clear() } - } - def writeBehind(): Unit = { + def writeBehind(): Unit = if (!pending.isEmpty()) { val t0 = System.nanoTime() val tx = lmdb().env.txnWrite() @@ -315,10 +312,8 @@ final class LmdbDurableStore(config: Config) extends Actor with ActorLogging { import pekko.util.ccompat.JavaConverters._ log.error(e, "failed to store [{}]", pending.keySet.asScala.mkString(",")) tx.abort() - } finally { + } finally pending.clear() - } } - } } diff --git a/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/ORMap.scala b/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/ORMap.scala index 70b66681bd1..a613e726849 100644 --- a/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/ORMap.scala +++ b/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/ORMap.scala @@ -535,19 +535,17 @@ final class ORMap[A, B <: ReplicatedData] private[pekko] ( deltaOp } - override def modifiedByNodes: Set[UniqueAddress] = { + override def modifiedByNodes: Set[UniqueAddress] = keys.modifiedByNodes.union(values.foldLeft(Set.empty[UniqueAddress]) { case (acc, (_, data: RemovedNodePruning)) => acc.union(data.modifiedByNodes) case (acc, _) => acc }) - } - override def needPruningFrom(removedNode: UniqueAddress): Boolean = { + override def needPruningFrom(removedNode: UniqueAddress): Boolean = keys.needPruningFrom(removedNode) || values.exists { case (_, data: RemovedNodePruning) => data.needPruningFrom(removedNode) case _ => false } - } override def prune(removedNode: UniqueAddress, collapseInto: UniqueAddress): ORMap[A, B] = { val prunedKeys = keys.prune(removedNode, collapseInto) diff --git a/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/ORMultiMap.scala b/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/ORMultiMap.scala index 36c3eb4ef51..fcc0b65efd8 100644 --- a/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/ORMultiMap.scala +++ b/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/ORMultiMap.scala @@ -224,7 +224,7 @@ final class ORMultiMap[A, B] private[pekko] ( /** * INTERNAL API */ - @InternalApi private[pekko] def remove(node: UniqueAddress, key: A): ORMultiMap[A, B] = { + @InternalApi private[pekko] def remove(node: UniqueAddress, key: A): ORMultiMap[A, B] = if (withValueDeltas) { val u = underlying.updated(node, key, ORSet.empty[B], valueDeltas = true) { existing => existing.clear() @@ -233,7 +233,6 @@ final class ORMultiMap[A, B] private[pekko] ( } else { new ORMultiMap(underlying.remove(node, key), withValueDeltas) } - } /** * Add an element to a set associated with a key. If there is no existing set then one will be initialised. diff --git a/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/ORSet.scala b/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/ORSet.scala index 1fc533144ab..53f3ad5057e 100644 --- a/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/ORSet.scala +++ b/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/ORSet.scala @@ -93,13 +93,12 @@ object ORSet { case DeltaGroup(ops) => DeltaGroup(this +: ops) } - private def concatElementsMap(thatMap: Map[A, Dot]): Map[A, Dot] = { + private def concatElementsMap(thatMap: Map[A, Dot]): Map[A, Dot] = if (thatMap.size == 1) { val head = thatMap.head underlying.elementsMap.updated(head._1, head._2) } else underlying.elementsMap ++ thatMap - } } /** INTERNAL API */ @@ -195,7 +194,7 @@ object ORSet { rhs: ORSet[A]): Map[A, ORSet.Dot] = mergeCommonKeys(commonKeys.iterator, lhs, rhs) - private def mergeCommonKeys[A](commonKeys: Iterator[A], lhs: ORSet[A], rhs: ORSet[A]): Map[A, ORSet.Dot] = { + private def mergeCommonKeys[A](commonKeys: Iterator[A], lhs: ORSet[A], rhs: ORSet[A]): Map[A, ORSet.Dot] = commonKeys.foldLeft(Map.empty[A, ORSet.Dot]) { case (acc, k) => val lhsDots = lhs.elementsMap(k) @@ -255,7 +254,6 @@ object ORSet { else acc.updated(k, merged) } } - } /** * INTERNAL API @@ -272,7 +270,7 @@ object ORSet { keys: Iterator[A], elementsMap: Map[A, ORSet.Dot], vvector: VersionVector, - accumulator: Map[A, ORSet.Dot]): Map[A, ORSet.Dot] = { + accumulator: Map[A, ORSet.Dot]): Map[A, ORSet.Dot] = keys.foldLeft(accumulator) { case (acc, k) => val dots = elementsMap(k) @@ -284,7 +282,6 @@ object ORSet { acc.updated(k, newDots) } } - } } /** @@ -451,11 +448,10 @@ final class ORSet[A] private[pekko] ( * and the other Set version vector dominates those dots, then we need to drop those dots. * Keep only common dots, and dots that are not dominated by the other sides version vector */ - override def merge(that: ORSet[A]): ORSet[A] = { + override def merge(that: ORSet[A]): ORSet[A] = if ((this eq that) || that.isAncestorOf(this)) this.clearAncestor() else if (this.isAncestorOf(that)) that.clearAncestor() else dryMerge(that, addDeltaOp = false) - } // share merge impl between full state merge and AddDeltaOp merge private def dryMerge(that: ORSet[A], addDeltaOp: Boolean): ORSet[A] = { @@ -480,7 +476,7 @@ final class ORSet[A] private[pekko] ( new ORSet(entries, mergedVvector) } - override def mergeDelta(thatDelta: ORSet.DeltaOp): ORSet[A] = { + override def mergeDelta(thatDelta: ORSet.DeltaOp): ORSet[A] = thatDelta match { case d: ORSet.AddDeltaOp[_] => dryMerge(d.asInstanceOf[ORSet.AddDeltaOp[A]].underlying, addDeltaOp = true) case d: ORSet.RemoveDeltaOp[_] => mergeRemoveDelta(d.asInstanceOf[ORSet.RemoveDeltaOp[A]]) @@ -497,7 +493,6 @@ final class ORSet[A] private[pekko] ( throw new IllegalArgumentException("ORSet.DeltaGroup should not be nested") } } - } private def mergeRemoveDelta(thatDelta: ORSet.RemoveDeltaOp[A]): ORSet[A] = { val that = thatDelta.underlying diff --git a/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/PNCounterMap.scala b/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/PNCounterMap.scala index b4357f47bdb..b05a55a971e 100644 --- a/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/PNCounterMap.scala +++ b/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/PNCounterMap.scala @@ -146,9 +146,8 @@ final class PNCounterMap[A] private[pekko] (private[pekko] val underlying: ORMap /** * INTERNAL API */ - @InternalApi private[pekko] def decrement(node: UniqueAddress, key: A, delta: Long): PNCounterMap[A] = { + @InternalApi private[pekko] def decrement(node: UniqueAddress, key: A, delta: Long): PNCounterMap[A] = new PNCounterMap(underlying.updated(node, key, PNCounter())(_.decrement(node, delta))) - } /** * Removes an entry from the map. diff --git a/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/PayloadSizeAggregator.scala b/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/PayloadSizeAggregator.scala index f548e45272c..b998a44eacd 100644 --- a/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/PayloadSizeAggregator.scala +++ b/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/PayloadSizeAggregator.scala @@ -30,12 +30,12 @@ import pekko.event.LoggingAdapter private val warnSizeExceeding = maxFrameSize * 3 / 4 private var maxPayloadBytes: Map[String, Int] = Map.empty - def updatePayloadSize(key: KeyId, size: Int): Unit = { + def updatePayloadSize(key: KeyId, size: Int): Unit = if (size > 0) { // deleted has size 0 // 10% threshold until next log def newMax = (size * 1.1).toInt - def logSize(): Unit = { + def logSize(): Unit = if (size >= warnSizeExceeding) log.warning( "Distributed data size for [{}] is [{}] bytes. Close to max remote message payload size.", @@ -43,7 +43,6 @@ import pekko.event.LoggingAdapter size) else log.info("Distributed data size for [{}] is [{}] bytes.", key, size) - } maxPayloadBytes.get(key) match { case Some(max) => @@ -58,11 +57,9 @@ import pekko.event.LoggingAdapter logSize() } } - } - def getMaxSize(key: KeyId): Int = { + def getMaxSize(key: KeyId): Int = maxPayloadBytes.getOrElse(key, 0) - } def remove(key: KeyId): Unit = maxPayloadBytes -= key diff --git a/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/PruningState.scala b/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/PruningState.scala index 40a849164a2..bf91023c8e4 100644 --- a/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/PruningState.scala +++ b/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/PruningState.scala @@ -25,10 +25,9 @@ import pekko.util.unused */ @InternalApi private[pekko] object PruningState { final case class PruningInitialized(owner: UniqueAddress, seen: Set[Address]) extends PruningState { - override def addSeen(node: Address): PruningState = { + override def addSeen(node: Address): PruningState = if (seen(node) || owner.address == node) this else copy(seen = seen + node) - } def estimatedSize: Int = EstimatedSize.UniqueAddress + EstimatedSize.Address * seen.size } final case class PruningPerformed(obsoleteTime: Long) extends PruningState { diff --git a/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/Replicator.scala b/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/Replicator.scala index 8b64e33ec66..9ea7a010859 100644 --- a/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/Replicator.scala +++ b/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/Replicator.scala @@ -93,10 +93,9 @@ object ReplicatorSettings { case _ => config.getDuration("pruning-interval", MILLISECONDS).millis } - val logDataSizeExceeding: Option[Int] = { + val logDataSizeExceeding: Option[Int] = if (toRootLowerCase(config.getString("log-data-size-exceeding")) == "off") None else Some(config.getBytes("log-data-size-exceeding").toInt) - } import pekko.util.ccompat.JavaConverters._ new ReplicatorSettings( @@ -997,13 +996,12 @@ object Replicator { case _ => false } - def initRemovedNodePruning(removed: UniqueAddress, owner: UniqueAddress): DataEnvelope = { + def initRemovedNodePruning(removed: UniqueAddress, owner: UniqueAddress): DataEnvelope = copy( pruning = pruning.updated(removed, PruningInitialized(owner, Set.empty)), deltaVersions = cleanedDeltaVersions(removed)) - } - def prune(from: UniqueAddress, pruningPerformed: PruningPerformed): DataEnvelope = { + def prune(from: UniqueAddress, pruningPerformed: PruningPerformed): DataEnvelope = data match { case dataWithRemovedNodePruning: RemovedNodePruning => require(pruning.contains(from)) @@ -1020,7 +1018,6 @@ object Replicator { case _ => this } - } def merge(other: DataEnvelope): DataEnvelope = if (other.data == DeletedData) DeletedEnvelope @@ -1035,7 +1032,7 @@ object Replicator { acc.updated(key, thisValue.merge(thatValue)) } } - val filteredMergedPruning = { + val filteredMergedPruning = if (mergedPruning.isEmpty) mergedPruning else { val currentTime = System.currentTimeMillis() @@ -1044,7 +1041,6 @@ object Replicator { case _ => true } } - } // cleanup and merge deltaVersions val removedNodes = filteredMergedPruning.keys @@ -1063,7 +1059,7 @@ object Replicator { pruning = filteredMergedPruning).merge(other.data) } - def merge(otherData: ReplicatedData): DataEnvelope = { + def merge(otherData: ReplicatedData): DataEnvelope = if (otherData == DeletedData) DeletedEnvelope else { val mergedData = @@ -1080,7 +1076,6 @@ object Replicator { s"Wrong type, existing type [${data.getClass.getName}], got [${mergedData.getClass.getName}]") copy(data = mergedData) } - } private def cleaned(c: ReplicatedData, p: Map[UniqueAddress, PruningState]): ReplicatedData = p.foldLeft(c) { case (c: RemovedNodePruning, (removed, _: PruningPerformed)) => @@ -1100,9 +1095,8 @@ object Replicator { else this } - def estimatedSizeWithoutData: Int = { + def estimatedSizeWithoutData: Int = deltaVersions.estimatedSize + pruning.valuesIterator.map(_.estimatedSize + EstimatedSize.UniqueAddress).sum - } } val DeletedEnvelope = DataEnvelope(DeletedData) @@ -1425,14 +1419,13 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog val deltaPropagationSelector = new DeltaPropagationSelector { override val gossipIntervalDivisor = 5 - override def allNodes: Vector[UniqueAddress] = { + override def allNodes: Vector[UniqueAddress] = // Replicator.allNodes is sorted Replicator.this.allNodes.diff(unreachable).toVector - } override def maxDeltaSize: Int = settings.maxDeltaSize - override def createDeltaPropagation(deltas: Map[KeyId, (ReplicatedData, Long, Long)]): DeltaPropagation = { + override def createDeltaPropagation(deltas: Map[KeyId, (ReplicatedData, Long, Long)]): DeltaPropagation = // Important to include the pruning state in the deltas. For example if the delta is based // on an entry that has been pruned but that has not yet been performed on the target node. DeltaPropagation( @@ -1445,7 +1438,6 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog case None => key -> Delta(DataEnvelope(d), fromSeqNr, toSeqNr) } }.toMap) - } } val deltaPropagationTask: Option[Cancellable] = if (deltaCrdtEnabled) { @@ -1515,7 +1507,7 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog // messages after loading durable data. var replyTo: ActorRef = null - private def nodesForReadWrite(excludeExiting: Boolean): Vector[UniqueAddress] = { + private def nodesForReadWrite(excludeExiting: Boolean): Vector[UniqueAddress] = if (excludeExiting && exitingNodes.nonEmpty) { if (settings.preferOldest) membersByAge.iterator.collect { case m if !exitingNodes.contains(m.uniqueAddress) => m.uniqueAddress @@ -1525,15 +1517,13 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog if (settings.preferOldest) membersByAge.iterator.map(_.uniqueAddress).toVector else nodes.toVector } - } override protected[pekko] def aroundReceive(rcv: Actor.Receive, msg: Any): Unit = { replyTo = sender() - try { + try super.aroundReceive(rcv, msg) - } finally { + finally replyTo = null - } } override def preStart(): Unit = { @@ -1730,9 +1720,8 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog case _ => false } - def receiveRead(key: KeyId): Unit = { + def receiveRead(key: KeyId): Unit = replyTo ! ReadResult(getData(key)) - } def isLocalSender(): Boolean = !replyTo.path.address.hasGlobalScope @@ -1743,12 +1732,11 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog req: Option[Any]): Unit = { val localValue = getData(key.id) - def deltaOrPlaceholder(d: DeltaReplicatedData): Option[ReplicatedDelta] = { + def deltaOrPlaceholder(d: DeltaReplicatedData): Option[ReplicatedDelta] = d.delta match { case s @ Some(_) => s case None => Some(NoDeltaPlaceholder) } - } Try { localValue match { @@ -1853,7 +1841,7 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog def receiveWrite(key: KeyId, envelope: DataEnvelope): Unit = writeAndStore(key, envelope, reply = true) - def writeAndStore(key: KeyId, writeEnvelope: DataEnvelope, reply: Boolean): Unit = { + def writeAndStore(key: KeyId, writeEnvelope: DataEnvelope, reply: Boolean): Unit = write(key, writeEnvelope) match { case Some(newEnvelope) => if (isDurable(key)) { @@ -1865,9 +1853,8 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog if (reply) replyTo ! WriteNack } - } - def write(key: KeyId, writeEnvelope: DataEnvelope): Option[DataEnvelope] = { + def write(key: KeyId, writeEnvelope: DataEnvelope): Option[DataEnvelope] = getData(key) match { case someEnvelope @ Some(envelope) if envelope eq writeEnvelope => someEnvelope case Some(DataEnvelope(DeletedData, _, _)) => Some(DeletedEnvelope) // already deleted @@ -1895,7 +1882,6 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog val writeEnvelope3 = writeEnvelope2.addSeen(selfAddress) Some(setData(key, writeEnvelope3)) } - } def receiveReadRepair(key: KeyId, writeEnvelope: DataEnvelope): Unit = { writeAndStore(key, writeEnvelope, reply = false) @@ -1911,7 +1897,7 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog replyTo ! GetKeyIdsResult(keys) } - def receiveDelete(key: KeyR, consistency: WriteConsistency, req: Option[Any]): Unit = { + def receiveDelete(key: KeyR, consistency: WriteConsistency, req: Option[Any]): Unit = getData(key.id) match { case Some(DataEnvelope(DeletedData, _, _)) => // already deleted @@ -1957,10 +1943,9 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog } } } - } def setData(key: KeyId, envelope: DataEnvelope): DataEnvelope = { - val newEnvelope = { + val newEnvelope = if (deltaCrdtEnabled) { val deltaVersions = envelope.deltaVersions val currVersion = deltaPropagationSelector.currentVersion(key) @@ -1969,7 +1954,6 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog else envelope.copy(deltaVersions = deltaVersions.merge(VersionVector(selfUniqueAddress, currVersion))) } else envelope - } val dig = if (subscribers.contains(key) && !changed.contains(key)) { @@ -1988,7 +1972,7 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog newEnvelope } - def getDigest(key: KeyId): Digest = { + def getDigest(key: KeyId): Digest = dataEntries.get(key) match { case Some((envelope, LazyDigest)) => val (d, size) = digest(envelope) @@ -1998,7 +1982,6 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog case Some((_, digest)) => digest case None => NotFoundDigest } - } /** * @return SHA-1 digest of the serialized data, and the size of the serialized data @@ -2019,13 +2002,12 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog case None => 0L } - def isNodeRemoved(node: UniqueAddress, keys: Iterable[KeyId]): Boolean = { + def isNodeRemoved(node: UniqueAddress, keys: Iterable[KeyId]): Boolean = removedNodes.contains(node) || (keys.exists(key => dataEntries.get(key) match { case Some((DataEnvelope(_, pruning, _), _)) => pruning.contains(node) case None => false })) - } def receiveFlushChanges(): Unit = { def notify(keyId: KeyId, subs: mutable.Set[ActorRef]): Unit = { @@ -2033,7 +2015,7 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog getData(keyId) match { case Some(envelope) => val msg = if (envelope.data == DeletedData) Deleted(key) else Changed(key)(envelope.data) - subs.foreach { _ ! msg } + subs.foreach(_ ! msg) case None => } } @@ -2048,7 +2030,7 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog if (newSubscribers.nonEmpty) { for ((key, subs) <- newSubscribers) { notify(key, subs) - subs.foreach { subscribers.addBinding(key, _) } + subs.foreach(subscribers.addBinding(key, _)) } newSubscribers.clear() } @@ -2132,10 +2114,9 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog if (reply) replyTo ! DeltaNack } - def receiveGossipTick(): Unit = { + def receiveGossipTick(): Unit = if (fullStateGossipEnabled) selectRandomNode(allNodes.toVector).foreach(gossipTo) - } def gossipTo(address: UniqueAddress): Unit = { val to = replica(address) @@ -2311,7 +2292,7 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog subscribers.exists { case (_, s) => s.contains(subscriber) } || newSubscribers.exists { case (_, s) => s.contains(subscriber) } - def receiveTerminated(ref: ActorRef): Unit = { + def receiveTerminated(ref: ActorRef): Unit = if (ref == durableStore) { log.error("Stopping distributed-data Replicator because durable store terminated") context.stop(self) @@ -2330,7 +2311,6 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog subscriptionKeys -= key } } - } def receiveMemberJoining(m: Member): Unit = if (matchingRole(m) && m.address != selfAddress) @@ -2358,7 +2338,7 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog if (matchingRole(m) && m.address != selfAddress) exitingNodes += m.uniqueAddress - def receiveMemberRemoved(m: Member): Unit = { + def receiveMemberRemoved(m: Member): Unit = if (m.address == selfAddress) context.stop(self) else if (matchingRole(m)) { @@ -2375,7 +2355,6 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog membersByAge -= m deltaPropagationSelector.cleanupRemovedNode(m.uniqueAddress) } - } def receiveOtherMemberEvent(m: Member): Unit = if (matchingRole(m)) { @@ -2397,7 +2376,7 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog previousClockTime = now } - def receiveRemovedNodePruningTick(): Unit = { + def receiveRemovedNodePruningTick(): Unit = // See 'CRDT Garbage' section in Replicator Scaladoc for description of the process if (unreachable.isEmpty) { if (isLeader) { @@ -2407,7 +2386,6 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog performRemovedNodePruning() deleteObsoletePruningPerformed() } - } def collectRemovedNodes(): Unit = { val knownNodes = allNodes.union(removedNodes.keySet) @@ -2498,10 +2476,9 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog } - def receiveGetReplicaCount(): Unit = { + def receiveGetReplicaCount(): Unit = // selfAddress is not included in the set replyTo ! ReplicaCount(nodes.size + 1) - } } @@ -2657,7 +2634,7 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog case Some(d) => d case None => writeMsg } - primaryNodes.foreach { replica(_) ! msg } + primaryNodes.foreach(replica(_) ! msg) if (isDone) reply(isTimeout = false) } @@ -2693,7 +2670,7 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog replica(to) ! writeMsg } } - secondaryNodes.foreach { replica(_) ! writeMsg } + secondaryNodes.foreach(replica(_) ! writeMsg) case ReceiveTimeout => reply(isTimeout = true) } @@ -2792,7 +2769,7 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog private val (primaryNodes, secondaryNodes) = primaryAndSecondaryNodes() override def preStart(): Unit = { - primaryNodes.foreach { replica(_) ! readMsg } + primaryNodes.foreach(replica(_) ! readMsg) if (remaining.size == doneWhenRemainingSize) reply(ok = true) @@ -2812,7 +2789,7 @@ final class Replicator(settings: ReplicatorSettings) extends Actor with ActorLog if (remaining.size == doneWhenRemainingSize) reply(ok = true) case SendToSecondary => - secondaryNodes.foreach { replica(_) ! readMsg } + secondaryNodes.foreach(replica(_) ! readMsg) case ReceiveTimeout => reply(ok = false) } diff --git a/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/VersionVector.scala b/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/VersionVector.scala index 2d438207b18..7c13dd729d3 100644 --- a/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/VersionVector.scala +++ b/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/VersionVector.scala @@ -258,9 +258,8 @@ sealed abstract class VersionVector extends ReplicatedData with ReplicatedDataSe * 4. Version 1 is CONCURRENT (<>) to Version 2 otherwise. * }}} */ - def compareTo(that: VersionVector): Ordering = { + def compareTo(that: VersionVector): Ordering = compareOnlyTo(that, FullOrder) - } /** * Merges this VersionVector with another VersionVector. E.g. merges its versioned history. @@ -306,7 +305,7 @@ final case class OneVersionVector private[pekko] (node: UniqueAddress, version: @InternalApi private[pekko] override def versionsIterator: Iterator[(UniqueAddress, Long)] = Iterator.single((node, version)) - override def merge(that: VersionVector): VersionVector = { + override def merge(that: VersionVector): VersionVector = that match { case OneVersionVector(n2, v2) => if (node == n2) if (version >= v2) this else OneVersionVector(n2, v2) @@ -318,7 +317,6 @@ final case class OneVersionVector private[pekko] (node: UniqueAddress, version: else vs2.updated(node, version) VersionVector(mergedVersions) } - } override def modifiedByNodes: Set[UniqueAddress] = Set(node) @@ -369,7 +367,7 @@ final case class ManyVersionVector(versions: TreeMap[UniqueAddress, Long]) exten @InternalApi private[pekko] override def versionsIterator: Iterator[(UniqueAddress, Long)] = versions.iterator - override def merge(that: VersionVector): VersionVector = { + override def merge(that: VersionVector): VersionVector = if (that.isEmpty) this else if (this.isEmpty) that else @@ -389,7 +387,6 @@ final case class ManyVersionVector(versions: TreeMap[UniqueAddress, Long]) exten else versions.updated(n2, v2) VersionVector(mergedVersions) } - } override def modifiedByNodes: Set[UniqueAddress] = versions.keySet diff --git a/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/protobuf/ReplicatedDataSerializer.scala b/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/protobuf/ReplicatedDataSerializer.scala index 759e17b4c03..17c9e32bc81 100644 --- a/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/protobuf/ReplicatedDataSerializer.scala +++ b/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/protobuf/ReplicatedDataSerializer.scala @@ -454,13 +454,12 @@ class ReplicatedDataSerializer(val system: ExtendedActorSystem) gsetFromProto(rd.GSet.parseFrom(bytes)) def gsetFromProto(gset: rd.GSet): GSet[Any] = { - val elements: Iterator[Any] = { + val elements: Iterator[Any] = gset.getStringElementsList.iterator.asScala ++ gset.getIntElementsList.iterator.asScala ++ gset.getLongElementsList.iterator.asScala ++ gset.getOtherElementsList.iterator.asScala.map(otherMessageFromProto) ++ gset.getActorRefElementsList.iterator.asScala.map(resolveActorRef) - } GSet(elements.toSet) } @@ -523,9 +522,8 @@ class ReplicatedDataSerializer(val system: ExtendedActorSystem) if (!actorRefElements.isEmpty) { Collections.sort(actorRefElements) val iter = actorRefElements.iterator - while (iter.hasNext) { + while (iter.hasNext) b.addActorRefElements(Serialization.serializedActorPath(iter.next())) - } addDots(actorRefElements) } @@ -545,9 +543,8 @@ class ReplicatedDataSerializer(val system: ExtendedActorSystem) new ORSet.FullStateDeltaOp(orsetFromProto(rd.ORSet.parseFrom(bytes))) private def orsetDeltaGroupToProto(deltaGroup: ORSet.DeltaGroup[_]): rd.ORSetDeltaGroup = { - def createEntry(opType: rd.ORSetDeltaOp, u: ORSet[_]) = { + def createEntry(opType: rd.ORSetDeltaOp, u: ORSet[_]) = rd.ORSetDeltaGroup.Entry.newBuilder().setOperation(opType).setUnderlying(orsetToProto(u)) - } val b = rd.ORSetDeltaGroup.newBuilder() deltaGroup.ops.foreach { @@ -582,13 +579,12 @@ class ReplicatedDataSerializer(val system: ExtendedActorSystem) } def orsetFromProto(orset: rd.ORSet): ORSet[Any] = { - val elements: Iterator[Any] = { + val elements: Iterator[Any] = orset.getStringElementsList.iterator.asScala ++ orset.getIntElementsList.iterator.asScala ++ orset.getLongElementsList.iterator.asScala ++ orset.getOtherElementsList.iterator.asScala.map(otherMessageFromProto) ++ orset.getActorRefElementsList.iterator.asScala.map(resolveActorRef) - } val dots = orset.getDotsList.asScala.map(versionVectorFromProto).iterator val elementsMap = elements.zip(dots).toMap @@ -638,12 +634,11 @@ class ReplicatedDataSerializer(val system: ExtendedActorSystem) def gcounterFromBinary(bytes: Array[Byte]): GCounter = gcounterFromProto(rd.GCounter.parseFrom(bytes)) - def gcounterFromProto(gcounter: rd.GCounter): GCounter = { + def gcounterFromProto(gcounter: rd.GCounter): GCounter = new GCounter( state = gcounter.getEntriesList.asScala.iterator .map(entry => uniqueAddressFromProto(entry.getNode) -> BigInt(entry.getValue.toByteArray)) .toMap) - } def pncounterToProto(pncounter: PNCounter): rd.PNCounter = rd.PNCounter @@ -655,11 +650,10 @@ class ReplicatedDataSerializer(val system: ExtendedActorSystem) def pncounterFromBinary(bytes: Array[Byte]): PNCounter = pncounterFromProto(rd.PNCounter.parseFrom(bytes)) - def pncounterFromProto(pncounter: rd.PNCounter): PNCounter = { + def pncounterFromProto(pncounter: rd.PNCounter): PNCounter = new PNCounter( increments = gcounterFromProto(pncounter.getIncrements), decrements = gcounterFromProto(pncounter.getDecrements)) - } /** * Convert a Map[A, B] to an Iterable[Entry] where Entry is the protobuf map entry. @@ -696,7 +690,7 @@ class ReplicatedDataSerializer(val system: ExtendedActorSystem) def mapTypeFromProto[PEntry <: GeneratedMessageV3, A <: GeneratedMessageV3, B <: ReplicatedData]( input: util.List[PEntry], - valueCreator: A => B)(implicit eh: ProtoMapEntryReader[PEntry, A]): Map[Any, B] = { + valueCreator: A => B)(implicit eh: ProtoMapEntryReader[PEntry, A]): Map[Any, B] = input.asScala.map { entry => if (eh.hasStringKey(entry)) eh.getStringKey(entry) -> valueCreator(eh.getValue(entry)) else if (eh.hasIntKey(entry)) eh.getIntKey(entry) -> valueCreator(eh.getValue(entry)) @@ -706,7 +700,6 @@ class ReplicatedDataSerializer(val system: ExtendedActorSystem) throw new IllegalArgumentException( s"Can't deserialize ${entry.getClass} because it does not have any key in the serialized message.") }.toMap - } def ormapFromProto(ormap: rd.ORMap): ORMap[Any, ReplicatedData] = { val entries = mapTypeFromProto( @@ -784,9 +777,8 @@ class ReplicatedDataSerializer(val system: ExtendedActorSystem) case _ => throw new IllegalArgumentException("Invalid ZeroTag code") } - private def ormapDeltaGroupFromBinary(bytes: Array[Byte]): ORMap.DeltaGroup[Any, ReplicatedData] = { + private def ormapDeltaGroupFromBinary(bytes: Array[Byte]): ORMap.DeltaGroup[Any, ReplicatedData] = ORMap.DeltaGroup(ormapDeltaGroupOpsFromBinary(bytes)) - } private def ormapDeltaGroupOpsFromBinary(bytes: Array[Byte]): scala.collection.immutable.IndexedSeq[ORMap.DeltaOp] = { val deltaGroup = rd.ORMapDeltaGroup.parseFrom(bytes) @@ -827,28 +819,23 @@ class ReplicatedDataSerializer(val system: ExtendedActorSystem) ops } - private def ormapPutToProto(deltaOp: ORMap.PutDeltaOp[_, _]): rd.ORMapDeltaGroup = { + private def ormapPutToProto(deltaOp: ORMap.PutDeltaOp[_, _]): rd.ORMapDeltaGroup = ormapDeltaGroupOpsToProto(immutable.IndexedSeq(deltaOp.asInstanceOf[ORMap.DeltaOp])) - } - private def ormapRemoveToProto(deltaOp: ORMap.RemoveDeltaOp[_, _]): rd.ORMapDeltaGroup = { + private def ormapRemoveToProto(deltaOp: ORMap.RemoveDeltaOp[_, _]): rd.ORMapDeltaGroup = ormapDeltaGroupOpsToProto(immutable.IndexedSeq(deltaOp.asInstanceOf[ORMap.DeltaOp])) - } - private def ormapRemoveKeyToProto(deltaOp: ORMap.RemoveKeyDeltaOp[_, _]): rd.ORMapDeltaGroup = { + private def ormapRemoveKeyToProto(deltaOp: ORMap.RemoveKeyDeltaOp[_, _]): rd.ORMapDeltaGroup = ormapDeltaGroupOpsToProto(immutable.IndexedSeq(deltaOp.asInstanceOf[ORMap.DeltaOp])) - } - private def ormapUpdateToProto(deltaOp: ORMap.UpdateDeltaOp[_, _]): rd.ORMapDeltaGroup = { + private def ormapUpdateToProto(deltaOp: ORMap.UpdateDeltaOp[_, _]): rd.ORMapDeltaGroup = ormapDeltaGroupOpsToProto(immutable.IndexedSeq(deltaOp.asInstanceOf[ORMap.DeltaOp])) - } - private def ormapDeltaGroupToProto(deltaGroup: ORMap.DeltaGroup[_, _]): rd.ORMapDeltaGroup = { + private def ormapDeltaGroupToProto(deltaGroup: ORMap.DeltaGroup[_, _]): rd.ORMapDeltaGroup = ormapDeltaGroupOpsToProto(deltaGroup.ops) - } private def ormapDeltaGroupOpsToProto(deltaGroupOps: immutable.IndexedSeq[ORMap.DeltaOp]): rd.ORMapDeltaGroup = { - def createEntry(opType: rd.ORMapDeltaOp, u: ORSet[_], m: Map[_, _], zt: Int) = { + def createEntry(opType: rd.ORMapDeltaOp, u: ORSet[_], m: Map[_, _], zt: Int) = if (m.size > 1 && opType != rd.ORMapDeltaOp.ORMapUpdate) throw new IllegalArgumentException("Invalid size of ORMap delta map") else { @@ -874,7 +861,6 @@ class ReplicatedDataSerializer(val system: ExtendedActorSystem) } builder } - } def createEntryWithKey(opType: rd.ORMapDeltaOp, u: ORSet[_], k: Any, zt: Int) = { val entryDataBuilder = rd.ORMapDeltaGroup.MapEntry.newBuilder() @@ -995,7 +981,7 @@ object OtherMessageComparator extends Comparator[dm.OtherMessage] { if (aSize == bSize) { val aIter = aByteString.iterator val bIter = bByteString.iterator - @tailrec def findDiff(): Int = { + @tailrec def findDiff(): Int = if (aIter.hasNext) { val aByte = aIter.nextByte() val bByte = bIter.nextByte() @@ -1003,7 +989,6 @@ object OtherMessageComparator extends Comparator[dm.OtherMessage] { else if (aByte > bByte) 1 else findDiff() } else 0 - } findDiff() } else if (aSize < bSize) -1 else 1 diff --git a/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/protobuf/ReplicatorMessageSerializer.scala b/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/protobuf/ReplicatorMessageSerializer.scala index f5538d21c1a..c489e11504f 100644 --- a/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/protobuf/ReplicatorMessageSerializer.scala +++ b/distributed-data/src/main/scala/org/apache/pekko/cluster/ddata/protobuf/ReplicatorMessageSerializer.scala @@ -82,14 +82,13 @@ private[pekko] object ReplicatorMessageSerializer { private def get(a: A, startPos: Int): B = { // start at the latest added value, most likely that we want that val end = startPos + elements.length - @tailrec def find(i: Int): B = { + @tailrec def find(i: Int): B = if (end - i == 0) null.asInstanceOf[B] else { val x = elements(i & mask) if ((x eq null) || (x._1 ne a)) find(i + 1) else x._2 } - } lastUsed = System.nanoTime() find(startPos) } @@ -487,7 +486,7 @@ class ReplicatorMessageSerializer(val system: ExtendedActorSystem) Changed(key)(data) } - private def pruningToProto(entries: Map[UniqueAddress, PruningState]): Iterable[dm.DataEnvelope.PruningEntry] = { + private def pruningToProto(entries: Map[UniqueAddress, PruningState]): Iterable[dm.DataEnvelope.PruningEntry] = entries.map { case (removedAddress, state) => val b = dm.DataEnvelope.PruningEntry.newBuilder().setRemovedAddress(uniqueAddressToProto(removedAddress)) @@ -506,7 +505,6 @@ class ReplicatorMessageSerializer(val system: ExtendedActorSystem) } b.build() } - } private def dataEnvelopeToProto(dataEnvelope: DataEnvelope): dm.DataEnvelope = { val dataEnvelopeBuilder = dm.DataEnvelope.newBuilder().setData(otherMessageToProto(dataEnvelope.data)) @@ -532,7 +530,7 @@ class ReplicatorMessageSerializer(val system: ExtendedActorSystem) } private def pruningFromProto( - pruningEntries: java.util.List[dm.DataEnvelope.PruningEntry]): Map[UniqueAddress, PruningState] = { + pruningEntries: java.util.List[dm.DataEnvelope.PruningEntry]): Map[UniqueAddress, PruningState] = if (pruningEntries.isEmpty) Map.empty else @@ -549,7 +547,6 @@ class ReplicatorMessageSerializer(val system: ExtendedActorSystem) val removed = uniqueAddressFromProto(pruningEntry.getRemovedAddress) removed -> state }.toMap - } private def writeToProto(write: Write): dm.Write = dm.Write diff --git a/distributed-data/src/multi-jvm/scala/org/apache/pekko/cluster/ddata/DurableDataSpec.scala b/distributed-data/src/multi-jvm/scala/org/apache/pekko/cluster/ddata/DurableDataSpec.scala index 1bde6f2d8d6..529fe3ae3a8 100644 --- a/distributed-data/src/multi-jvm/scala/org/apache/pekko/cluster/ddata/DurableDataSpec.scala +++ b/distributed-data/src/multi-jvm/scala/org/apache/pekko/cluster/ddata/DurableDataSpec.scala @@ -241,7 +241,7 @@ abstract class DurableDataSpec(multiNodeConfig: DurableDataSpecConfig) system.stop(r) expectTerminated(r) - val r2 = awaitAssert { newReplicator() } // try until name is free + val r2 = awaitAssert(newReplicator()) // try until name is free awaitAssert { r2 ! GetKeyIds expectMsgType[GetKeyIdsResult].keyIds should !==(Set.empty[String]) @@ -288,9 +288,8 @@ abstract class DurableDataSpec(multiNodeConfig: DurableDataSpecConfig) system.stop(r) expectTerminated(r) } - } finally { + } finally Await.ready(sys1.terminate(), 10.seconds) - } val sys2 = ActorSystem( "AdditionalSys", @@ -319,9 +318,8 @@ abstract class DurableDataSpec(multiNodeConfig: DurableDataSpecConfig) r2 ! Get(KeyB, ReadLocal) expectMsgType[GetSuccess[GCounter]].dataValue.value.toInt should be(2) } - } finally { + } finally Await.ready(sys1.terminate(), 10.seconds) - } } system.log.info("Setup complete") diff --git a/distributed-data/src/multi-jvm/scala/org/apache/pekko/cluster/ddata/DurablePruningSpec.scala b/distributed-data/src/multi-jvm/scala/org/apache/pekko/cluster/ddata/DurablePruningSpec.scala index 36edb54f961..2dfd5f3e246 100644 --- a/distributed-data/src/multi-jvm/scala/org/apache/pekko/cluster/ddata/DurablePruningSpec.scala +++ b/distributed-data/src/multi-jvm/scala/org/apache/pekko/cluster/ddata/DurablePruningSpec.scala @@ -179,10 +179,9 @@ class DurablePruningSpec extends MultiNodeSpec(DurablePruningSpec) with STMultiN val probe3 = TestProbe()(sys3) cluster3.join(node(first).address) - awaitAssert({ - cluster.state.members.exists(m => - m.uniqueAddress == cluster3.selfUniqueAddress && m.status == MemberStatus.Up) should ===(true) - }, 10.seconds) + awaitAssert( + cluster.state.members.exists(m => + m.uniqueAddress == cluster3.selfUniqueAddress && m.status == MemberStatus.Up) should ===(true), 10.seconds) within(10.seconds) { var values = Set.empty[Int] diff --git a/distributed-data/src/multi-jvm/scala/org/apache/pekko/cluster/ddata/JepsenInspiredInsertSpec.scala b/distributed-data/src/multi-jvm/scala/org/apache/pekko/cluster/ddata/JepsenInspiredInsertSpec.scala index 6674c52df25..d567f8a1f8f 100644 --- a/distributed-data/src/multi-jvm/scala/org/apache/pekko/cluster/ddata/JepsenInspiredInsertSpec.scala +++ b/distributed-data/src/multi-jvm/scala/org/apache/pekko/cluster/ddata/JepsenInspiredInsertSpec.scala @@ -87,10 +87,9 @@ class JepsenInspiredInsertSpec if (rndDelay != 0) Thread.sleep(delayMillis) } - def sleepBeforePartition(): Unit = { + def sleepBeforePartition(): Unit = if (delayMillis != 0) Thread.sleep(delayMillis * totalCount / nodeCount / 10) - } def sleepDuringPartition(): Unit = Thread.sleep(math.max(5000, delayMillis * totalCount / nodeCount / 2)) @@ -106,7 +105,7 @@ class JepsenInspiredInsertSpec "setup cluster" in { runOn(nodes: _*) { - nodes.foreach { join(_, n1) } + nodes.foreach(join(_, n1)) within(10.seconds) { awaitAssert { diff --git a/distributed-data/src/multi-jvm/scala/org/apache/pekko/cluster/ddata/PerformanceSpec.scala b/distributed-data/src/multi-jvm/scala/org/apache/pekko/cluster/ddata/PerformanceSpec.scala index 8dd2c4d2ec2..d5b3f531d23 100644 --- a/distributed-data/src/multi-jvm/scala/org/apache/pekko/cluster/ddata/PerformanceSpec.scala +++ b/distributed-data/src/multi-jvm/scala/org/apache/pekko/cluster/ddata/PerformanceSpec.scala @@ -102,8 +102,7 @@ class PerformanceSpec extends MultiNodeSpec(PerformanceSpec) with STMultiNodeSpe expectedAfterReplication: Option[Set[Int]] = None, oneByOne: Boolean = false)( block: (ORSetKey[Int], Int, ActorRef) => Unit, - afterEachKey: ORSetKey[Int] => Unit = _ => ()): Unit = { - + afterEachKey: ORSetKey[Int] => Unit = _ => ()): Unit = keys.foreach { key => val startTime = System.nanoTime() runOn(n1) { @@ -138,14 +137,13 @@ class PerformanceSpec extends MultiNodeSpec(PerformanceSpec) with STMultiNodeSpe afterEachKey(key) enterBarrier("repeat-" + key + "-done") } - } def awaitReplicated(keys: Iterable[ORSetKey[Int]], expectedData: Set[Int]): Unit = keys.foreach { key => awaitReplicated(key, expectedData) } - def awaitReplicated(key: ORSetKey[Int], expectedData: Set[Int]): Unit = { + def awaitReplicated(key: ORSetKey[Int], expectedData: Set[Int]): Unit = within(20.seconds) { awaitAssert { val readProbe = TestProbe() @@ -154,12 +152,11 @@ class PerformanceSpec extends MultiNodeSpec(PerformanceSpec) with STMultiNodeSpe result.elements should be(expectedData) } } - } "Performance" must { "setup cluster" taggedAs PerformanceTest in { - roles.foreach { join(_, n1) } + roles.foreach(join(_, n1)) within(10.seconds) { awaitAssert { @@ -175,9 +172,8 @@ class PerformanceSpec extends MultiNodeSpec(PerformanceSpec) with STMultiNodeSpe val keys = (1 to repeatCount).map(n => ORSetKey[Int]("A" + n)) val n = 1000 * factor val expectedData = (0 until n).toSet - repeat("ORSet Update WriteLocal", keys, n)({ (key, i, replyTo) => - replicator.tell(Update(key, ORSet(), WriteLocal)(_ :+ i), replyTo) - }, key => awaitReplicated(key, expectedData)) + repeat("ORSet Update WriteLocal", keys, n)((key, i, replyTo) => + replicator.tell(Update(key, ORSet(), WriteLocal)(_ :+ i), replyTo), key => awaitReplicated(key, expectedData)) enterBarrier("after-1") } diff --git a/distributed-data/src/multi-jvm/scala/org/apache/pekko/cluster/ddata/ReplicatorDeltaSpec.scala b/distributed-data/src/multi-jvm/scala/org/apache/pekko/cluster/ddata/ReplicatorDeltaSpec.scala index 41f60b961f2..872bd758c32 100644 --- a/distributed-data/src/multi-jvm/scala/org/apache/pekko/cluster/ddata/ReplicatorDeltaSpec.scala +++ b/distributed-data/src/multi-jvm/scala/org/apache/pekko/cluster/ddata/ReplicatorDeltaSpec.scala @@ -86,29 +86,26 @@ object ReplicatorDeltaSpec extends MultiNodeConfig { def generateOperations(onNode: RoleName): Vector[Op] = { val rnd = ThreadLocalRandom.current() - def consistency(): WriteConsistency = { + def consistency(): WriteConsistency = rnd.nextInt(100) match { case n if n < 90 => WriteLocal case n if n < 95 => writeTwo case n if n < 100 => writeMajority } - } - def rndPnCounterkey(): PNCounterKey = { + def rndPnCounterkey(): PNCounterKey = rnd.nextInt(3) match { case 0 => KeyA case 1 => KeyB case 2 => KeyC } - } - def rndOrSetkey(): ORSetKey[String] = { + def rndOrSetkey(): ORSetKey[String] = rnd.nextInt(3) match { case 0 => KeyD case 1 => KeyE case 2 => KeyF } - } var availableForRemove = Set.empty[String] @@ -119,12 +116,11 @@ object ReplicatorDeltaSpec extends MultiNodeConfig { s } - def rndRemoveElement(): String = { + def rndRemoveElement(): String = if (availableForRemove.isEmpty) "a" else availableForRemove.toVector(rnd.nextInt(availableForRemove.size)) - } (0 to (30 + rnd.nextInt(10))).map { _ => rnd.nextInt(4) match { diff --git a/distributed-data/src/multi-jvm/scala/org/apache/pekko/cluster/ddata/ReplicatorMapDeltaSpec.scala b/distributed-data/src/multi-jvm/scala/org/apache/pekko/cluster/ddata/ReplicatorMapDeltaSpec.scala index 7c9103ebaa6..404564adcc7 100644 --- a/distributed-data/src/multi-jvm/scala/org/apache/pekko/cluster/ddata/ReplicatorMapDeltaSpec.scala +++ b/distributed-data/src/multi-jvm/scala/org/apache/pekko/cluster/ddata/ReplicatorMapDeltaSpec.scala @@ -88,45 +88,40 @@ object ReplicatorMapDeltaSpec extends MultiNodeConfig { def generateOperations(onNode: RoleName): Vector[Op] = { val rnd = ThreadLocalRandom.current() - def consistency(): WriteConsistency = { + def consistency(): WriteConsistency = rnd.nextInt(100) match { case n if n < 90 => WriteLocal case n if n < 95 => writeTwo case n if n < 100 => writeMajority } - } - def rndPnCounterkey(): (PNCounterMapKey[String], String) = { + def rndPnCounterkey(): (PNCounterMapKey[String], String) = rnd.nextInt(3) match { case 0 => KeyA case 1 => KeyB case 2 => KeyC } - } - def rndOrSetkeyVD(): (ORMultiMapKey[String, String], String) = { + def rndOrSetkeyVD(): (ORMultiMapKey[String, String], String) = rnd.nextInt(3) match { case 0 => KeyD case 1 => KeyE case 2 => KeyF } - } - def rndOrSetkeyNoVD(): (ORMultiMapKey[String, String], String) = { + def rndOrSetkeyNoVD(): (ORMultiMapKey[String, String], String) = rnd.nextInt(3) match { case 0 => KeyG case 1 => KeyH case 2 => KeyI } - } - def rndOrSetkeyOM(): (ORMapKey[String, ORSet[String]], String) = { + def rndOrSetkeyOM(): (ORMapKey[String, ORSet[String]], String) = rnd.nextInt(3) match { case 0 => KeyJ case 1 => KeyK case 2 => KeyL } - } var availableForRemove = Set.empty[String] @@ -137,12 +132,11 @@ object ReplicatorMapDeltaSpec extends MultiNodeConfig { s } - def rndRemoveElement(): String = { + def rndRemoveElement(): String = if (availableForRemove.isEmpty) "a" else availableForRemove.toVector(rnd.nextInt(availableForRemove.size)) - } (0 to (50 + rnd.nextInt(10))).map { _ => rnd.nextInt(6) match { @@ -320,9 +314,8 @@ class ReplicatorMapDeltaSpec extends MultiNodeSpec(ReplicatorMapDeltaSpec) with val errorLogProbe = TestProbe() system.eventStream.subscribe(errorLogProbe.ref, classOf[Error]) runOn(first) { - for (_ <- 1 to N; key <- List(KeyA, KeyB)) { + for (_ <- 1 to N; key <- List(KeyA, KeyB)) ordinaryReplicator ! Update(key._1, PNCounterMap.empty[String], WriteLocal)(_.incrementBy(key._2, 1)) - } } enterBarrier("updated-2") diff --git a/distributed-data/src/multi-jvm/scala/org/apache/pekko/cluster/ddata/ReplicatorPruningSpec.scala b/distributed-data/src/multi-jvm/scala/org/apache/pekko/cluster/ddata/ReplicatorPruningSpec.scala index a9445e04d83..419b52fc679 100644 --- a/distributed-data/src/multi-jvm/scala/org/apache/pekko/cluster/ddata/ReplicatorPruningSpec.scala +++ b/distributed-data/src/multi-jvm/scala/org/apache/pekko/cluster/ddata/ReplicatorPruningSpec.scala @@ -115,7 +115,7 @@ class ReplicatorPruningSpec extends MultiNodeSpec(ReplicatorPruningSpec) with ST } expectMsg(UpdateSuccess(KeyC, None)) - replicator ! Update(KeyD, ORMultiMap.empty[String, String], WriteAll(timeout)) { _ :+ ("a" -> Set("A")) } + replicator ! Update(KeyD, ORMultiMap.empty[String, String], WriteAll(timeout))(_ :+ ("a" -> Set("A"))) expectMsg(UpdateSuccess(KeyD, None)) replicator ! Update(KeyE, ORMap.empty[String, GSet[String]], WriteAll(timeout)) { @@ -150,7 +150,7 @@ class ReplicatorPruningSpec extends MultiNodeSpec(ReplicatorPruningSpec) with ST enterBarrier("get-old") runOn(third) { - replicator ! Update(KeyE, ORMap.empty[String, GSet[String]], WriteLocal) { _.remove("a") } + replicator ! Update(KeyE, ORMap.empty[String, GSet[String]], WriteLocal)(_.remove("a")) expectMsg(UpdateSuccess(KeyE, None)) } diff --git a/distributed-data/src/test/scala/org/apache/pekko/cluster/ddata/LocalConcurrencySpec.scala b/distributed-data/src/test/scala/org/apache/pekko/cluster/ddata/LocalConcurrencySpec.scala index ceb966f5455..e9e0752aa89 100644 --- a/distributed-data/src/test/scala/org/apache/pekko/cluster/ddata/LocalConcurrencySpec.scala +++ b/distributed-data/src/test/scala/org/apache/pekko/cluster/ddata/LocalConcurrencySpec.scala @@ -66,9 +66,8 @@ class LocalConcurrencySpec(_system: ActorSystem) pekko.remote.artery.canonical.port = 0 """))) - override def afterAll(): Unit = { + override def afterAll(): Unit = shutdown(system) - } val replicator = DistributedData(system).replicator diff --git a/distributed-data/src/test/scala/org/apache/pekko/cluster/ddata/LotsOfDataBot.scala b/distributed-data/src/test/scala/org/apache/pekko/cluster/ddata/LotsOfDataBot.scala index 35af027f834..6465a642288 100644 --- a/distributed-data/src/test/scala/org/apache/pekko/cluster/ddata/LotsOfDataBot.scala +++ b/distributed-data/src/test/scala/org/apache/pekko/cluster/ddata/LotsOfDataBot.scala @@ -31,14 +31,13 @@ import pekko.actor.Props */ object LotsOfDataBot { - def main(args: Array[String]): Unit = { + def main(args: Array[String]): Unit = if (args.isEmpty) startup(Seq("7354", "7355", "0")) else startup(args.toIndexedSeq) - } - def startup(ports: Seq[String]): Unit = { + def startup(ports: Seq[String]): Unit = ports.foreach { port => // Override the configuration of the port val config = ConfigFactory @@ -70,7 +69,6 @@ object LotsOfDataBot { // Create an actor that handles cluster domain events system.actorOf(Props[LotsOfDataBot](), name = "dataBot") } - } private case object Tick diff --git a/distributed-data/src/test/scala/org/apache/pekko/cluster/ddata/VersionVectorSpec.scala b/distributed-data/src/test/scala/org/apache/pekko/cluster/ddata/VersionVectorSpec.scala index ad1e871d45e..26a51af7e46 100644 --- a/distributed-data/src/test/scala/org/apache/pekko/cluster/ddata/VersionVectorSpec.scala +++ b/distributed-data/src/test/scala/org/apache/pekko/cluster/ddata/VersionVectorSpec.scala @@ -34,9 +34,8 @@ class VersionVectorSpec val node3 = UniqueAddress(node1.address.copy(port = Some(7356)), 3L) val node4 = UniqueAddress(node1.address.copy(port = Some(7357)), 4L) - override def afterAll(): Unit = { + override def afterAll(): Unit = shutdown() - } "A VersionVector" must { diff --git a/distributed-data/src/test/scala/org/apache/pekko/cluster/ddata/WriteAggregatorSpec.scala b/distributed-data/src/test/scala/org/apache/pekko/cluster/ddata/WriteAggregatorSpec.scala index 5b7e7795d96..e876797f395 100644 --- a/distributed-data/src/test/scala/org/apache/pekko/cluster/ddata/WriteAggregatorSpec.scala +++ b/distributed-data/src/test/scala/org/apache/pekko/cluster/ddata/WriteAggregatorSpec.scala @@ -174,9 +174,8 @@ class WriteAggregatorSpec extends PekkoSpec(s""" /** * Create a tuple for each node with the WriteAckAdapter and the TestProbe */ - def probes(): Map[UniqueAddress, TestMock] = { + def probes(): Map[UniqueAddress, TestMock] = nodes.toSeq.map(_ -> TestMock()).toMap - } "WriteAggregator" must { "send to at least N/2+1 replicas when WriteMajority" in { @@ -223,7 +222,7 @@ class WriteAggregatorSpec extends PekkoSpec(s""" val t = timeout / 5 - 50.milliseconds.dilated import system.dispatcher Future.sequence { - Seq(Future { testProbes(nodeC).expectNoMessage(t) }, Future { testProbes(nodeD).expectNoMessage(t) }) + Seq(Future(testProbes(nodeC).expectNoMessage(t)), Future(testProbes(nodeD).expectNoMessage(t))) }.futureValue testProbes(nodeC).expectMsgType[Write] testProbes(nodeC).lastSender ! WriteAck diff --git a/distributed-data/src/test/scala/org/apache/pekko/cluster/ddata/protobuf/ReplicatedDataSerializerSpec.scala b/distributed-data/src/test/scala/org/apache/pekko/cluster/ddata/protobuf/ReplicatedDataSerializerSpec.scala index 66116ed1939..55ae7fda89e 100644 --- a/distributed-data/src/test/scala/org/apache/pekko/cluster/ddata/protobuf/ReplicatedDataSerializerSpec.scala +++ b/distributed-data/src/test/scala/org/apache/pekko/cluster/ddata/protobuf/ReplicatedDataSerializerSpec.scala @@ -61,9 +61,8 @@ class ReplicatedDataSerializerSpec val ref2 = system.actorOf(Props.empty, "ref2") val ref3 = system.actorOf(Props.empty, "ref3") - override def afterAll(): Unit = { + override def afterAll(): Unit = shutdown() - } def checkSerialization(obj: AnyRef): Int = { val blob = serializer.toBinary(obj) @@ -145,9 +144,8 @@ class ReplicatedDataSerializerSpec val reply = expectMsgType[ORSet[ActorRef]] reply.elements should ===(Set(echo1, echo2)) - } finally { + } finally shutdown(system2) - } } "serialize ORSet delta" in { diff --git a/distributed-data/src/test/scala/org/apache/pekko/cluster/ddata/protobuf/ReplicatorMessageSerializerSpec.scala b/distributed-data/src/test/scala/org/apache/pekko/cluster/ddata/protobuf/ReplicatorMessageSerializerSpec.scala index c1a0212e0dc..c8d71aefc79 100644 --- a/distributed-data/src/test/scala/org/apache/pekko/cluster/ddata/protobuf/ReplicatorMessageSerializerSpec.scala +++ b/distributed-data/src/test/scala/org/apache/pekko/cluster/ddata/protobuf/ReplicatorMessageSerializerSpec.scala @@ -64,9 +64,8 @@ class ReplicatorMessageSerializerSpec val keyA = GSetKey[String]("A") - override def afterAll(): Unit = { + override def afterAll(): Unit = shutdown() - } def checkSerialization[T <: AnyRef](obj: T): T = { val blob = serializer.toBinary(obj) diff --git a/docs/src/test/scala-jdk9-only/docs/stream/operators/source/AsSubscriber.scala b/docs/src/test/scala-jdk9-only/docs/stream/operators/source/AsSubscriber.scala index 24b875a5db7..b5e0be12562 100644 --- a/docs/src/test/scala-jdk9-only/docs/stream/operators/source/AsSubscriber.scala +++ b/docs/src/test/scala-jdk9-only/docs/stream/operators/source/AsSubscriber.scala @@ -36,12 +36,12 @@ object AsSubscriber { // #example val rowSource: Source[Row, NotUsed] = JavaFlowSupport.Source.asSubscriber - .mapMaterializedValue((subscriber: Subscriber[Row]) => { + .mapMaterializedValue { (subscriber: Subscriber[Row]) => // For each materialization, fetch the rows from the database: val rows: Publisher[Row] = databaseClient.fetchRows() rows.subscribe(subscriber) NotUsed - }); + }; val names: Source[String, NotUsed] = // rowSource can be re-used, since it will start a new diff --git a/docs/src/test/scala/docs/actor/ActorDocSpec.scala b/docs/src/test/scala/docs/actor/ActorDocSpec.scala index da97a4f7d2e..793e8a6cf62 100644 --- a/docs/src/test/scala/docs/actor/ActorDocSpec.scala +++ b/docs/src/test/scala/docs/actor/ActorDocSpec.scala @@ -181,17 +181,15 @@ class ActorWithMessagesWrapper { class Hook extends Actor { var child: ActorRef = _ // #preStart - override def preStart(): Unit = { + override def preStart(): Unit = child = context.actorOf(Props[MyActor](), "child") - } // #preStart def receive = Actor.emptyBehavior // #postStop - override def postStop(): Unit = { + override def postStop(): Unit = // #clean-up-some-resources () - // #clean-up-some-resources - } + // #clean-up-some-resources // #postStop } @@ -210,7 +208,7 @@ class ReplyException extends Actor { // #reply-exception } - def operation(): String = { "Hi" } + def operation(): String = "Hi" } @@ -732,17 +730,16 @@ class ActorDocSpec extends PekkoSpec(""" "using CoordinatedShutdown" in { // other snippets moved to docs.actor.typed.CoordinatedActorShutdownSpec - { // https://github.com/akka/akka/issues/29056 - val someActor = system.actorOf(Props(classOf[Replier], this)) - someActor ! PoisonPill - // #coordinated-shutdown-addActorTerminationTask - CoordinatedShutdown(system).addActorTerminationTask( - CoordinatedShutdown.PhaseBeforeServiceUnbind, - "someTaskName", - someActor, - Some("stop")) - // #coordinated-shutdown-addActorTerminationTask - } + // https://github.com/akka/akka/issues/29056 + val someActor = system.actorOf(Props(classOf[Replier], this)) + someActor ! PoisonPill + // #coordinated-shutdown-addActorTerminationTask + CoordinatedShutdown(system).addActorTerminationTask( + CoordinatedShutdown.PhaseBeforeServiceUnbind, + "someTaskName", + someActor, + Some("stop")) + // #coordinated-shutdown-addActorTerminationTask } } diff --git a/docs/src/test/scala/docs/actor/FaultHandlingDocSample.scala b/docs/src/test/scala/docs/actor/FaultHandlingDocSample.scala index 74c6ba09aa3..f4a229c1a7a 100644 --- a/docs/src/test/scala/docs/actor/FaultHandlingDocSample.scala +++ b/docs/src/test/scala/docs/actor/FaultHandlingDocSample.scala @@ -159,9 +159,8 @@ class CounterService extends Actor { import context.dispatcher // Use this Actors' Dispatcher as ExecutionContext - override def preStart(): Unit = { + override def preStart(): Unit = initStorage() - } /** * The child storage is restarted in case of failure, but after 3 restarts, @@ -172,7 +171,7 @@ class CounterService extends Actor { def initStorage(): Unit = { storage = Some(context.watch(context.actorOf(Props[Storage](), name = "storage"))) // Tell the counter, if any, to use the new storage - counter.foreach { _ ! UseStorage(storage) } + counter.foreach(_ ! UseStorage(storage)) // We need the initial value to be able to operate storage.get ! Get(key) } @@ -198,7 +197,7 @@ class CounterService extends Actor { // We receive Terminated because we watch the child, see initStorage. storage = None // Tell the counter that there is no storage for the moment - counter.foreach { _ ! UseStorage(None) } + counter.foreach(_ ! UseStorage(None)) // Try to re-establish storage after while context.system.scheduler.scheduleOnce(10 seconds, self, Reconnect) @@ -207,7 +206,7 @@ class CounterService extends Actor { initStorage() } - def forwardOrPlaceInBacklog(msg: Any): Unit = { + def forwardOrPlaceInBacklog(msg: Any): Unit = // We need the initial value from storage before we can start delegate to // the counter. Before that we place the messages in a backlog, to be sent // to the counter when it is initialized. @@ -218,7 +217,6 @@ class CounterService extends Actor { throw new ServiceUnavailable("CounterService not available, lack of initial value") backlog :+= (sender() -> msg) } - } } @@ -255,11 +253,10 @@ class Counter(key: String, initialValue: Long) extends Actor { } - def storeCount(): Unit = { + def storeCount(): Unit = // Delegate dangerous work, to protect our valuable state. // We can continue without storage. - storage.foreach { _ ! Store(Entry(key, count)) } - } + storage.foreach(_ ! Store(Entry(key, count))) } diff --git a/docs/src/test/scala/docs/actor/FaultHandlingDocSpec.scala b/docs/src/test/scala/docs/actor/FaultHandlingDocSpec.scala index 71166a83071..3f05f5bde1a 100644 --- a/docs/src/test/scala/docs/actor/FaultHandlingDocSpec.scala +++ b/docs/src/test/scala/docs/actor/FaultHandlingDocSpec.scala @@ -132,9 +132,8 @@ class FaultHandlingDocSpec(_system: ActorSystem) } """))) - override def afterAll(): Unit = { + override def afterAll(): Unit = TestKit.shutdownActorSystem(system) - } "A supervisor" must { "apply the chosen strategy for its child" in { diff --git a/docs/src/test/scala/docs/actor/InitializationDocSpec.scala b/docs/src/test/scala/docs/actor/InitializationDocSpec.scala index b0d59c682fd..3270173e74f 100644 --- a/docs/src/test/scala/docs/actor/InitializationDocSpec.scala +++ b/docs/src/test/scala/docs/actor/InitializationDocSpec.scala @@ -35,10 +35,9 @@ object InitializationDocSpec { // The default implementation of preRestart() stops all the children // of the actor. To opt-out from stopping the children, we // have to override preRestart() - override def preRestart(reason: Throwable, message: Option[Any]): Unit = { + override def preRestart(reason: Throwable, message: Option[Any]): Unit = // Keep the call to postStop(), but no stopping of children postStop() - } // #preStartInit } @@ -54,7 +53,7 @@ object InitializationDocSpec { } def initialized: Receive = { - case "U OK?" => initializeMe.foreach { sender() ! _ } + case "U OK?" => initializeMe.foreach(sender() ! _) } // #messageInit diff --git a/docs/src/test/scala/docs/actor/SharedMutableStateDocSpec.scala b/docs/src/test/scala/docs/actor/SharedMutableStateDocSpec.scala index a77345d1905..f959e7adec6 100644 --- a/docs/src/test/scala/docs/actor/SharedMutableStateDocSpec.scala +++ b/docs/src/test/scala/docs/actor/SharedMutableStateDocSpec.scala @@ -42,15 +42,13 @@ class SharedMutableStateDocSpec { var state = "" val mySet = mutable.Set[String]() - def expensiveCalculation(actorRef: ActorRef): String = { + def expensiveCalculation(actorRef: ActorRef): String = // this is a very costly operation "Meaning of life is 42" - } - def expensiveCalculation(): String = { + def expensiveCalculation(): String = // this is a very costly operation "Meaning of life is 42" - } def receive = { case _ => @@ -72,17 +70,17 @@ class SharedMutableStateDocSpec { // Very bad: "sender" changes for every message, // shared mutable state bug - Future { expensiveCalculation(sender()) } + Future(expensiveCalculation(sender())) // Example of correct approach // Completely safe: "self" is OK to close over // and it's an ActorRef, which is thread-safe - Future { expensiveCalculation() }.foreach { self ! _ } + Future(expensiveCalculation()).foreach(self ! _) // Completely safe: we close over a fixed value // and it's an ActorRef, which is thread-safe val currentSender = sender() - Future { expensiveCalculation(currentSender) } + Future(expensiveCalculation(currentSender)) } } // #mutable-state diff --git a/docs/src/test/scala/docs/circuitbreaker/CircuitBreakerDocSpec.scala b/docs/src/test/scala/docs/circuitbreaker/CircuitBreakerDocSpec.scala index 3cf1f375994..e497794bef0 100644 --- a/docs/src/test/scala/docs/circuitbreaker/CircuitBreakerDocSpec.scala +++ b/docs/src/test/scala/docs/circuitbreaker/CircuitBreakerDocSpec.scala @@ -66,18 +66,14 @@ class TellPatternActor(recipient: ActorRef) extends Actor with ActorLogging { import org.apache.pekko.actor.ReceiveTimeout def receive = { - case "call" if breaker.isClosed => { + case "call" if breaker.isClosed => recipient ! "message" - } - case "response" => { + case "response" => breaker.succeed() - } - case err: Throwable => { + case err: Throwable => breaker.fail() - } - case ReceiveTimeout => { + case ReceiveTimeout => breaker.fail() - } } // #circuit-breaker-tell-pattern } diff --git a/docs/src/test/scala/docs/cluster/ClusterDocSpec.scala b/docs/src/test/scala/docs/cluster/ClusterDocSpec.scala index 81a58392ae6..0f7697ce035 100644 --- a/docs/src/test/scala/docs/cluster/ClusterDocSpec.scala +++ b/docs/src/test/scala/docs/cluster/ClusterDocSpec.scala @@ -37,18 +37,16 @@ class ClusterDocSpec extends PekkoSpec(ClusterDocSpec.config) with CompileOnlySp } "demonstrate data center" in compileOnlySpec { - { - // #dcAccess - val cluster = Cluster(system) - // this node's data center - val dc = cluster.selfDataCenter - // all known data centers - val allDc = cluster.state.allDataCenters - // a specific member's data center - val aMember = cluster.state.members.head - val aDc = aMember.dataCenter - // #dcAccess - } + // #dcAccess + val cluster = Cluster(system) + // this node's data center + val dc = cluster.selfDataCenter + // all known data centers + val allDc = cluster.state.allDataCenters + // a specific member's data center + val aMember = cluster.state.members.head + val aDc = aMember.dataCenter + // #dcAccess } "demonstrate programmatic joining to seed nodes" in compileOnlySpec { diff --git a/docs/src/test/scala/docs/cluster/FactorialBackend.scala b/docs/src/test/scala/docs/cluster/FactorialBackend.scala index 495a583ae7b..b85918ab718 100644 --- a/docs/src/test/scala/docs/cluster/FactorialBackend.scala +++ b/docs/src/test/scala/docs/cluster/FactorialBackend.scala @@ -37,10 +37,9 @@ class FactorialBackend extends Actor with ActorLogging { } def factorial(n: Int): BigInt = { - @tailrec def factorialAcc(acc: BigInt, n: Int): BigInt = { + @tailrec def factorialAcc(acc: BigInt, n: Int): BigInt = if (n <= 1) acc else factorialAcc(acc * n, n - 1) - } factorialAcc(BigInt(1), n) } diff --git a/docs/src/test/scala/docs/cluster/FactorialFrontend.scala b/docs/src/test/scala/docs/cluster/FactorialFrontend.scala index c7d466800cd..cf9c6411173 100644 --- a/docs/src/test/scala/docs/cluster/FactorialFrontend.scala +++ b/docs/src/test/scala/docs/cluster/FactorialFrontend.scala @@ -51,7 +51,7 @@ class FactorialFrontend(upToN: Int, repeat: Boolean) extends Actor with ActorLog def sendJobs(): Unit = { log.info("Starting batch of factorials up to [{}]", upToN) - (1 to upToN).foreach { backend ! _ } + (1 to upToN).foreach(backend ! _) } } //#frontend diff --git a/docs/src/test/scala/docs/cluster/SimpleClusterListener.scala b/docs/src/test/scala/docs/cluster/SimpleClusterListener.scala index b6add716be8..8fef317533f 100644 --- a/docs/src/test/scala/docs/cluster/SimpleClusterListener.scala +++ b/docs/src/test/scala/docs/cluster/SimpleClusterListener.scala @@ -24,11 +24,10 @@ class SimpleClusterListener extends Actor with ActorLogging { val cluster = Cluster(context.system) // subscribe to cluster changes, re-subscribe when restart - override def preStart(): Unit = { + override def preStart(): Unit = // #subscribe cluster.subscribe(self, initialStateMode = InitialStateAsEvents, classOf[MemberEvent], classOf[UnreachableMember]) - // #subscribe - } + // #subscribe override def postStop(): Unit = cluster.unsubscribe(self) def receive = { diff --git a/docs/src/test/scala/docs/coordination/LeaseDocSpec.scala b/docs/src/test/scala/docs/coordination/LeaseDocSpec.scala index 7bf5266e8c7..f513f225b93 100644 --- a/docs/src/test/scala/docs/coordination/LeaseDocSpec.scala +++ b/docs/src/test/scala/docs/coordination/LeaseDocSpec.scala @@ -26,21 +26,17 @@ import org.apache.pekko.testkit.PekkoSpec //#lease-example class SampleLease(settings: LeaseSettings) extends Lease(settings) { - override def acquire(): Future[Boolean] = { + override def acquire(): Future[Boolean] = Future.successful(true) - } - override def acquire(leaseLostCallback: Option[Throwable] => Unit): Future[Boolean] = { + override def acquire(leaseLostCallback: Option[Throwable] => Unit): Future[Boolean] = Future.successful(true) - } - override def release(): Future[Boolean] = { + override def release(): Future[Boolean] = Future.successful(true) - } - override def checkLease(): Boolean = { + override def checkLease(): Boolean = true - } } //#lease-example diff --git a/docs/src/test/scala/docs/ddata/protobuf/TwoPhaseSetSerializer.scala b/docs/src/test/scala/docs/ddata/protobuf/TwoPhaseSetSerializer.scala index 44931d3ac3a..796923c3efc 100644 --- a/docs/src/test/scala/docs/ddata/protobuf/TwoPhaseSetSerializer.scala +++ b/docs/src/test/scala/docs/ddata/protobuf/TwoPhaseSetSerializer.scala @@ -36,9 +36,8 @@ class TwoPhaseSetSerializer(val system: ExtendedActorSystem) extends Serializer case _ => throw new IllegalArgumentException(s"Can't serialize object of type ${obj.getClass}") } - override def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]]): AnyRef = { + override def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]]): AnyRef = twoPhaseSetFromBinary(bytes) - } def twoPhaseSetToProto(twoPhaseSet: TwoPhaseSet): TwoPhaseSetMessages.TwoPhaseSet = { val b = TwoPhaseSetMessages.TwoPhaseSet.newBuilder() @@ -78,8 +77,7 @@ class TwoPhaseSetSerializerWithCompression(system: ExtendedActorSystem) extends case _ => throw new IllegalArgumentException(s"Can't serialize object of type ${obj.getClass}") } - override def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]]): AnyRef = { + override def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]]): AnyRef = twoPhaseSetFromBinary(decompress(bytes)) - } // #compression } diff --git a/docs/src/test/scala/docs/ddata/protobuf/TwoPhaseSetSerializer2.scala b/docs/src/test/scala/docs/ddata/protobuf/TwoPhaseSetSerializer2.scala index 89eae2ae9f5..f217a7c827e 100644 --- a/docs/src/test/scala/docs/ddata/protobuf/TwoPhaseSetSerializer2.scala +++ b/docs/src/test/scala/docs/ddata/protobuf/TwoPhaseSetSerializer2.scala @@ -33,9 +33,8 @@ class TwoPhaseSetSerializer2(val system: ExtendedActorSystem) extends Serializer case _ => throw new IllegalArgumentException(s"Can't serialize object of type ${obj.getClass}") } - override def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]]): AnyRef = { + override def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]]): AnyRef = twoPhaseSetFromBinary(bytes) - } def twoPhaseSetToProto(twoPhaseSet: TwoPhaseSet): TwoPhaseSetMessages.TwoPhaseSet2 = { val b = TwoPhaseSetMessages.TwoPhaseSet2.newBuilder() diff --git a/docs/src/test/scala/docs/dispatcher/MyUnboundedMailbox.scala b/docs/src/test/scala/docs/dispatcher/MyUnboundedMailbox.scala index 7b751956df2..0d50645c90d 100644 --- a/docs/src/test/scala/docs/dispatcher/MyUnboundedMailbox.scala +++ b/docs/src/test/scala/docs/dispatcher/MyUnboundedMailbox.scala @@ -37,11 +37,9 @@ object MyUnboundedMailbox { def dequeue(): Envelope = queue.poll() def numberOfMessages: Int = queue.size def hasMessages: Boolean = !queue.isEmpty - def cleanUp(owner: ActorRef, deadLetters: MessageQueue): Unit = { - while (hasMessages) { + def cleanUp(owner: ActorRef, deadLetters: MessageQueue): Unit = + while (hasMessages) deadLetters.enqueue(owner, dequeue()) - } - } } } @@ -51,10 +49,9 @@ class MyUnboundedMailbox extends MailboxType with ProducesMessageQueue[MyUnbound import MyUnboundedMailbox._ // This constructor signature must exist, it will be called by Pekko - def this(settings: ActorSystem.Settings, config: Config) = { + def this(settings: ActorSystem.Settings, config: Config) = // put your initialization code here this() - } // The create method is called to create the MessageQueue final override def create(owner: Option[ActorRef], system: Option[ActorSystem]): MessageQueue = diff --git a/docs/src/test/scala/docs/event/EventBusDocSpec.scala b/docs/src/test/scala/docs/event/EventBusDocSpec.scala index a52c069b660..e4a75d35994 100644 --- a/docs/src/test/scala/docs/event/EventBusDocSpec.scala +++ b/docs/src/test/scala/docs/event/EventBusDocSpec.scala @@ -41,9 +41,8 @@ object EventBusDocSpec { // will be invoked for each event for all subscribers which registered themselves // for the event’s classifier - override protected def publish(event: Event, subscriber: Subscriber): Unit = { + override protected def publish(event: Event, subscriber: Subscriber): Unit = subscriber ! event.payload - } // must define a full order over the subscribers, expressed as expected from // `java.lang.Comparable.compare` @@ -90,9 +89,8 @@ object EventBusDocSpec { // will be invoked for each event for all subscribers which registered // themselves for the event’s classifier - override protected def publish(event: Event, subscriber: Subscriber): Unit = { + override protected def publish(event: Event, subscriber: Subscriber): Unit = subscriber ! event.payload - } } // #subchannel-bus @@ -124,9 +122,8 @@ object EventBusDocSpec { // will be invoked for each event for all subscribers which registered themselves // for a classifier matching this event - override protected def publish(event: Event, subscriber: Subscriber): Unit = { + override protected def publish(event: Event, subscriber: Subscriber): Unit = subscriber ! event - } } // #scanning-bus diff --git a/docs/src/test/scala/docs/event/LoggingDocSpec.scala b/docs/src/test/scala/docs/event/LoggingDocSpec.scala index cc36f7957f1..9239f1ec15f 100644 --- a/docs/src/test/scala/docs/event/LoggingDocSpec.scala +++ b/docs/src/test/scala/docs/event/LoggingDocSpec.scala @@ -24,12 +24,10 @@ object LoggingDocSpec { class MyActor extends Actor { val log = Logging(context.system, this) - override def preStart() = { + override def preStart() = log.debug("Starting") - } - override def preRestart(reason: Throwable, message: Option[Any]): Unit = { + override def preRestart(reason: Throwable, message: Option[Any]): Unit = log.error(reason, "Restarting due to [{}] when processing [{}]", reason.getMessage, message.getOrElse("")) - } def receive = { case "test" => log.info("Received test") case x => log.warning("Received unknown message: {}", x) @@ -43,7 +41,7 @@ object LoggingDocSpec { val log = Logging(this) def receive = { - case _ => { + case _ => // #mdc val mdc = Map("requestId" -> 1234, "visitorId" -> 5678) log.mdc(mdc) @@ -52,8 +50,7 @@ object LoggingDocSpec { log.info("Starting new request") log.clearMDC() - // #mdc - } + // #mdc } } @@ -76,9 +73,8 @@ object LoggingDocSpec { } def receive: Receive = { - case r: Req => { + case r: Req => log.info(s"Starting new request: ${r.work}") - } } } diff --git a/docs/src/test/scala/docs/extension/SettingsExtensionDocSpec.scala b/docs/src/test/scala/docs/extension/SettingsExtensionDocSpec.scala index 105924f0f01..11a356af714 100644 --- a/docs/src/test/scala/docs/extension/SettingsExtensionDocSpec.scala +++ b/docs/src/test/scala/docs/extension/SettingsExtensionDocSpec.scala @@ -82,9 +82,8 @@ object SettingsExtensionDocSpec { case someMessage => } - def connect(dbUri: String, circuitBreakerTimeout: Duration) = { + def connect(dbUri: String, circuitBreakerTimeout: Duration) = "dummy" - } } } diff --git a/docs/src/test/scala/docs/future/FutureDocSpec.scala b/docs/src/test/scala/docs/future/FutureDocSpec.scala index e6dfd16a560..69b76ad8120 100644 --- a/docs/src/test/scala/docs/future/FutureDocSpec.scala +++ b/docs/src/test/scala/docs/future/FutureDocSpec.scala @@ -423,8 +423,8 @@ class FutureDocSpec extends PekkoSpec { } "demonstrate usage of zip" in { - val future1 = Future { "foo" } - val future2 = Future { "bar" } + val future1 = Future("foo") + val future2 = Future("bar") // #zip val future3 = future1.zip(future2).map { case (a, b) => a + " " + b } future3.foreach(println) @@ -438,7 +438,7 @@ class FutureDocSpec extends PekkoSpec { def log(cause: Throwable) = () def watchSomeTV(): Unit = () // #and-then - val result = Future { loadPage(url) } + val result = Future(loadPage(url)) .andThen { case Failure(exception) => log(exception) } @@ -451,9 +451,9 @@ class FutureDocSpec extends PekkoSpec { } "demonstrate usage of fallbackTo" in { - val future1 = Future { "foo" } - val future2 = Future { "bar" } - val future3 = Future { "pigdog" } + val future1 = Future("foo") + val future2 = Future("bar") + val future3 = Future("pigdog") // #fallback-to val future4 = future1.fallbackTo(future2).fallbackTo(future3) future4.foreach(println) @@ -462,7 +462,7 @@ class FutureDocSpec extends PekkoSpec { } "demonstrate usage of onComplete" in { - val future = Future { "foo" } + val future = Future("foo") def doSomethingOnSuccess(r: String) = () def doSomethingOnFailure(t: Throwable) = () // #onComplete @@ -487,7 +487,7 @@ class FutureDocSpec extends PekkoSpec { promise.success("hello") // #promise Await.result(future, 3 seconds) should be("Yay!") - intercept[IllegalArgumentException] { Await.result(otherFuture, 3 seconds) } + intercept[IllegalArgumentException](Await.result(otherFuture, 3 seconds)) Await.result(theFuture, 3 seconds) should be("hello") } @@ -501,7 +501,7 @@ class FutureDocSpec extends PekkoSpec { val future = Future { Thread.sleep(1000); "foo" } val result = Future.firstCompletedOf(Seq(future, delayed)) // #after - intercept[IllegalStateException] { Await.result(result, 2 second) } + intercept[IllegalStateException](Await.result(result, 2 second)) } "demonstrate pattern.retry" in { @@ -515,12 +515,11 @@ class FutureDocSpec extends PekkoSpec { // Given some future that will succeed eventually @volatile var failCount = 0 - def futureToAttempt() = { + def futureToAttempt() = if (failCount < 5) { failCount += 1 Future.failed(new IllegalStateException(failCount.toString)) } else Future.successful(5) - } // Return a new future that will retry up to 10 times val retried: Future[Int] = pekko.pattern.retry(() => futureToAttempt(), attempts = 10, 100 milliseconds) diff --git a/docs/src/test/scala/docs/io/EchoServer.scala b/docs/src/test/scala/docs/io/EchoServer.scala index 0df40557238..26328c5bfd3 100644 --- a/docs/src/test/scala/docs/io/EchoServer.scala +++ b/docs/src/test/scala/docs/io/EchoServer.scala @@ -44,9 +44,8 @@ class EchoManager(handlerClass: Class[_]) extends Actor with ActorLogging { override val supervisorStrategy = SupervisorStrategy.stoppingStrategy // bind to the listen port; the port will automatically be closed once this actor dies - override def preStart(): Unit = { + override def preStart(): Unit = IO(Tcp) ! Bind(self, new InetSocketAddress("localhost", 0)) - } // do not restart override def postRestart(thr: Throwable): Unit = context.stop(self) @@ -155,9 +154,8 @@ class EchoHandler(connection: ActorRef, remote: InetSocketAddress) extends Actor } // #closing - override def postStop(): Unit = { + override def postStop(): Unit = log.info(s"transferred $transferred bytes from/to [$remote]") - } // #storage-omitted private var storageOffset = 0 @@ -207,15 +205,12 @@ class EchoHandler(connection: ActorRef, remote: InetSocketAddress) extends Actor } // #helpers - private def writeFirst(): Unit = { + private def writeFirst(): Unit = connection ! Write(storage(0), Ack(storageOffset)) - } - private def writeAll(): Unit = { - for ((data, i) <- storage.zipWithIndex) { + private def writeAll(): Unit = + for ((data, i) <- storage.zipWithIndex) connection ! Write(data, Ack(storageOffset + i)) - } - } // #storage-omitted } @@ -246,9 +241,8 @@ class SimpleEchoHandler(connection: ActorRef, remote: InetSocketAddress) extends } // #storage-omitted - override def postStop(): Unit = { + override def postStop(): Unit = log.info(s"transferred $transferred bytes from/to [$remote]") - } var storage = Vector.empty[ByteString] var stored = 0L diff --git a/docs/src/test/scala/docs/io/ScalaUdpMulticast.scala b/docs/src/test/scala/docs/io/ScalaUdpMulticast.scala index c1d4752e19a..254c9624915 100644 --- a/docs/src/test/scala/docs/io/ScalaUdpMulticast.scala +++ b/docs/src/test/scala/docs/io/ScalaUdpMulticast.scala @@ -62,10 +62,9 @@ class Sender(iface: String, group: String, port: Int, msg: String) extends Actor IO(Udp) ! Udp.SimpleSender(List(Inet6ProtocolFamily())) def receive = { - case Udp.SimpleSenderReady => { + case Udp.SimpleSenderReady => val remote = new InetSocketAddress(s"$group%$iface", port) log.info("Sending message to {}", remote) sender() ! Udp.Send(ByteString(msg), remote) - } } } diff --git a/docs/src/test/scala/docs/io/ScalaUdpMulticastSpec.scala b/docs/src/test/scala/docs/io/ScalaUdpMulticastSpec.scala index 0f866edd6f5..fa25a356e37 100644 --- a/docs/src/test/scala/docs/io/ScalaUdpMulticastSpec.scala +++ b/docs/src/test/scala/docs/io/ScalaUdpMulticastSpec.scala @@ -76,10 +76,9 @@ class ScalaUdpMulticastSpec system.log.info("Failed to run test on interface {}", ipv6iface.getDisplayName) failures = ex :: failures - } finally { + } finally // unbind system.stop(listener) - } } if (failures.size == ipv6ifaces.size) @@ -89,8 +88,7 @@ class ScalaUdpMulticastSpec } } - override def afterAll(): Unit = { + override def afterAll(): Unit = TestKit.shutdownActorSystem(system) - } } diff --git a/docs/src/test/scala/docs/persistence/PersistenceDocSpec.scala b/docs/src/test/scala/docs/persistence/PersistenceDocSpec.scala index da694744690..d19ada1942e 100644 --- a/docs/src/test/scala/docs/persistence/PersistenceDocSpec.scala +++ b/docs/src/test/scala/docs/persistence/PersistenceDocSpec.scala @@ -220,7 +220,7 @@ object PersistenceDocSpec { } override def receiveCommand: Receive = { - case c: String => { + case c: String => sender() ! c persistAsync(s"evt-$c-1") { e => sender() ! e @@ -228,7 +228,6 @@ object PersistenceDocSpec { persistAsync(s"evt-$c-2") { e => sender() ! e } - } } } @@ -259,7 +258,7 @@ object PersistenceDocSpec { } override def receiveCommand: Receive = { - case c: String => { + case c: String => sender() ! c persistAsync(s"evt-$c-1") { e => sender() ! e @@ -270,7 +269,6 @@ object PersistenceDocSpec { deferAsync(s"evt-$c-3") { e => sender() ! e } - } } } // #defer @@ -303,7 +301,7 @@ object PersistenceDocSpec { } override def receiveCommand: Receive = { - case c: String => { + case c: String => sender() ! c persist(s"evt-$c-1") { e => sender() ! e @@ -314,7 +312,6 @@ object PersistenceDocSpec { defer(s"evt-$c-3") { e => sender() ! e } - } } } // #defer-with-persist @@ -432,7 +429,7 @@ object PersistenceDocSpec { override def receiveCommand: Receive = { case c: String => println(c) - persist(s"handle-$c") { println(_) } + persist(s"handle-$c")(println(_)) case Shutdown => context.stop(self) } diff --git a/docs/src/test/scala/docs/persistence/PersistenceEventAdapterDocSpec.scala b/docs/src/test/scala/docs/persistence/PersistenceEventAdapterDocSpec.scala index 3fadeb9aac4..de249a0a967 100644 --- a/docs/src/test/scala/docs/persistence/PersistenceEventAdapterDocSpec.scala +++ b/docs/src/test/scala/docs/persistence/PersistenceEventAdapterDocSpec.scala @@ -231,13 +231,12 @@ class MyTaggingEventAdapter(system: ExtendedActorSystem) extends EventAdapter { case j: MyTaggingJournalModel => EventSeq.single(j) } - override def toJournal(event: Any): Any = { + override def toJournal(event: Any): Any = event match { case Person(_, age) if age >= 18 => MyTaggingJournalModel(event, tags = Set("adult")) case Person(_, age) => MyTaggingJournalModel(event, tags = Set("minor")) case _ => MyTaggingJournalModel(event, tags = Set.empty) } - } } object v1 { diff --git a/docs/src/test/scala/docs/persistence/PersistencePluginDocSpec.scala b/docs/src/test/scala/docs/persistence/PersistencePluginDocSpec.scala index b86a72e99d6..bc400748853 100644 --- a/docs/src/test/scala/docs/persistence/PersistencePluginDocSpec.scala +++ b/docs/src/test/scala/docs/persistence/PersistencePluginDocSpec.scala @@ -107,11 +107,10 @@ class PersistencePluginDocSpec extends AnyWordSpec { ConfigFactory .parseString(providerConfig) .withFallback(ConfigFactory.parseString(PersistencePluginDocSpec.config))) - try { + try Persistence(system) - } finally { + finally TestKit.shutdownActorSystem(system, 10.seconds, false) - } } } @@ -137,9 +136,8 @@ object SharedLeveldbPluginDocSpec { // #shared-store-usage trait SharedStoreUsage extends Actor { - override def preStart(): Unit = { + override def preStart(): Unit = context.actorSelection("pekko://example@127.0.0.1:7355/user/store") ! Identify(1) - } def receive = { case ActorIdentity(1, Some(store)) => diff --git a/docs/src/test/scala/docs/persistence/PersistenceSchemaEvolutionDocSpec.scala b/docs/src/test/scala/docs/persistence/PersistenceSchemaEvolutionDocSpec.scala index 3709de62e3f..725160c3df9 100644 --- a/docs/src/test/scala/docs/persistence/PersistenceSchemaEvolutionDocSpec.scala +++ b/docs/src/test/scala/docs/persistence/PersistenceSchemaEvolutionDocSpec.scala @@ -46,11 +46,10 @@ class PersistenceSchemaEvolutionDocSpec extends AnyWordSpec { """ val system = ActorSystem("PersistenceSchemaEvolutionDocSpec", ConfigFactory.parseString(customSerializerConfig)) - try { + try SerializationExtension(system) - } finally { + finally TestKit.shutdownActorSystem(system, 10.seconds, false) - } } diff --git a/docs/src/test/scala/docs/persistence/PersistenceSerializerDocSpec.scala b/docs/src/test/scala/docs/persistence/PersistenceSerializerDocSpec.scala index 819151b36b6..4e45b1f9a14 100644 --- a/docs/src/test/scala/docs/persistence/PersistenceSerializerDocSpec.scala +++ b/docs/src/test/scala/docs/persistence/PersistenceSerializerDocSpec.scala @@ -40,11 +40,10 @@ class PersistenceSerializerDocSpec extends AnyWordSpec { """ val system = ActorSystem("PersistenceSerializerDocSpec", ConfigFactory.parseString(customSerializerConfig)) - try { + try SerializationExtension(system) - } finally { + finally TestKit.shutdownActorSystem(system, 10.seconds, false) - } } class MyPayload diff --git a/docs/src/test/scala/docs/persistence/query/MyEventsByTagSource.scala b/docs/src/test/scala/docs/persistence/query/MyEventsByTagSource.scala index 541860b4e8c..91ccc8d0d10 100644 --- a/docs/src/test/scala/docs/persistence/query/MyEventsByTagSource.scala +++ b/docs/src/test/scala/docs/persistence/query/MyEventsByTagSource.scala @@ -40,9 +40,8 @@ class MyEventsByTagSource(tag: String, offset: Long, refreshInterval: FiniteDura private var buf = Vector.empty[EventEnvelope] private val serialization = SerializationExtension(system) - override def preStart(): Unit = { + override def preStart(): Unit = scheduleWithFixedDelay(Continue, refreshInterval, refreshInterval) - } override def onPull(): Unit = { query() @@ -53,23 +52,21 @@ class MyEventsByTagSource(tag: String, offset: Long, refreshInterval: FiniteDura // close connection if responsible for doing so } - private def query(): Unit = { + private def query(): Unit = if (buf.isEmpty) { - try { + try buf = Select.run(tag, currentOffset, Limit) - } catch { + catch { case NonFatal(e) => failStage(e) } } - } - private def tryPush(): Unit = { + private def tryPush(): Unit = if (buf.nonEmpty && isAvailable(out)) { push(out, buf.head) buf = buf.tail } - } override protected def onTimer(timerKey: Any): Unit = timerKey match { case Continue => diff --git a/docs/src/test/scala/docs/persistence/query/PersistenceQueryDocSpec.scala b/docs/src/test/scala/docs/persistence/query/PersistenceQueryDocSpec.scala index 66962a6ee54..1c439e93bc9 100644 --- a/docs/src/test/scala/docs/persistence/query/PersistenceQueryDocSpec.scala +++ b/docs/src/test/scala/docs/persistence/query/PersistenceQueryDocSpec.scala @@ -89,29 +89,25 @@ object PersistenceQueryDocSpec { override def eventsByPersistenceId( persistenceId: String, fromSequenceNr: Long, - toSequenceNr: Long): Source[EventEnvelope, NotUsed] = { + toSequenceNr: Long): Source[EventEnvelope, NotUsed] = // implement in a similar way as eventsByTag ??? - } - override def persistenceIds(): Source[String, NotUsed] = { + override def persistenceIds(): Source[String, NotUsed] = // implement in a similar way as eventsByTag ??? - } - override def currentPersistenceIds(): Source[String, NotUsed] = { + override def currentPersistenceIds(): Source[String, NotUsed] = // implement in a similar way as eventsByTag ??? - } // possibility to add more plugin specific queries // #advanced-journal-query-definition - def byTagsWithMeta(tags: Set[String]): Source[RichEvent, QueryMetadata] = { + def byTagsWithMeta(tags: Set[String]): Source[RichEvent, QueryMetadata] = // #advanced-journal-query-definition // implement in a similar way as eventsByTag ??? - } } diff --git a/docs/src/test/scala/docs/persistence/testkit/TestKitExamples.scala b/docs/src/test/scala/docs/persistence/testkit/TestKitExamples.scala index 7dde5a7ffdc..ac80d0d99a2 100644 --- a/docs/src/test/scala/docs/persistence/testkit/TestKitExamples.scala +++ b/docs/src/test/scala/docs/persistence/testkit/TestKitExamples.scala @@ -46,9 +46,8 @@ class PersistenceTestKitSampleSpec val persistenceTestKit = PersistenceTestKit(system) - override def beforeEach(): Unit = { + override def beforeEach(): Unit = persistenceTestKit.clearAll() - } "Persistent actor" should { diff --git a/docs/src/test/scala/docs/remoting/RemoteDeploymentDocSpec.scala b/docs/src/test/scala/docs/remoting/RemoteDeploymentDocSpec.scala index 945ad8b5da7..1cb2801c003 100644 --- a/docs/src/test/scala/docs/remoting/RemoteDeploymentDocSpec.scala +++ b/docs/src/test/scala/docs/remoting/RemoteDeploymentDocSpec.scala @@ -42,7 +42,7 @@ class RemoteDeploymentDocSpec extends PekkoSpec(""" val address = other.asInstanceOf[ExtendedActorSystem].provider.getExternalAddressFor(Address("pekko", "s", "host", 1)).get - override def afterTermination(): Unit = { shutdown(other) } + override def afterTermination(): Unit = shutdown(other) "demonstrate programmatic deployment" in { // #deploy diff --git a/docs/src/test/scala/docs/routing/RouterDocSpec.scala b/docs/src/test/scala/docs/routing/RouterDocSpec.scala index 27c9c652504..cd43f671187 100644 --- a/docs/src/test/scala/docs/routing/RouterDocSpec.scala +++ b/docs/src/test/scala/docs/routing/RouterDocSpec.scala @@ -407,7 +407,7 @@ router-dispatcher {} context.actorOf(BalancingPool(20).props(Props[Worker]()), "router10b") // #balancing-pool-3 for (i <- 1 to 100) router10b ! i - val threads10b = Thread.getAllStackTraces.keySet.asScala.filter { _.getName contains "router10b" } + val threads10b = Thread.getAllStackTraces.keySet.asScala.filter(_.getName contains "router10b") val threads10bNr = threads10b.size require( threads10bNr == 5, diff --git a/docs/src/test/scala/docs/serialization/SerializationDocSpec.scala b/docs/src/test/scala/docs/serialization/SerializationDocSpec.scala index ab58efde98c..6d5ff9f3f83 100644 --- a/docs/src/test/scala/docs/serialization/SerializationDocSpec.scala +++ b/docs/src/test/scala/docs/serialization/SerializationDocSpec.scala @@ -44,21 +44,19 @@ package docs.serialization { def identifier = 1234567 // "toBinary" serializes the given object to an Array of Bytes - def toBinary(obj: AnyRef): Array[Byte] = { + def toBinary(obj: AnyRef): Array[Byte] = // Put the code that serializes the object here // #... Array[Byte]() - // #... - } + // #... // "fromBinary" deserializes the given array, // using the type hint (if any, see "includeManifest" above) - def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]]): AnyRef = { + def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]]): AnyRef = // Put your code that deserializes here // #... null - // #... - } + // #... } // #my-own-serializer @@ -83,17 +81,16 @@ package docs.serialization { } // "toBinary" serializes the given object to an Array of Bytes - def toBinary(obj: AnyRef): Array[Byte] = { + def toBinary(obj: AnyRef): Array[Byte] = // Put the real code that serializes the object here obj match { case Customer(name) => name.getBytes(UTF_8) case User(name) => name.getBytes(UTF_8) } - } // "fromBinary" deserializes the given array, // using the type hint - def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = { + def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = // Put the real code that deserializes here manifest match { case CustomerManifest => @@ -101,7 +98,6 @@ package docs.serialization { case UserManifest => User(new String(bytes, UTF_8)) } - } } // #my-own-serializer2 diff --git a/docs/src/test/scala/docs/stream/BidiFlowDocSpec.scala b/docs/src/test/scala/docs/stream/BidiFlowDocSpec.scala index d83df2a17a2..0eba8986af2 100644 --- a/docs/src/test/scala/docs/stream/BidiFlowDocSpec.scala +++ b/docs/src/test/scala/docs/stream/BidiFlowDocSpec.scala @@ -89,10 +89,9 @@ object BidiFlowDocSpec { setHandler(out, new OutHandler { - override def onPull(): Unit = { + override def onPull(): Unit = if (isClosed(in)) run() else pull(in) - } }) setHandler(in, new InHandler { @@ -102,17 +101,16 @@ object BidiFlowDocSpec { run() } - override def onUpstreamFinish(): Unit = { + override def onUpstreamFinish(): Unit = // either we are done if (stash.isEmpty) completeStage() // or we still have bytes to emit // wait with completion and let run() complete when the // rest of the stash has been sent downstream else if (isAvailable(out)) run() - } }) - private def run(): Unit = { + private def run(): Unit = if (needed == -1) { // are we at a boundary? then figure out next length if (stash.length < 4) { @@ -135,7 +133,6 @@ object BidiFlowDocSpec { needed = -1 push(out, emit) } - } } } diff --git a/docs/src/test/scala/docs/stream/GraphDSLDocSpec.scala b/docs/src/test/scala/docs/stream/GraphDSLDocSpec.scala index 5d7c2045d12..fa4e4f3faf4 100644 --- a/docs/src/test/scala/docs/stream/GraphDSLDocSpec.scala +++ b/docs/src/test/scala/docs/stream/GraphDSLDocSpec.scala @@ -127,8 +127,7 @@ class GraphDSLDocSpec extends PekkoSpec { object PriorityWorkerPool { def apply[In, Out]( worker: Flow[In, Out, Any], - workerCount: Int): Graph[PriorityWorkerPoolShape[In, Out], NotUsed] = { - + workerCount: Int): Graph[PriorityWorkerPoolShape[In, Out], NotUsed] = GraphDSL.create() { implicit b => import GraphDSL.Implicits._ @@ -153,8 +152,6 @@ class GraphDSLDocSpec extends PekkoSpec { resultsOut = resultsMerge.out) } - } - } // #graph-dsl-components-create diff --git a/docs/src/test/scala/docs/stream/GraphStageDocSpec.scala b/docs/src/test/scala/docs/stream/GraphStageDocSpec.scala index a50dda3c658..c07055ccbce 100644 --- a/docs/src/test/scala/docs/stream/GraphStageDocSpec.scala +++ b/docs/src/test/scala/docs/stream/GraphStageDocSpec.scala @@ -143,15 +143,13 @@ class GraphStageDocSpec extends PekkoSpec { new GraphStageLogic(shape) { setHandler(in, new InHandler { - override def onPush(): Unit = { + override def onPush(): Unit = push(out, f(grab(in))) - } }) setHandler(out, new OutHandler { - override def onPull(): Unit = { + override def onPull(): Unit = pull(in) - } }) } } @@ -187,9 +185,8 @@ class GraphStageDocSpec extends PekkoSpec { }) setHandler(out, new OutHandler { - override def onPull(): Unit = { + override def onPull(): Unit = pull(in) - } }) } } @@ -236,14 +233,13 @@ class GraphStageDocSpec extends PekkoSpec { }) setHandler(out, new OutHandler { - override def onPull(): Unit = { + override def onPull(): Unit = if (lastElem.isDefined) { push(out, lastElem.get) lastElem = None } else { pull(in) } - } }) } } @@ -282,9 +278,8 @@ class GraphStageDocSpec extends PekkoSpec { }) setHandler(out, new OutHandler { - override def onPull(): Unit = { + override def onPull(): Unit = pull(in) - } }) } } @@ -336,11 +331,11 @@ class GraphStageDocSpec extends PekkoSpec { setHandler(in, new InHandler { - override def onPush(): Unit = { push(out, grab(in)) } + override def onPush(): Unit = push(out, grab(in)) }) setHandler(out, new OutHandler { - override def onPull(): Unit = { pull(in) } + override def onPull(): Unit = pull(in) }) } } @@ -405,12 +400,11 @@ class GraphStageDocSpec extends PekkoSpec { }) setHandler(out, new OutHandler { - override def onPull(): Unit = { pull(in) } + override def onPull(): Unit = pull(in) }) - override protected def onTimer(timerKey: Any): Unit = { + override protected def onTimer(timerKey: Any): Unit = open = false - } } } // #timed @@ -449,18 +443,16 @@ class GraphStageDocSpec extends PekkoSpec { // replace handler with one that only forwards elements setHandler(in, new InHandler { - override def onPush(): Unit = { + override def onPush(): Unit = push(out, grab(in)) - } }) } }) setHandler(out, new OutHandler { - override def onPull(): Unit = { + override def onPull(): Unit = pull(in) - } }) } @@ -496,11 +488,10 @@ class GraphStageDocSpec extends PekkoSpec { def bufferFull = buffer.size == 2 var downstreamWaiting = false - override def preStart(): Unit = { + override def preStart(): Unit = // a detached stage needs to start upstream demand // itself as it is not triggered by downstream demand pull(in) - } setHandler( in, diff --git a/docs/src/test/scala/docs/stream/IntegrationDocSpec.scala b/docs/src/test/scala/docs/stream/IntegrationDocSpec.scala index 95b5a201f06..f137db7e447 100644 --- a/docs/src/test/scala/docs/stream/IntegrationDocSpec.scala +++ b/docs/src/test/scala/docs/stream/IntegrationDocSpec.scala @@ -86,12 +86,11 @@ object IntegrationDocSpec { class SmsServer(probe: ActorRef) { // #sms-server-send - def send(text: TextMessage): Unit = { + def send(text: TextMessage): Unit = // ... // #sms-server-send probe ! text.to - // #sms-server-send - } + // #sms-server-send // #sms-server-send } @@ -181,9 +180,9 @@ class IntegrationDocSpec extends PekkoSpec(IntegrationDocSpec.config) { // #send-emails val sendEmails: RunnableGraph[NotUsed] = emailAddresses - .mapAsync(4)(address => { + .mapAsync(4) { address => emailServer.send(Email(to = address, title = "pekko", body = "I like your tweet")) - }) + } .to(Sink.ignore) sendEmails.run() @@ -294,9 +293,9 @@ class IntegrationDocSpec extends PekkoSpec(IntegrationDocSpec.config) { val sendEmails: RunnableGraph[NotUsed] = emailAddresses - .mapAsyncUnordered(4)(address => { + .mapAsyncUnordered(4) { address => emailServer.send(Email(to = address, title = "Pekko", body = "I like your tweet")) - }) + } .to(Sink.ignore) sendEmails.run() @@ -330,11 +329,11 @@ class IntegrationDocSpec extends PekkoSpec(IntegrationDocSpec.config) { val sendTextMessages: RunnableGraph[NotUsed] = phoneNumbers - .mapAsync(4)(phoneNo => { + .mapAsync(4) { phoneNo => Future { smsServer.send(TextMessage(to = phoneNo, body = "I like your tweet")) }(blockingExecutionContext) - }) + } .to(Sink.ignore) sendTextMessages.run() @@ -411,17 +410,16 @@ class IntegrationDocSpec extends PekkoSpec(IntegrationDocSpec.config) { "illustrate ordering and parallelism of mapAsync" in { val probe = TestProbe() - def println(s: String): Unit = { + def println(s: String): Unit = if (s.startsWith("after:")) probe.ref ! s - } // #sometimes-slow-mapAsync implicit val blockingExecutionContext = system.dispatchers.lookup("blocking-dispatcher") val service = new SometimesSlowService Source(List("a", "B", "C", "D", "e", "F", "g", "H", "i", "J")) - .map(elem => { println(s"before: $elem"); elem }) + .map { elem => println(s"before: $elem"); elem } .mapAsync(4)(service.convert) .to(Sink.foreach(elem => println(s"after: $elem"))) .withAttributes(Attributes.inputBuffer(initial = 4, max = 4)) @@ -442,17 +440,16 @@ class IntegrationDocSpec extends PekkoSpec(IntegrationDocSpec.config) { "illustrate ordering and parallelism of mapAsyncUnordered" in { val probe = TestProbe() - def println(s: String): Unit = { + def println(s: String): Unit = if (s.startsWith("after:")) probe.ref ! s - } // #sometimes-slow-mapAsyncUnordered implicit val blockingExecutionContext = system.dispatchers.lookup("blocking-dispatcher") val service = new SometimesSlowService Source(List("a", "B", "C", "D", "e", "F", "g", "H", "i", "J")) - .map(elem => { println(s"before: $elem"); elem }) + .map { elem => println(s"before: $elem"); elem } .mapAsyncUnordered(4)(service.convert) .to(Sink.foreach(elem => println(s"after: $elem"))) .withAttributes(Attributes.inputBuffer(initial = 4, max = 4)) @@ -489,14 +486,14 @@ class IntegrationDocSpec extends PekkoSpec(IntegrationDocSpec.config) { implicit val ec = system.dispatcher source - .map(x => { + .map { x => queue.offer(x).map { case QueueOfferResult.Enqueued => println(s"enqueued $x") case QueueOfferResult.Dropped => println(s"dropped $x") case QueueOfferResult.Failure(ex) => println(s"Offer failed ${ex.getMessage}") case QueueOfferResult.QueueClosed => println("Source Queue closed") } - }) + } .runWith(Sink.ignore) // #source-queue } diff --git a/docs/src/test/scala/docs/stream/MigrationsScala.scala b/docs/src/test/scala/docs/stream/MigrationsScala.scala index 41044e93250..803ab652d26 100644 --- a/docs/src/test/scala/docs/stream/MigrationsScala.scala +++ b/docs/src/test/scala/docs/stream/MigrationsScala.scala @@ -25,13 +25,13 @@ class MigrationsScala extends PekkoSpec { Flow[Int].expand(Iterator.continually(_)) // #expand-continually // #expand-state - Flow[Int].expand(i => { + Flow[Int].expand { i => var state = 0 Iterator.continually { state += 1 (i, state) } - }) + } // #expand-state // #async diff --git a/docs/src/test/scala/docs/stream/RateTransformationDocSpec.scala b/docs/src/test/scala/docs/stream/RateTransformationDocSpec.scala index 221d2c1beb3..c8b36ce38e3 100644 --- a/docs/src/test/scala/docs/stream/RateTransformationDocSpec.scala +++ b/docs/src/test/scala/docs/stream/RateTransformationDocSpec.scala @@ -93,7 +93,7 @@ class RateTransformationDocSpec extends PekkoSpec { val driftFlow = Flow[Double].map(_ -> 0).extrapolate[(Double, Int)] { case (i, _) => Iterator.from(1).map(i -> _) } // #extrapolate-drift val latch = TestLatch(2) - val realDriftFlow = Flow[Double].map(d => { latch.countDown(); d -> 0; }).extrapolate[(Double, Int)] { + val realDriftFlow = Flow[Double].map { d => latch.countDown(); d -> 0; }.extrapolate[(Double, Int)] { case (d, _) => latch.countDown(); Iterator.from(1).map(d -> _) } @@ -116,7 +116,7 @@ class RateTransformationDocSpec extends PekkoSpec { val driftFlow = Flow[Double].expand(i => Iterator.from(0).map(i -> _)) // #expand-drift val latch = TestLatch(2) - val realDriftFlow = Flow[Double].expand(d => { latch.countDown(); Iterator.from(0).map(d -> _) }) + val realDriftFlow = Flow[Double].expand { d => latch.countDown(); Iterator.from(0).map(d -> _) } val (pub, sub) = TestSource.probe[Double].via(realDriftFlow).toMat(TestSink[(Double, Int)]())(Keep.both).run() diff --git a/docs/src/test/scala/docs/stream/SinkRecipeDocSpec.scala b/docs/src/test/scala/docs/stream/SinkRecipeDocSpec.scala index 6efd1886f92..a2a9bc8b379 100644 --- a/docs/src/test/scala/docs/stream/SinkRecipeDocSpec.scala +++ b/docs/src/test/scala/docs/stream/SinkRecipeDocSpec.scala @@ -21,7 +21,7 @@ import scala.concurrent.Future class SinkRecipeDocSpec extends RecipeSpec { "Sink.foreachAsync" must { "processing each element asynchronously" in { - def asyncProcessing(value: Int): Future[Unit] = Future { println(value) }(system.dispatcher) + def asyncProcessing(value: Int): Future[Unit] = Future(println(value))(system.dispatcher) // #forseachAsync-processing // def asyncProcessing(value: Int): Future[Unit] = _ diff --git a/docs/src/test/scala/docs/stream/SubstreamDocSpec.scala b/docs/src/test/scala/docs/stream/SubstreamDocSpec.scala index f3cf41e9d62..55d3a7aab6f 100644 --- a/docs/src/test/scala/docs/stream/SubstreamDocSpec.scala +++ b/docs/src/test/scala/docs/stream/SubstreamDocSpec.scala @@ -54,7 +54,7 @@ class SubstreamDocSpec extends PekkoSpec { "There is also the 3rd line\n" val charCount = Source(text.toList) - .splitAfter { _ == '\n' } + .splitAfter(_ == '\n') .filter(_ != '\n') .map(_ => 1) .reduce(_ + _) diff --git a/docs/src/test/scala/docs/stream/TwitterStreamQuickstartDocSpec.scala b/docs/src/test/scala/docs/stream/TwitterStreamQuickstartDocSpec.scala index b11217ad277..ec88f7dba0f 100644 --- a/docs/src/test/scala/docs/stream/TwitterStreamQuickstartDocSpec.scala +++ b/docs/src/test/scala/docs/stream/TwitterStreamQuickstartDocSpec.scala @@ -189,7 +189,7 @@ class TwitterStreamQuickstartDocSpec extends PekkoSpec { // #backpressure-by-readline val completion: Future[Done] = - Source(1 to 10).map(i => { println(s"map => $i"); i }).runForeach { i => + Source(1 to 10).map { i => println(s"map => $i"); i }.runForeach { i => readLine(s"Element = $i; continue reading? [press enter]\n") } diff --git a/docs/src/test/scala/docs/stream/cookbook/RecipeByteStrings.scala b/docs/src/test/scala/docs/stream/cookbook/RecipeByteStrings.scala index 505df9be31a..69554980d10 100644 --- a/docs/src/test/scala/docs/stream/cookbook/RecipeByteStrings.scala +++ b/docs/src/test/scala/docs/stream/cookbook/RecipeByteStrings.scala @@ -41,9 +41,8 @@ class RecipeByteStrings extends RecipeSpec { setHandler(out, new OutHandler { - override def onPull(): Unit = { + override def onPull(): Unit = emitChunk() - } }) setHandler( in, @@ -54,7 +53,7 @@ class RecipeByteStrings extends RecipeSpec { emitChunk() } - override def onUpstreamFinish(): Unit = { + override def onUpstreamFinish(): Unit = if (buffer.isEmpty) completeStage() else { // There are elements left in buffer, so @@ -65,10 +64,9 @@ class RecipeByteStrings extends RecipeSpec { // In that case we need to emit from the buffer. if (isAvailable(out)) emitChunk() } - } }) - private def emitChunk(): Unit = { + private def emitChunk(): Unit = if (buffer.isEmpty) { if (isClosed(in)) completeStage() else pull(in) @@ -77,7 +75,6 @@ class RecipeByteStrings extends RecipeSpec { buffer = nextBuffer push(out, chunk) } - } } } @@ -107,9 +104,8 @@ class RecipeByteStrings extends RecipeSpec { setHandlers(in, out, new InHandler with OutHandler { - override def onPull(): Unit = { + override def onPull(): Unit = pull(in) - } override def onPush(): Unit = { val chunk = grab(in) diff --git a/docs/src/test/scala/docs/stream/cookbook/RecipeGlobalRateLimit.scala b/docs/src/test/scala/docs/stream/cookbook/RecipeGlobalRateLimit.scala index 75e149c6a80..a4e88bcd33b 100644 --- a/docs/src/test/scala/docs/stream/cookbook/RecipeGlobalRateLimit.scala +++ b/docs/src/test/scala/docs/stream/cookbook/RecipeGlobalRateLimit.scala @@ -93,12 +93,12 @@ class RecipeGlobalRateLimit extends RecipeSpec { import org.apache.pekko import pekko.pattern.ask import pekko.util.Timeout - Flow[T].mapAsync(4)((element: T) => { + Flow[T].mapAsync(4) { (element: T) => import system.dispatcher implicit val triggerTimeout = Timeout(maxAllowedWait) val limiterTriggerFuture = limiter ? Limiter.WantToPass limiterTriggerFuture.map(_ => element) - }) + } } // #global-limiter-flow diff --git a/docs/src/test/scala/docs/stream/cookbook/RecipeHold.scala b/docs/src/test/scala/docs/stream/cookbook/RecipeHold.scala index 4303002f36c..021bf946c66 100644 --- a/docs/src/test/scala/docs/stream/cookbook/RecipeHold.scala +++ b/docs/src/test/scala/docs/stream/cookbook/RecipeHold.scala @@ -40,14 +40,12 @@ object HoldOps { pull(in) } - override def onPull(): Unit = { + override def onPull(): Unit = push(out, currentValue) - } }) - override def preStart(): Unit = { + override def preStart(): Unit = pull(in) - } } } @@ -80,14 +78,12 @@ object HoldOps { pull(in) } - override def onPull(): Unit = { + override def onPull(): Unit = if (!waitingFirstValue) push(out, currentValue) - } }) - override def preStart(): Unit = { + override def preStart(): Unit = pull(in) - } } } // #hold-version-2 diff --git a/docs/src/test/scala/docs/stream/cookbook/RecipeMissedTicks.scala b/docs/src/test/scala/docs/stream/cookbook/RecipeMissedTicks.scala index 856935b522b..ee8408dcf84 100644 --- a/docs/src/test/scala/docs/stream/cookbook/RecipeMissedTicks.scala +++ b/docs/src/test/scala/docs/stream/cookbook/RecipeMissedTicks.scala @@ -38,7 +38,7 @@ class RecipeMissedTicks extends RecipeSpec { // #missed-ticks val latch = TestLatch(3) val realMissedTicks: Flow[Tick, Int, NotUsed] = - Flow[Tick].conflateWithSeed(seed = _ => 0)((missedTicks, tick) => { latch.countDown(); missedTicks + 1 }) + Flow[Tick].conflateWithSeed(seed = _ => 0) { (missedTicks, tick) => latch.countDown(); missedTicks + 1 } tickStream.via(realMissedTicks).to(sink).run() diff --git a/docs/src/test/scala/docs/stream/cookbook/RecipeReduceByKey.scala b/docs/src/test/scala/docs/stream/cookbook/RecipeReduceByKey.scala index 4ae8cb2fb92..4140dbe56b6 100644 --- a/docs/src/test/scala/docs/stream/cookbook/RecipeReduceByKey.scala +++ b/docs/src/test/scala/docs/stream/cookbook/RecipeReduceByKey.scala @@ -50,14 +50,12 @@ class RecipeReduceByKey extends RecipeSpec { // #reduce-by-key-general def reduceByKey[In, K, Out](maximumGroupSize: Int, groupKey: (In) => K, map: (In) => Out)( - reduce: (Out, Out) => Out): Flow[In, (K, Out), NotUsed] = { - + reduce: (Out, Out) => Out): Flow[In, (K, Out), NotUsed] = Flow[In] .groupBy[K](maximumGroupSize, groupKey) .map(e => groupKey(e) -> map(e)) .reduce((l, r) => l._1 -> reduce(l._2, r._2)) .mergeSubstreams - } val wordCounts = words.via( reduceByKey(MaximumDistinctWords, groupKey = (word: String) => word, map = (word: String) => 1)( diff --git a/docs/src/test/scala/docs/stream/cookbook/RecipeSimpleDrop.scala b/docs/src/test/scala/docs/stream/cookbook/RecipeSimpleDrop.scala index 0f275a9391b..fcddefa7459 100644 --- a/docs/src/test/scala/docs/stream/cookbook/RecipeSimpleDrop.scala +++ b/docs/src/test/scala/docs/stream/cookbook/RecipeSimpleDrop.scala @@ -32,7 +32,7 @@ class RecipeSimpleDrop extends RecipeSpec { // #simple-drop val latch = TestLatch(2) val realDroppyStream = - Flow[Message].conflate((lastMessage, newMessage) => { latch.countDown(); newMessage }) + Flow[Message].conflate { (lastMessage, newMessage) => latch.countDown(); newMessage } val pub = TestPublisher.probe[Message]() val sub = TestSubscriber.manualProbe[Message]() diff --git a/docs/src/test/scala/docs/stream/cookbook/RecipeWorkerPool.scala b/docs/src/test/scala/docs/stream/cookbook/RecipeWorkerPool.scala index 20ab3636553..c37465935cc 100644 --- a/docs/src/test/scala/docs/stream/cookbook/RecipeWorkerPool.scala +++ b/docs/src/test/scala/docs/stream/cookbook/RecipeWorkerPool.scala @@ -38,11 +38,10 @@ class RecipeWorkerPool extends RecipeSpec { val balancer = b.add(Balance[In](workerCount, waitForAllDownstreams = true)) val merge = b.add(Merge[Out](workerCount)) - for (_ <- 1 to workerCount) { + for (_ <- 1 to workerCount) // for each worker, add an edge from the balancer to the worker, then wire // it to the merge element balancer ~> worker.async ~> merge - } FlowShape(balancer.in, merge.out) }) diff --git a/docs/src/test/scala/docs/stream/io/StreamTcpDocSpec.scala b/docs/src/test/scala/docs/stream/io/StreamTcpDocSpec.scala index 83546b3a10e..a28ce054f7c 100644 --- a/docs/src/test/scala/docs/stream/io/StreamTcpDocSpec.scala +++ b/docs/src/test/scala/docs/stream/io/StreamTcpDocSpec.scala @@ -110,12 +110,11 @@ class StreamTcpDocSpec extends PekkoSpec { import org.apache.pekko.stream.scaladsl.Framing val input = new AtomicReference("Hello world" :: "What a lovely day" :: Nil) - def readLine(prompt: String): String = { + def readLine(prompt: String): String = input.get() match { case all @ cmd :: tail if input.compareAndSet(all, tail) => cmd case _ => "q" } - } { // just for docs, never actually used diff --git a/docs/src/test/scala/docs/stream/operators/flow/StatefulMap.scala b/docs/src/test/scala/docs/stream/operators/flow/StatefulMap.scala index 29ae78f53b4..6255f818759 100644 --- a/docs/src/test/scala/docs/stream/operators/flow/StatefulMap.scala +++ b/docs/src/test/scala/docs/stream/operators/flow/StatefulMap.scala @@ -19,20 +19,19 @@ object StatefulMap { implicit val actorSystem: ActorSystem = ??? - def indexed(): Unit = { + def indexed(): Unit = // #zipWithIndex Source(List("A", "B", "C", "D")) .statefulMap(() => 0L)((index, elem) => (index + 1, (elem, index)), _ => None) .runForeach(println) - // prints - // (A,0) - // (B,1) - // (C,2) - // (D,3) - // #zipWithIndex - } + // prints + // (A,0) + // (B,1) + // (C,2) + // (D,3) + // #zipWithIndex - def bufferUntilChanged(): Unit = { + def bufferUntilChanged(): Unit = // #bufferUntilChanged Source("A" :: "B" :: "B" :: "C" :: "C" :: "C" :: "D" :: Nil) .statefulMap(() => List.empty[String])( @@ -44,15 +43,14 @@ object StatefulMap { buffer => Some(buffer)) .filter(_.nonEmpty) .runForeach(println) - // prints - // List(A) - // List(B, B) - // List(C, C, C) - // List(D) - // #bufferUntilChanged - } + // prints + // List(A) + // List(B, B) + // List(C, C, C) + // List(D) + // #bufferUntilChanged - def distinctUntilChanged(): Unit = { + def distinctUntilChanged(): Unit = // #distinctUntilChanged Source("A" :: "B" :: "B" :: "C" :: "C" :: "C" :: "D" :: Nil) .statefulMap(() => Option.empty[String])( @@ -64,15 +62,14 @@ object StatefulMap { _ => None) .collect { case Some(elem) => elem } .runForeach(println) - // prints - // A - // B - // C - // D - // #distinctUntilChanged - } + // prints + // A + // B + // C + // D + // #distinctUntilChanged - def statefulMapConcatLike(): Unit = { + def statefulMapConcatLike(): Unit = // #statefulMapConcatLike Source(1 to 10) .statefulMap(() => List.empty[Int])( @@ -87,17 +84,16 @@ object StatefulMap { state => Some(state.reverse)) .mapConcat(identity) .runForeach(println) - // prints - // 1 - // 2 - // 3 - // 4 - // 5 - // 6 - // 7 - // 8 - // 9 - // 10 - // #statefulMapConcatLike - } + // prints + // 1 + // 2 + // 3 + // 4 + // 5 + // 6 + // 7 + // 8 + // 9 + // 10 + // #statefulMapConcatLike } diff --git a/docs/src/test/scala/docs/stream/operators/source/From.scala b/docs/src/test/scala/docs/stream/operators/source/From.scala index 5da6b061128..e914626bc87 100644 --- a/docs/src/test/scala/docs/stream/operators/source/From.scala +++ b/docs/src/test/scala/docs/stream/operators/source/From.scala @@ -22,24 +22,22 @@ object From { implicit val system: ActorSystem = null - def fromIteratorSample(): Unit = { + def fromIteratorSample(): Unit = // #from-iterator Source.fromIterator(() => (1 to 3).iterator).runForeach(println) - // could print - // 1 - // 2 - // 3 - // #from-iterator - } + // could print + // 1 + // 2 + // 3 + // #from-iterator - def fromJavaStreamSample(): Unit = { + def fromJavaStreamSample(): Unit = // #from-javaStream Source.fromJavaStream(() => IntStream.rangeClosed(1, 3)).runForeach(println) - // could print - // 1 - // 2 - // 3 - // #from-javaStream - } + // could print + // 1 + // 2 + // 3 + // #from-javaStream } diff --git a/docs/src/test/scala/docs/stream/operators/source/Tick.scala b/docs/src/test/scala/docs/stream/operators/source/Tick.scala index 287e2e5df6c..6a2b0216b08 100644 --- a/docs/src/test/scala/docs/stream/operators/source/Tick.scala +++ b/docs/src/test/scala/docs/stream/operators/source/Tick.scala @@ -36,7 +36,7 @@ object Tick { case class Response(text: String) } - def simple(): Unit = { + def simple(): Unit = // #simple Source .tick( @@ -45,8 +45,7 @@ object Tick { "tick" // element emitted each tick ) .runForeach(println) - // #simple - } + // #simple def pollSomething(): Unit = { // #poll-actor diff --git a/docs/src/test/scala/docs/stream/operators/source/UnfoldResource.scala b/docs/src/test/scala/docs/stream/operators/source/UnfoldResource.scala index b6a2818c377..d59cc377ea1 100644 --- a/docs/src/test/scala/docs/stream/operators/source/UnfoldResource.scala +++ b/docs/src/test/scala/docs/stream/operators/source/UnfoldResource.scala @@ -43,17 +43,15 @@ object UnfoldResource { val queryResultSource: Source[DatabaseEntry, NotUsed] = Source.unfoldResource[DatabaseEntry, QueryResult]( // open - { () => - database.doQuery() - }, + () => + database.doQuery(), // read - { query => + query => if (query.hasMore) Some(query.nextEntry()) else // signals end of resource - None - }, + None, // close query => query.close()) diff --git a/docs/src/test/scala/docs/stream/operators/sourceorflow/Collect.scala b/docs/src/test/scala/docs/stream/operators/sourceorflow/Collect.scala index 21423439399..67bd4aa6ed3 100644 --- a/docs/src/test/scala/docs/stream/operators/sourceorflow/Collect.scala +++ b/docs/src/test/scala/docs/stream/operators/sourceorflow/Collect.scala @@ -41,23 +41,21 @@ object Collect { // #collectType } - def collectWhile(): Unit = { + def collectWhile(): Unit = // #collectWhile Flow[Message].collectWhile { case Ping(id) if id <= 100 => Pong(id) } - // #collectWhile - } + // #collectWhile - def collectFirst(): Unit = { + def collectFirst(): Unit = // #collectFirst Source(List(1, 3, 5, 7, 8, 9, 10)) .collectFirst { case elem if elem % 2 == 0 => elem } .runWith(Sink.foreach(println)) - // expect prints output: - // 8 - // #collectFirst - } + // expect prints output: + // 8 + // #collectFirst } diff --git a/docs/src/test/scala/docs/stream/operators/sourceorflow/ExtrapolateAndExpand.scala b/docs/src/test/scala/docs/stream/operators/sourceorflow/ExtrapolateAndExpand.scala index 92deb1edda4..841734c4384 100644 --- a/docs/src/test/scala/docs/stream/operators/sourceorflow/ExtrapolateAndExpand.scala +++ b/docs/src/test/scala/docs/stream/operators/sourceorflow/ExtrapolateAndExpand.scala @@ -69,11 +69,11 @@ object ExtrapolateAndExpand { // of the upstream frame and grayed out copies. The grayed out copies should // only be used downstream if the producer is too slow. val watermarkerRateControl: Flow[Frame, Frame, NotUsed] = - Flow[Frame].expand((frame: Frame) => { + Flow[Frame].expand { (frame: Frame) => val watermarked = frame.withFilter(Watermark) val grayedOut = frame.withFilter(Gray) Iterator.single(watermarked) ++ Iterator.continually(grayedOut) - }) + } val watermarkedVideoSource: Source[Frame, NotUsed] = networkSource.via(decode).via(rateControl) diff --git a/docs/src/test/scala/docs/stream/operators/sourceorflow/FlatMapConcat.scala b/docs/src/test/scala/docs/stream/operators/sourceorflow/FlatMapConcat.scala index 5a35f9de519..44a02b3125e 100644 --- a/docs/src/test/scala/docs/stream/operators/sourceorflow/FlatMapConcat.scala +++ b/docs/src/test/scala/docs/stream/operators/sourceorflow/FlatMapConcat.scala @@ -24,9 +24,8 @@ object FlatMapConcat { val source: Source[String, NotUsed] = Source(List("customer-1", "customer-2")) // e.g. could b a query to a database - def lookupCustomerEvents(customerId: String): Source[String, NotUsed] = { + def lookupCustomerEvents(customerId: String): Source[String, NotUsed] = Source(List(s"$customerId-event-1", s"$customerId-event-2")) - } source.flatMapConcat(customerId => lookupCustomerEvents(customerId)).runForeach(println) diff --git a/docs/src/test/scala/docs/stream/operators/sourceorflow/FlatMapMerge.scala b/docs/src/test/scala/docs/stream/operators/sourceorflow/FlatMapMerge.scala index 0778535cc0a..8fd7166fb17 100644 --- a/docs/src/test/scala/docs/stream/operators/sourceorflow/FlatMapMerge.scala +++ b/docs/src/test/scala/docs/stream/operators/sourceorflow/FlatMapMerge.scala @@ -25,9 +25,8 @@ object FlatMapMerge { val source: Source[String, NotUsed] = Source(List("customer-1", "customer-2")) // e.g. could b a query to a database - def lookupCustomerEvents(customerId: String): Source[String, NotUsed] = { + def lookupCustomerEvents(customerId: String): Source[String, NotUsed] = Source(List(s"$customerId-evt-1", s"$customerId-evt2")) - } source.flatMapMerge(10, customerId => lookupCustomerEvents(customerId)).runForeach(println) diff --git a/docs/src/test/scala/docs/stream/operators/sourceorflow/FoldAsync.scala b/docs/src/test/scala/docs/stream/operators/sourceorflow/FoldAsync.scala index 18ba1cc2598..79cec8906ed 100644 --- a/docs/src/test/scala/docs/stream/operators/sourceorflow/FoldAsync.scala +++ b/docs/src/test/scala/docs/stream/operators/sourceorflow/FoldAsync.scala @@ -29,8 +29,8 @@ object FoldAsync extends App { // #foldAsync case class Histogram(low: Long = 0, high: Long = 0) { def add(i: Int): Future[Histogram] = - if (i < 100) Future { copy(low = low + 1) } - else Future { copy(high = high + 1) } + if (i < 100) Future(copy(low = low + 1)) + else Future(copy(high = high + 1)) } Source(1 to 150).foldAsync(Histogram())((acc, n) => acc.add(n)).runForeach(println) diff --git a/docs/src/test/scala/docs/stream/operators/sourceorflow/Log.scala b/docs/src/test/scala/docs/stream/operators/sourceorflow/Log.scala index c11acd0a2cf..77369291db0 100644 --- a/docs/src/test/scala/docs/stream/operators/sourceorflow/Log.scala +++ b/docs/src/test/scala/docs/stream/operators/sourceorflow/Log.scala @@ -20,7 +20,7 @@ import org.apache.pekko.stream.Attributes //#log object Log { - def logExample(): Unit = { + def logExample(): Unit = Flow[String] // #log .log(name = "myStream") @@ -29,6 +29,5 @@ object Log { onElement = Attributes.LogLevels.Off, onFinish = Attributes.LogLevels.Info, onFailure = Attributes.LogLevels.Error)) - // #log - } + // #log } diff --git a/docs/src/test/scala/docs/stream/operators/sourceorflow/LogWithMarker.scala b/docs/src/test/scala/docs/stream/operators/sourceorflow/LogWithMarker.scala index 2264ddf09dc..6cde3988f53 100644 --- a/docs/src/test/scala/docs/stream/operators/sourceorflow/LogWithMarker.scala +++ b/docs/src/test/scala/docs/stream/operators/sourceorflow/LogWithMarker.scala @@ -22,7 +22,7 @@ import pekko.stream.Attributes //#logWithMarker object LogWithMarker { - def logWithMarkerExample(): Unit = { + def logWithMarkerExample(): Unit = Flow[String] // #logWithMarker .logWithMarker(name = "myStream", e => LogMarker(name = "myMarker", properties = Map("element" -> e))) @@ -31,6 +31,5 @@ object LogWithMarker { onElement = Attributes.LogLevels.Off, onFinish = Attributes.LogLevels.Info, onFailure = Attributes.LogLevels.Error)) - // #logWithMarker - } + // #logWithMarker } diff --git a/docs/src/test/scala/docs/stream/operators/sourceorflow/OptionalVia.scala b/docs/src/test/scala/docs/stream/operators/sourceorflow/OptionalVia.scala index 64714df49ec..54a61d0a401 100644 --- a/docs/src/test/scala/docs/stream/operators/sourceorflow/OptionalVia.scala +++ b/docs/src/test/scala/docs/stream/operators/sourceorflow/OptionalVia.scala @@ -27,7 +27,7 @@ object OptionalVia { // #optionalVia Source.optionalVia( Source(List(Some("1"), None, None, Some("4"))), - Flow.fromFunction { (string: String) => string.toInt } + Flow.fromFunction((string: String) => string.toInt) )(Keep.none).runForeach(println) // Some(1) // None diff --git a/docs/src/test/scala/docs/stream/operators/sourceorflow/Split.scala b/docs/src/test/scala/docs/stream/operators/sourceorflow/Split.scala index c4919925dac..19a640999a6 100644 --- a/docs/src/test/scala/docs/stream/operators/sourceorflow/Split.scala +++ b/docs/src/test/scala/docs/stream/operators/sourceorflow/Split.scala @@ -35,7 +35,7 @@ object Split { Source(1 to 100) .throttle(1, 100.millis) .map(elem => (elem, Instant.now())) - .statefulMapConcat(() => { + .statefulMapConcat { () => // stateful decision in statefulMapConcat // keep track of time bucket (one per second) var currentTimeBucket = LocalDateTime.ofInstant(Instant.ofEpochMilli(0), ZoneOffset.UTC) @@ -49,7 +49,7 @@ object Split { currentTimeBucket = bucket List((elem, newBucket)) } - }) + } .splitWhen(_._2) // split when time bucket changes .map(_._1) .fold(0)((acc, _) => acc + 1) // sum diff --git a/docs/src/test/scala/docs/testkit/ParentChildSpec.scala b/docs/src/test/scala/docs/testkit/ParentChildSpec.scala index 056bca85a55..a1cd9bd8b20 100644 --- a/docs/src/test/scala/docs/testkit/ParentChildSpec.scala +++ b/docs/src/test/scala/docs/testkit/ParentChildSpec.scala @@ -87,9 +87,8 @@ class MockedChild extends Actor { class ParentChildSpec extends AnyWordSpec with Matchers with TestKitBase with BeforeAndAfterAll { implicit lazy val system: ActorSystem = ActorSystem("ParentChildSpec") - override def afterAll(): Unit = { + override def afterAll(): Unit = TestKit.shutdownActorSystem(system) - } "A DependentChild" should { "be tested without its parent" in { diff --git a/docs/src/test/scala/docs/testkit/PlainWordSpec.scala b/docs/src/test/scala/docs/testkit/PlainWordSpec.scala index 954bc3a35b3..9b6d2f9d410 100644 --- a/docs/src/test/scala/docs/testkit/PlainWordSpec.scala +++ b/docs/src/test/scala/docs/testkit/PlainWordSpec.scala @@ -30,9 +30,8 @@ class MySpec() with BeforeAndAfterAll { // #implicit-sender - override def afterAll(): Unit = { + override def afterAll(): Unit = TestKit.shutdownActorSystem(system) - } "An Echo actor" must { diff --git a/docs/src/test/scala/docs/testkit/TestKitUsageSpec.scala b/docs/src/test/scala/docs/testkit/TestKitUsageSpec.scala index 75456696492..8cf376b8857 100644 --- a/docs/src/test/scala/docs/testkit/TestKitUsageSpec.scala +++ b/docs/src/test/scala/docs/testkit/TestKitUsageSpec.scala @@ -55,9 +55,8 @@ class TestKitUsageSpec val seqRef = system.actorOf(Props(classOf[SequencingActor], testActor, headList, tailList)) - override def afterAll(): Unit = { + override def afterAll(): Unit = shutdown() - } "An EchoActor" should { "Respond with the same message it receives" in { @@ -150,11 +149,10 @@ object TestKitUsageSpec { */ class SequencingActor(next: ActorRef, head: immutable.Seq[String], tail: immutable.Seq[String]) extends Actor { def receive = { - case msg => { - head.foreach { next ! _ } + case msg => + head.foreach(next ! _) next ! msg - tail.foreach { next ! _ } - } + tail.foreach(next ! _) } } } diff --git a/docs/src/test/scala/docs/testkit/TestkitDocSpec.scala b/docs/src/test/scala/docs/testkit/TestkitDocSpec.scala index 93a1b92ff90..854995916bd 100644 --- a/docs/src/test/scala/docs/testkit/TestkitDocSpec.scala +++ b/docs/src/test/scala/docs/testkit/TestkitDocSpec.scala @@ -204,7 +204,7 @@ class TestKitDocSpec extends PekkoSpec with DefaultTimeout with ImplicitSender { case "hello" => throw new IllegalArgumentException("boom") } }) - intercept[IllegalArgumentException] { actorRef.receive("hello") } + intercept[IllegalArgumentException](actorRef.receive("hello")) // #test-expecting-exceptions } @@ -343,9 +343,8 @@ class TestKitDocSpec extends PekkoSpec with DefaultTimeout with ImplicitSender { EventFilter[ActorKilledException](occurrences = 1).intercept { actor ! Kill } - } finally { + } finally shutdown(system) - } // #event-filter } diff --git a/docs/src/test/scala/typed/tutorial_1/ActorHierarchyExperiments.scala b/docs/src/test/scala/typed/tutorial_1/ActorHierarchyExperiments.scala index d76b9bfd3a6..f6bd1ecdbc7 100644 --- a/docs/src/test/scala/typed/tutorial_1/ActorHierarchyExperiments.scala +++ b/docs/src/test/scala/typed/tutorial_1/ActorHierarchyExperiments.scala @@ -83,10 +83,9 @@ object StartStopActor2 { class StartStopActor2(context: ActorContext[String]) extends AbstractBehavior[String](context) { println("second started") - override def onMessage(msg: String): Behavior[String] = { + override def onMessage(msg: String): Behavior[String] = // no messages handled by this actor Behaviors.unhandled - } override def onSignal: PartialFunction[Signal, Behavior[String]] = { case PostStop => diff --git a/docs/src/test/scala/typed/tutorial_2/IotApp.scala b/docs/src/test/scala/typed/tutorial_2/IotApp.scala index 0427000b178..4ad5f04af20 100644 --- a/docs/src/test/scala/typed/tutorial_2/IotApp.scala +++ b/docs/src/test/scala/typed/tutorial_2/IotApp.scala @@ -25,10 +25,9 @@ import org.apache.pekko.actor.typed.ActorSystem object IotApp { - def main(args: Array[String]): Unit = { + def main(args: Array[String]): Unit = // Create ActorSystem and top level supervisor ActorSystem[Nothing](IotSupervisor(), "iot-system") - } } //#iot-app diff --git a/docs/src/test/scala/typed/tutorial_2/IotSupervisor.scala b/docs/src/test/scala/typed/tutorial_2/IotSupervisor.scala index a0bad95eb0d..bfbb6b0ae48 100644 --- a/docs/src/test/scala/typed/tutorial_2/IotSupervisor.scala +++ b/docs/src/test/scala/typed/tutorial_2/IotSupervisor.scala @@ -37,10 +37,9 @@ object IotSupervisor { class IotSupervisor(context: ActorContext[Nothing]) extends AbstractBehavior[Nothing](context) { context.log.info("IoT Application started") - override def onMessage(msg: Nothing): Behavior[Nothing] = { + override def onMessage(msg: Nothing): Behavior[Nothing] = // No need to handle any messages Behaviors.unhandled - } override def onSignal: PartialFunction[Signal, Behavior[Nothing]] = { case PostStop => diff --git a/docs/src/test/scala/typed/tutorial_3/Device.scala b/docs/src/test/scala/typed/tutorial_3/Device.scala index 7359c80b348..c6788df7b76 100644 --- a/docs/src/test/scala/typed/tutorial_3/Device.scala +++ b/docs/src/test/scala/typed/tutorial_3/Device.scala @@ -48,7 +48,7 @@ class Device(context: ActorContext[Device.Command], groupId: String, deviceId: S context.log.info2("Device actor {}-{} started", groupId, deviceId) - override def onMessage(msg: Command): Behavior[Command] = { + override def onMessage(msg: Command): Behavior[Command] = msg match { case RecordTemperature(id, value, replyTo) => context.log.info2("Recorded temperature reading {} with {}", value, id) @@ -60,7 +60,6 @@ class Device(context: ActorContext[Device.Command], groupId: String, deviceId: S replyTo ! RespondTemperature(id, lastTemperatureReading) this } - } override def onSignal: PartialFunction[Signal, Behavior[Command]] = { case PostStop => diff --git a/docs/src/test/scala/typed/tutorial_3/DeviceInProgress.scala b/docs/src/test/scala/typed/tutorial_3/DeviceInProgress.scala index 9119ed623a0..9d2caf537fe 100644 --- a/docs/src/test/scala/typed/tutorial_3/DeviceInProgress.scala +++ b/docs/src/test/scala/typed/tutorial_3/DeviceInProgress.scala @@ -67,13 +67,12 @@ object DeviceInProgress2 { context.log.info2("Device actor {}-{} started", groupId, deviceId) - override def onMessage(msg: Command): Behavior[Command] = { + override def onMessage(msg: Command): Behavior[Command] = msg match { case ReadTemperature(id, replyTo) => replyTo ! RespondTemperature(id, lastTemperatureReading) this } - } override def onSignal: PartialFunction[Signal, Behavior[Command]] = { case PostStop => diff --git a/docs/src/test/scala/typed/tutorial_4/Device.scala b/docs/src/test/scala/typed/tutorial_4/Device.scala index c8acd7e2c3c..975827731f0 100644 --- a/docs/src/test/scala/typed/tutorial_4/Device.scala +++ b/docs/src/test/scala/typed/tutorial_4/Device.scala @@ -50,7 +50,7 @@ class Device(context: ActorContext[Device.Command], groupId: String, deviceId: S context.log.info2("Device actor {}-{} started", groupId, deviceId) - override def onMessage(msg: Command): Behavior[Command] = { + override def onMessage(msg: Command): Behavior[Command] = msg match { case RecordTemperature(id, value, replyTo) => context.log.info2("Recorded temperature reading {} with {}", value, id) @@ -65,7 +65,6 @@ class Device(context: ActorContext[Device.Command], groupId: String, deviceId: S case Passivate => Behaviors.stopped } - } override def onSignal: PartialFunction[Signal, Behavior[Command]] = { case PostStop => diff --git a/docs/src/test/scala/typed/tutorial_5/Device.scala b/docs/src/test/scala/typed/tutorial_5/Device.scala index 8357120d9aa..16bb2ae22c0 100644 --- a/docs/src/test/scala/typed/tutorial_5/Device.scala +++ b/docs/src/test/scala/typed/tutorial_5/Device.scala @@ -49,7 +49,7 @@ class Device(context: ActorContext[Device.Command], groupId: String, deviceId: S context.log.info2("Device actor {}-{} started", groupId, deviceId) - override def onMessage(msg: Command): Behavior[Command] = { + override def onMessage(msg: Command): Behavior[Command] = msg match { case RecordTemperature(id, value, replyTo) => context.log.info2("Recorded temperature reading {} with {}", value, id) @@ -64,7 +64,6 @@ class Device(context: ActorContext[Device.Command], groupId: String, deviceId: S case Passivate => Behaviors.stopped } - } override def onSignal: PartialFunction[Signal, Behavior[Command]] = { case PostStop => diff --git a/docs/src/test/scala/typed/tutorial_5/DeviceGroupQuery.scala b/docs/src/test/scala/typed/tutorial_5/DeviceGroupQuery.scala index cb9bf483605..e7bf6086582 100644 --- a/docs/src/test/scala/typed/tutorial_5/DeviceGroupQuery.scala +++ b/docs/src/test/scala/typed/tutorial_5/DeviceGroupQuery.scala @@ -31,13 +31,12 @@ object DeviceGroupQuery { deviceIdToActor: Map[String, ActorRef[Device.Command]], requestId: Long, requester: ActorRef[DeviceManager.RespondAllTemperatures], - timeout: FiniteDuration): Behavior[Command] = { + timeout: FiniteDuration): Behavior[Command] = Behaviors.setup { context => Behaviors.withTimers { timers => new DeviceGroupQuery(deviceIdToActor, requestId, requester, timeout, context, timers) } } - } trait Command @@ -121,14 +120,13 @@ class DeviceGroupQuery( // #query-state // #query-collect-reply - private def respondWhenAllCollected(): Behavior[Command] = { + private def respondWhenAllCollected(): Behavior[Command] = if (stillWaiting.isEmpty) { requester ! RespondAllTemperatures(requestId, repliesSoFar) Behaviors.stopped } else { this } - } // #query-collect-reply // #query-outline } diff --git a/multi-node-testkit/src/main/scala/org/apache/pekko/remote/testconductor/Conductor.scala b/multi-node-testkit/src/main/scala/org/apache/pekko/remote/testconductor/Conductor.scala index 60620238438..a0757afe6c4 100644 --- a/multi-node-testkit/src/main/scala/org/apache/pekko/remote/testconductor/Conductor.scala +++ b/multi-node-testkit/src/main/scala/org/apache/pekko/remote/testconductor/Conductor.scala @@ -154,7 +154,7 @@ trait Conductor { this: TestConductorExt => def blackhole(node: RoleName, target: RoleName, direction: Direction): Future[Done] = throttle(node, target, direction, 0f) - private def requireTestConductorTranport(): Unit = { + private def requireTestConductorTranport(): Unit = if (transport.provider.remoteSettings.Artery.Enabled) { if (!transport.provider.remoteSettings.Artery.Advanced.TestMode) throw new ConfigurationException( @@ -166,7 +166,6 @@ trait Conductor { this: TestConductorExt => "To use this feature you must activate the failure injector adapters " + "(trttl, gremlin) by specifying `testTransport(on = true)` in your MultiNodeConfig.") } - } /** * Switch the Netty pipeline of the remote support into pass through mode for @@ -455,7 +454,7 @@ private[pekko] class Controller(private var initialParticipants: Int, controller case BarrierTimeout(data) => failBarrier(data) case FailedBarrier(data) => failBarrier(data) case BarrierEmpty(_, _) => SupervisorStrategy.Resume - case WrongBarrier(name, client, data) => { client ! ToClient(BarrierResult(name, false)); failBarrier(data) } + case WrongBarrier(name, client, data) => client ! ToClient(BarrierResult(name, false)); failBarrier(data) case ClientLost(data, _) => failBarrier(data) case DuplicateNode(data, _) => failBarrier(data) } @@ -532,9 +531,8 @@ private[pekko] class Controller(private var initialParticipants: Int, controller sender() ! connection.channelFuture.sync().channel().localAddress() } - override def postStop(): Unit = { + override def postStop(): Unit = connection.shutdown() - } } /** @@ -600,7 +598,7 @@ private[pekko] class BarrierCoordinator var failed = false override def preRestart(reason: Throwable, message: Option[Any]): Unit = {} - override def postRestart(reason: Throwable): Unit = { failed = true } + override def postRestart(reason: Throwable): Unit = failed = true // TODO what happens with the other waiting players in case of a test failure? @@ -680,8 +678,7 @@ private[pekko] class BarrierCoordinator } } - def getDeadline(timeout: Option[FiniteDuration]): Deadline = { + def getDeadline(timeout: Option[FiniteDuration]): Deadline = Deadline.now + timeout.getOrElse(TestConductor().Settings.BarrierTimeout.duration) - } } diff --git a/multi-node-testkit/src/main/scala/org/apache/pekko/remote/testconductor/DataTypes.scala b/multi-node-testkit/src/main/scala/org/apache/pekko/remote/testconductor/DataTypes.scala index 2184ed419bd..b4c9714c3c0 100644 --- a/multi-node-testkit/src/main/scala/org/apache/pekko/remote/testconductor/DataTypes.scala +++ b/multi-node-testkit/src/main/scala/org/apache/pekko/remote/testconductor/DataTypes.scala @@ -87,9 +87,8 @@ private[pekko] class MsgEncoder extends MessageToMessageEncoder[AnyRef] { case Direction.Both => TCP.Direction.Both } - override def encode(ctx: ChannelHandlerContext, msg: AnyRef, out: java.util.List[AnyRef]): Unit = { + override def encode(ctx: ChannelHandlerContext, msg: AnyRef, out: java.util.List[AnyRef]): Unit = out.add(encode0(msg)) - } private def encode0(msg: AnyRef): AnyRef = msg match { case x: NetworkOp => @@ -148,9 +147,8 @@ private[pekko] class MsgDecoder extends MessageToMessageDecoder[AnyRef] { case TCP.Direction.Both => Direction.Both } - override def decode(ctx: ChannelHandlerContext, msg: AnyRef, out: java.util.List[AnyRef]): Unit = { + override def decode(ctx: ChannelHandlerContext, msg: AnyRef, out: java.util.List[AnyRef]): Unit = out.add(decode0(msg)) - } private def decode0(msg: AnyRef): AnyRef = msg match { case w: TCP.Wrapper if w.getAllFields.size == 1 => diff --git a/multi-node-testkit/src/main/scala/org/apache/pekko/remote/testconductor/Player.scala b/multi-node-testkit/src/main/scala/org/apache/pekko/remote/testconductor/Player.scala index 570be3b53b4..a0334ee192b 100644 --- a/multi-node-testkit/src/main/scala/org/apache/pekko/remote/testconductor/Player.scala +++ b/multi-node-testkit/src/main/scala/org/apache/pekko/remote/testconductor/Player.scala @@ -310,9 +310,9 @@ private[pekko] class ClientFSM(name: RoleName, controllerAddr: InetSocketAddress onTermination { case StopEvent(_, _, Data(Some(channel), _)) => - try { + try channel.close() - } catch { + catch { case NonFatal(ex) => // silence this one to not make tests look like they failed, it's not really critical log.debug(s"Failed closing channel with ${ex.getClass.getName} ${ex.getMessage}") @@ -357,7 +357,7 @@ private[pekko] class PlayerHandler( } } - private def tryConnectToController(): Unit = { + private def tryConnectToController(): Unit = Try(reconnect()) match { case Success(r) => connectionRef.set(r) case Failure(ex) => @@ -365,11 +365,9 @@ private[pekko] class PlayerHandler( server, nextAttempt.timeLeft, ex.getMessage) scheduleReconnect() } - } - private def scheduleReconnect(): Unit = { + private def scheduleReconnect(): Unit = scheduler.scheduleOnce(nextAttempt.timeLeft)(tryConnectToController()) - } private def reconnect(): RemoteConnection = { nextAttempt = Deadline.now + backoff diff --git a/multi-node-testkit/src/main/scala/org/apache/pekko/remote/testconductor/RemoteConnection.scala b/multi-node-testkit/src/main/scala/org/apache/pekko/remote/testconductor/RemoteConnection.scala index 99801878bf9..494032f855b 100644 --- a/multi-node-testkit/src/main/scala/org/apache/pekko/remote/testconductor/RemoteConnection.scala +++ b/multi-node-testkit/src/main/scala/org/apache/pekko/remote/testconductor/RemoteConnection.scala @@ -41,13 +41,12 @@ import pekko.util.Helpers */ private[pekko] class ProtobufEncoder extends MessageToMessageEncoder[Message] { - override def encode(ctx: ChannelHandlerContext, msg: Message, out: java.util.List[AnyRef]): Unit = { + override def encode(ctx: ChannelHandlerContext, msg: Message, out: java.util.List[AnyRef]): Unit = msg match { case message: Message => val bytes = message.toByteArray out.add(ctx.alloc().buffer(bytes.length).writeBytes(bytes)) } - } } /** @@ -119,7 +118,7 @@ private[pekko] object RemoteConnection { role: Role, sockaddr: InetSocketAddress, poolSize: Int, - handler: ChannelInboundHandler): RemoteConnection = { + handler: ChannelInboundHandler): RemoteConnection = role match { case Client => val bootstrap = new Bootstrap() @@ -136,14 +135,13 @@ private[pekko] object RemoteConnection { new RemoteConnection { override def channelFuture: ChannelFuture = cf - override def shutdown(): Unit = { + override def shutdown(): Unit = try { channelFuture.channel().close().sync() eventLoopGroup.shutdownGracefully(0L, 0L, TimeUnit.SECONDS) } catch { case NonFatal(_) => // silence this one to not make tests look like they failed, it's not really critical } - } } case Server => @@ -163,7 +161,7 @@ private[pekko] object RemoteConnection { new RemoteConnection { override def channelFuture: ChannelFuture = cf - override def shutdown(): Unit = { + override def shutdown(): Unit = try { channelFuture.channel().close().sync() parentEventLoopGroup.shutdownGracefully(0L, 0L, TimeUnit.SECONDS) @@ -171,10 +169,8 @@ private[pekko] object RemoteConnection { } catch { case NonFatal(_) => // silence this one to not make tests look like they failed, it's not really critical } - } } } - } def getAddrString(channel: Channel): String = channel.remoteAddress() match { case i: InetSocketAddress => i.toString diff --git a/multi-node-testkit/src/main/scala/org/apache/pekko/remote/testkit/MultiNodeSpec.scala b/multi-node-testkit/src/main/scala/org/apache/pekko/remote/testkit/MultiNodeSpec.scala index 95f6a3f1df9..5441d6b48ef 100644 --- a/multi-node-testkit/src/main/scala/org/apache/pekko/remote/testkit/MultiNodeSpec.scala +++ b/multi-node-testkit/src/main/scala/org/apache/pekko/remote/testkit/MultiNodeSpec.scala @@ -59,7 +59,7 @@ abstract class MultiNodeConfig { */ def nodeConfig(roles: RoleName*)(configs: Config*): Unit = { val c = configs.reduceLeft(_.withFallback(_)) - _nodeConf ++= roles.map { _ -> c } + _nodeConf ++= roles.map(_ -> c) } /** @@ -331,9 +331,9 @@ abstract class MultiNodeSpec( this(config, { val name = TestKitUtils.testNameFromCallStack(classOf[MultiNodeSpec], "".r) config => - try { + try ActorSystem(name, config) - } catch { + catch { // Retry creating the system once as when using port = 0 two systems may try and use the same one. // RTE is for aeron, CE for netty case _: RemoteTransportException => ActorSystem(name, config) @@ -352,19 +352,18 @@ abstract class MultiNodeSpec( def await: T = Await.result(w, remainingOr(testConductor.Settings.QueryTimeout.duration)) } - final override def multiNodeSpecBeforeAll(): Unit = { + final override def multiNodeSpecBeforeAll(): Unit = atStartup() - } final override def multiNodeSpecAfterAll(): Unit = { // wait for all nodes to remove themselves before we shut the conductor down if (selfIndex == 0) { testConductor.removeNode(myself) within(testConductor.Settings.BarrierTimeout.duration) { - awaitCond({ - // Await.result(testConductor.getNodes, remaining).filterNot(_ == myself).isEmpty - testConductor.getNodes.await.forall(_ == myself) - }, message = s"Nodes not shutdown: ${testConductor.getNodes.await}") + awaitCond( + // Await.result(testConductor.getNodes, remaining).filterNot(_ == myself).isEmpty + testConductor.getNodes.await.forall(_ == myself), + message = s"Nodes not shutdown: ${testConductor.getNodes.await}") } } shutdown(system, duration = shutdownTimeout) @@ -424,11 +423,10 @@ abstract class MultiNodeSpec( * Execute the given block of code only on the given nodes (names according * to the `roleMap`). */ - def runOn(nodes: RoleName*)(thunk: => Unit): Unit = { + def runOn(nodes: RoleName*)(thunk: => Unit): Unit = if (isNode(nodes: _*)) { thunk } - } /** * Verify that the running node matches one of the given nodes diff --git a/multi-node-testkit/src/main/scala/org/apache/pekko/remote/testkit/PerfFlamesSupport.scala b/multi-node-testkit/src/main/scala/org/apache/pekko/remote/testkit/PerfFlamesSupport.scala index 35c3da6f34b..916c82ba30d 100644 --- a/multi-node-testkit/src/main/scala/org/apache/pekko/remote/testkit/PerfFlamesSupport.scala +++ b/multi-node-testkit/src/main/scala/org/apache/pekko/remote/testkit/PerfFlamesSupport.scala @@ -32,7 +32,7 @@ private[pekko] trait PerfFlamesSupport { self: MultiNodeSpec => * * Options are currently to be passed in via `export PERF_MAP_OPTIONS` etc. */ - def runPerfFlames(nodes: RoleName*)(delay: FiniteDuration): Unit = { + def runPerfFlames(nodes: RoleName*)(delay: FiniteDuration): Unit = if (isPerfJavaFlamesAvailable && isNode(nodes: _*)) { import scala.concurrent.ExecutionContext.Implicits.global @@ -53,7 +53,6 @@ private[pekko] trait PerfFlamesSupport { self: MultiNodeSpec => }) } } - } def perfJavaFlamesPath: String = "/home/ubuntu/perf-java-flames" diff --git a/osgi/src/main/scala/org/apache/pekko/osgi/ActorSystemActivator.scala b/osgi/src/main/scala/org/apache/pekko/osgi/ActorSystemActivator.scala index 12536c0326d..9eb0a9c3323 100644 --- a/osgi/src/main/scala/org/apache/pekko/osgi/ActorSystemActivator.scala +++ b/osgi/src/main/scala/org/apache/pekko/osgi/ActorSystemActivator.scala @@ -68,21 +68,20 @@ abstract class ActorSystemActivator extends BundleActivator { */ def addLogServiceListener(context: BundleContext, system: ActorSystem): Unit = { val logServiceListner = new ServiceListener { - def serviceChanged(event: ServiceEvent): Unit = { + def serviceChanged(event: ServiceEvent): Unit = event.getType match { case ServiceEvent.REGISTERED => system.eventStream.publish(serviceForReference[LogService](context, event.getServiceReference)) case ServiceEvent.UNREGISTERING => system.eventStream.publish(UnregisteringLogService) } - } } val filter = s"(objectclass=${classOf[LogService].getName})" context.addServiceListener(logServiceListner, filter) // Small trick to create an event if the service is registered before this start listing for - Option(context.getServiceReference(classOf[LogService].getName)).foreach(x => { + Option(context.getServiceReference(classOf[LogService].getName)).foreach { x => logServiceListner.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, x)) - }) + } } /** diff --git a/osgi/src/main/scala/org/apache/pekko/osgi/BundleDelegatingClassLoader.scala b/osgi/src/main/scala/org/apache/pekko/osgi/BundleDelegatingClassLoader.scala index 45c8bd99342..5749f33dca7 100644 --- a/osgi/src/main/scala/org/apache/pekko/osgi/BundleDelegatingClassLoader.scala +++ b/osgi/src/main/scala/org/apache/pekko/osgi/BundleDelegatingClassLoader.scala @@ -51,38 +51,36 @@ class BundleDelegatingClassLoader(bundle: Bundle, fallBackClassLoader: ClassLoad private val bundles = findTransitiveBundles(bundle).toList override def findClass(name: String): Class[_] = { - @tailrec def find(remaining: List[Bundle]): Class[_] = { + @tailrec def find(remaining: List[Bundle]): Class[_] = if (remaining.isEmpty) throw new ClassNotFoundException(name) else - Try { remaining.head.loadClass(name) } match { + Try(remaining.head.loadClass(name)) match { case Success(cls) => cls case Failure(_) => find(remaining.tail) } - } find(bundles) } override def findResource(name: String): URL = { - @tailrec def find(remaining: List[Bundle]): URL = { + @tailrec def find(remaining: List[Bundle]): URL = if (remaining.isEmpty) getParent.getResource(name) else - Option { remaining.head.getResource(name) } match { + Option(remaining.head.getResource(name)) match { case Some(r) => r case None => find(remaining.tail) } - } find(bundles) } override def findResources(name: String): Enumeration[URL] = { val resources = bundles.flatMap { bundle => - Option(bundle.getResources(name)).map { _.asScala.toList }.getOrElse(Nil) + Option(bundle.getResources(name)).map(_.asScala.toList).getOrElse(Nil) } java.util.Collections.enumeration(resources.asJava) } private def findTransitiveBundles(bundle: Bundle): Set[Bundle] = { - @tailrec def process(processed: Set[Bundle], remaining: Set[Bundle]): Set[Bundle] = { + @tailrec def process(processed: Set[Bundle], remaining: Set[Bundle]): Set[Bundle] = if (remaining.isEmpty) { processed } else { @@ -97,13 +95,12 @@ class BundleDelegatingClassLoader(bundle: Bundle, fallBackClassLoader: ClassLoad val requiredWires: List[BundleWire] = wiring.getRequiredWires(BundleRevision.PACKAGE_NAMESPACE).asScala.toList requiredWires.flatMap { wire => - Option(wire.getProviderWiring).map { _.getBundle } + Option(wire.getProviderWiring).map(_.getBundle) }.toSet } process(processed + b, rest ++ (direct.diff(processed))) } } - } process(Set.empty, Set(bundle)) } } diff --git a/osgi/src/main/scala/org/apache/pekko/osgi/DefaultOSGiLogger.scala b/osgi/src/main/scala/org/apache/pekko/osgi/DefaultOSGiLogger.scala index 2c96fb71a33..a3a8ded1917 100644 --- a/osgi/src/main/scala/org/apache/pekko/osgi/DefaultOSGiLogger.scala +++ b/osgi/src/main/scala/org/apache/pekko/osgi/DefaultOSGiLogger.scala @@ -47,9 +47,9 @@ class DefaultOSGiLogger extends DefaultLogger { * @param logService OSGi LogService that has been registered, */ def setLogService(logService: LogService): Unit = { - messagesToLog.foreach(x => { + messagesToLog.foreach { x => logMessage(logService, x) - }) + } context.become(initialisedReceive(logService)) } @@ -80,7 +80,7 @@ class DefaultOSGiLogger extends DefaultLogger { * @param logService OSGi LogService registered and used for logging * @param event akka LogEvent that is logged using the LogService */ - def logMessage(logService: LogService, event: LogEvent): Unit = { + def logMessage(logService: LogService, event: LogEvent): Unit = event match { case error: Logging.Error if error.cause != NoCause => logService.log( @@ -92,7 +92,6 @@ class DefaultOSGiLogger extends DefaultLogger { event.level.asInt, messageFormat.format(timestamp(event), event.thread.getName, event.logSource, event.message)) } - } } diff --git a/osgi/src/main/scala/org/apache/pekko/osgi/OsgiActorSystemFactory.scala b/osgi/src/main/scala/org/apache/pekko/osgi/OsgiActorSystemFactory.scala index 5b5c319e876..ba071836e75 100644 --- a/osgi/src/main/scala/org/apache/pekko/osgi/OsgiActorSystemFactory.scala +++ b/osgi/src/main/scala/org/apache/pekko/osgi/OsgiActorSystemFactory.scala @@ -52,12 +52,11 @@ class OsgiActorSystemFactory( * ensuring that the default/reference configuration is loaded from the pekko-actor bundle. * Configuration files found in pekko-actor bundle */ - def actorSystemConfig(@unused context: BundleContext): Config = { + def actorSystemConfig(@unused context: BundleContext): Config = config.withFallback( ConfigFactory .load(classloader) .withFallback(ConfigFactory.defaultReference(OsgiActorSystemFactory.pekkoActorClassLoader))) - } /** * Determine the name for the [[pekko.actor.ActorSystem]] diff --git a/osgi/src/test/scala/org/apache/pekko/osgi/PojoSRTestSupport.scala b/osgi/src/test/scala/org/apache/pekko/osgi/PojoSRTestSupport.scala index d7bb7a02fcc..d8f3de47d35 100644 --- a/osgi/src/test/scala/org/apache/pekko/osgi/PojoSRTestSupport.scala +++ b/osgi/src/test/scala/org/apache/pekko/osgi/PojoSRTestSupport.scala @@ -56,18 +56,17 @@ trait PojoSRTestSupport extends Suite with BeforeAndAfterAll { val oldErr = System.err System.setErr(new PrintStream(bufferedLoadingErrors)) - try { + try ServiceLoader .load(classOf[PojoServiceRegistryFactory]) .iterator .next .newPojoServiceRegistry(config) .getBundleContext - } catch { + catch { case e: Throwable => oldErr.write(bufferedLoadingErrors.toByteArray); throw e - } finally { + } finally System.setErr(oldErr) - } } // Ensure bundles get stopped at the end of the test to release resources and stop threads @@ -169,10 +168,10 @@ class BundleDescriptorBuilder(name: String) { def extractHeaders(file: File): HashMap[String, String] = { val headers = new HashMap[String, String]() val jis = new JarInputStream(new FileInputStream(file)) - try { + try for (entry <- jis.getManifest.getMainAttributes.entrySet.asScala) headers.put(entry.getKey.toString, entry.getValue.toString) - } finally jis.close() + finally jis.close() headers } diff --git a/persistence-query/src/main/scala/org/apache/pekko/persistence/query/Offset.scala b/persistence-query/src/main/scala/org/apache/pekko/persistence/query/Offset.scala index 716bcb8f689..8703b3f1fb5 100644 --- a/persistence-query/src/main/scala/org/apache/pekko/persistence/query/Offset.scala +++ b/persistence-query/src/main/scala/org/apache/pekko/persistence/query/Offset.scala @@ -71,7 +71,7 @@ object TimestampOffset { /** * Try to convert the Offset to a TimestampOffset. Epoch timestamp is used for `NoOffset`. */ - def toTimestampOffset(offset: Offset): TimestampOffset = { + def toTimestampOffset(offset: Offset): TimestampOffset = offset match { case t: TimestampOffset => t case NoOffset => TimestampOffset.Zero @@ -81,7 +81,6 @@ object TimestampOffset { s"Supported offset types are TimestampOffset and NoOffset, " + s"received ${other.getClass.getName}") } - } } /** diff --git a/persistence-query/src/main/scala/org/apache/pekko/persistence/query/internal/QuerySerializer.scala b/persistence-query/src/main/scala/org/apache/pekko/persistence/query/internal/QuerySerializer.scala index a4f2dee8673..7bc877a7170 100644 --- a/persistence-query/src/main/scala/org/apache/pekko/persistence/query/internal/QuerySerializer.scala +++ b/persistence-query/src/main/scala/org/apache/pekko/persistence/query/internal/QuerySerializer.scala @@ -124,7 +124,7 @@ import pekko.serialization.Serializers * Deserialize an offset from a stored string representation and manifest. * The offset is converted from its string representation to its real type. */ - private def fromStorageRepresentation(offsetStr: String, manifest: String): Offset = { + private def fromStorageRepresentation(offsetStr: String, manifest: String): Offset = manifest match { case TimestampOffsetManifest => timestampOffsetFromStorageRepresentation(offsetStr) case SequenceOffsetManifest => Offset.sequence(offsetStr.toLong) @@ -148,13 +148,12 @@ import pekko.serialization.Serializers s"in [${getClass.getName}]. [$manifest] doesn't contain two parts.") } } - } /** * Convert the offset to a tuple (String, String) where the first element is * the String representation of the offset and the second element is its manifest. */ - private def toStorageRepresentation(offset: Offset): (String, String) = { + private def toStorageRepresentation(offset: Offset): (String, String) = offset match { case t: TimestampOffset => (timestampOffsetToStorageRepresentation(t), TimestampOffsetManifest) case seq: Sequence => (seq.value.toString, SequenceOffsetManifest) @@ -173,10 +172,9 @@ import pekko.serialization.Serializers s"offset [${offset.getClass.getName}] must not contain [$manifestSeparator] character.") (offsetStr, s"$serializerId$manifestSeparator$serializerManifest") } - } - private def timestampOffsetFromStorageRepresentation(str: String): TimestampOffset = { - try { + private def timestampOffsetFromStorageRepresentation(str: String): TimestampOffset = + try str.split(timestampOffsetSeparator) match { case Array(timestamp, readTimestamp, pid, seqNr) => // optimized for the normal case @@ -198,11 +196,10 @@ import pekko.serialization.Serializers .toMap TimestampOffset(Instant.parse(parts(0)), Instant.parse(parts(1)), seen) } - } catch { + catch { case NonFatal(e) => throw new IllegalArgumentException(s"Unexpected serialized TimestampOffset format [$str].", e) } - } private def timestampOffsetToStorageRepresentation(offset: TimestampOffset): String = { def checkSeparator(pid: String): Unit = diff --git a/persistence-query/src/main/scala/org/apache/pekko/persistence/query/journal/leveldb/AllPersistenceIdsStage.scala b/persistence-query/src/main/scala/org/apache/pekko/persistence/query/journal/leveldb/AllPersistenceIdsStage.scala index e008b1abcb8..fa840946a13 100644 --- a/persistence-query/src/main/scala/org/apache/pekko/persistence/query/journal/leveldb/AllPersistenceIdsStage.scala +++ b/persistence-query/src/main/scala/org/apache/pekko/persistence/query/journal/leveldb/AllPersistenceIdsStage.scala @@ -48,9 +48,8 @@ final private[pekko] class AllPersistenceIdsStage(liveQuery: Boolean, writeJourn override protected def logSource: Class[_] = classOf[AllPersistenceIdsStage] - override def preStart(): Unit = { + override def preStart(): Unit = journal.tell(LeveldbJournal.SubscribeAllPersistenceIds, getStageActor(journalInteraction).ref) - } private def journalInteraction(in: (ActorRef, Any)): Unit = { val (_, msg) = in diff --git a/persistence-query/src/main/scala/org/apache/pekko/persistence/query/journal/leveldb/Buffer.scala b/persistence-query/src/main/scala/org/apache/pekko/persistence/query/journal/leveldb/Buffer.scala index 25f3b4e5d8c..c9270994a2f 100644 --- a/persistence-query/src/main/scala/org/apache/pekko/persistence/query/journal/leveldb/Buffer.scala +++ b/persistence-query/src/main/scala/org/apache/pekko/persistence/query/journal/leveldb/Buffer.scala @@ -30,17 +30,14 @@ private[leveldb] abstract trait Buffer[T] { self: GraphStageLogic => def doPush(out: Outlet[T], elem: T): Unit private val buf: java.util.LinkedList[T] = new util.LinkedList[T]() - def buffer(element: T): Unit = { + def buffer(element: T): Unit = buf.add(element) - } - def buffer(all: Set[T]): Unit = { + def buffer(all: Set[T]): Unit = buf.addAll(all.asJava) - } - def deliverBuf(out: Outlet[T]): Unit = { + def deliverBuf(out: Outlet[T]): Unit = if (!buf.isEmpty && isAvailable(out)) { doPush(out, buf.remove()) } - } def bufferSize: Int = buf.size def bufferEmpty: Boolean = buf.isEmpty } diff --git a/persistence-query/src/main/scala/org/apache/pekko/persistence/query/journal/leveldb/EventsByPersistenceIdStage.scala b/persistence-query/src/main/scala/org/apache/pekko/persistence/query/journal/leveldb/EventsByPersistenceIdStage.scala index 2bc7f10ca60..ebe6cd7563c 100644 --- a/persistence-query/src/main/scala/org/apache/pekko/persistence/query/journal/leveldb/EventsByPersistenceIdStage.scala +++ b/persistence-query/src/main/scala/org/apache/pekko/persistence/query/journal/leveldb/EventsByPersistenceIdStage.scala @@ -76,14 +76,14 @@ final private[pekko] class EventsByPersistenceIdStage( override def preStart(): Unit = { stageActorRef = getStageActor(journalInteraction).ref - refreshInterval.foreach(fd => { + refreshInterval.foreach { fd => scheduleWithFixedDelay(Continue, fd, fd) journal.tell(LeveldbJournal.SubscribePersistenceId(persistenceId), stageActorRef) - }) + } requestMore() } - private def requestMore(): Unit = { + private def requestMore(): Unit = if (!replayInProgress) { val limit = maxBufSize - bufferSize if (limit > 0 && nextSequenceNr <= toSequenceNr) { @@ -95,7 +95,6 @@ final private[pekko] class EventsByPersistenceIdStage( } else { outstandingReplay = true } - } override protected def onTimer(timerKey: Any): Unit = { requestMore() @@ -152,11 +151,10 @@ final private[pekko] class EventsByPersistenceIdStage( private def isCurrentQuery(): Boolean = refreshInterval.isEmpty - private def maybeCompleteStage(): Unit = { + private def maybeCompleteStage(): Unit = if (bufferEmpty && nextSequenceNr > toSequenceNr) { completeStage() } - } override def onPull(): Unit = { requestMore() diff --git a/persistence-query/src/main/scala/org/apache/pekko/persistence/query/journal/leveldb/EventsByTagStage.scala b/persistence-query/src/main/scala/org/apache/pekko/persistence/query/journal/leveldb/EventsByTagStage.scala index 5d514ae5752..779dbc5b396 100644 --- a/persistence-query/src/main/scala/org/apache/pekko/persistence/query/journal/leveldb/EventsByTagStage.scala +++ b/persistence-query/src/main/scala/org/apache/pekko/persistence/query/journal/leveldb/EventsByTagStage.scala @@ -76,10 +76,10 @@ final private[leveldb] class EventsByTagStage( override def preStart(): Unit = { stageActorRef = getStageActor(journalInteraction).ref - refreshInterval.foreach(fd => { + refreshInterval.foreach { fd => scheduleWithFixedDelay(Continue, fd, fd) journal.tell(LeveldbJournal.SubscribeTag(tag), stageActorRef) - }) + } requestMore() } @@ -88,7 +88,7 @@ final private[leveldb] class EventsByTagStage( deliverBuf(out) } - private def requestMore(): Unit = { + private def requestMore(): Unit = if (!replayInProgress) { val limit = maxBufSize - bufferSize if (limit > 0) { @@ -100,7 +100,6 @@ final private[leveldb] class EventsByTagStage( } else { outstandingReplay = true } - } private def journalInteraction(in: (ActorRef, Any)): Unit = { val (_, msg) = in @@ -151,11 +150,10 @@ final private[leveldb] class EventsByTagStage( private def isCurrentQuery(): Boolean = refreshInterval.isEmpty - private def checkComplete(): Unit = { + private def checkComplete(): Unit = if (bufferEmpty && currOffset >= toOffset) { completeStage() } - } override def onPull(): Unit = { requestMore() diff --git a/persistence-query/src/main/scala/org/apache/pekko/persistence/query/journal/leveldb/scaladsl/LeveldbReadJournal.scala b/persistence-query/src/main/scala/org/apache/pekko/persistence/query/journal/leveldb/scaladsl/LeveldbReadJournal.scala index 07f97d03123..558ca61ea46 100644 --- a/persistence-query/src/main/scala/org/apache/pekko/persistence/query/journal/leveldb/scaladsl/LeveldbReadJournal.scala +++ b/persistence-query/src/main/scala/org/apache/pekko/persistence/query/journal/leveldb/scaladsl/LeveldbReadJournal.scala @@ -145,7 +145,7 @@ class LeveldbReadJournal(system: ExtendedActorSystem, config: Config) override def eventsByPersistenceId( persistenceId: String, fromSequenceNr: Long = 0L, - toSequenceNr: Long = Long.MaxValue): Source[EventEnvelope, NotUsed] = { + toSequenceNr: Long = Long.MaxValue): Source[EventEnvelope, NotUsed] = Source .fromMaterializer { (mat, _) => Source @@ -161,7 +161,6 @@ class LeveldbReadJournal(system: ExtendedActorSystem, config: Config) .named("eventsByPersistenceId-" + persistenceId) } .mapMaterializedValue(_ => NotUsed) - } /** * Same type of query as [[#eventsByPersistenceId]] but the event stream @@ -171,7 +170,7 @@ class LeveldbReadJournal(system: ExtendedActorSystem, config: Config) override def currentEventsByPersistenceId( persistenceId: String, fromSequenceNr: Long = 0L, - toSequenceNr: Long = Long.MaxValue): Source[EventEnvelope, NotUsed] = { + toSequenceNr: Long = Long.MaxValue): Source[EventEnvelope, NotUsed] = Source .fromMaterializer { (mat, _) => Source @@ -188,8 +187,6 @@ class LeveldbReadJournal(system: ExtendedActorSystem, config: Config) } .mapMaterializedValue(_ => NotUsed) - } - /** * `eventsByTag` is used for retrieving events that were marked with * a given tag, e.g. all events of an Aggregate Root type. diff --git a/persistence-query/src/test/scala/org/apache/pekko/persistence/query/journal/leveldb/Cleanup.scala b/persistence-query/src/test/scala/org/apache/pekko/persistence/query/journal/leveldb/Cleanup.scala index e75c748b107..891171fbf91 100644 --- a/persistence-query/src/test/scala/org/apache/pekko/persistence/query/journal/leveldb/Cleanup.scala +++ b/persistence-query/src/test/scala/org/apache/pekko/persistence/query/journal/leveldb/Cleanup.scala @@ -26,11 +26,9 @@ trait Cleanup { this: PekkoSpec => "pekko.persistence.journal.leveldb-shared.store.dir", "pekko.persistence.snapshot-store.local.dir").map(s => new File(system.settings.config.getString(s))) - override protected def atStartup(): Unit = { + override protected def atStartup(): Unit = storageLocations.foreach(FileUtils.deleteDirectory) - } - override protected def afterTermination(): Unit = { + override protected def afterTermination(): Unit = storageLocations.foreach(FileUtils.deleteDirectory) - } } diff --git a/persistence-query/src/test/scala/org/apache/pekko/persistence/query/journal/leveldb/EventsByPersistenceIdSpec.scala b/persistence-query/src/test/scala/org/apache/pekko/persistence/query/journal/leveldb/EventsByPersistenceIdSpec.scala index a4d29950b68..6e87725d668 100644 --- a/persistence-query/src/test/scala/org/apache/pekko/persistence/query/journal/leveldb/EventsByPersistenceIdSpec.scala +++ b/persistence-query/src/test/scala/org/apache/pekko/persistence/query/journal/leveldb/EventsByPersistenceIdSpec.scala @@ -55,9 +55,8 @@ class EventsByPersistenceIdSpec extends PekkoSpec(EventsByPersistenceIdSpec.conf ref } - def setupEmpty(persistenceId: String): ActorRef = { + def setupEmpty(persistenceId: String): ActorRef = system.actorOf(TestActor.props(persistenceId)) - } "Leveldb query EventsByPersistenceId" must { diff --git a/persistence-query/src/test/scala/org/apache/pekko/persistence/query/journal/leveldb/EventsByTagSpec.scala b/persistence-query/src/test/scala/org/apache/pekko/persistence/query/journal/leveldb/EventsByTagSpec.scala index 4c8e7d422c6..98b2f3a680d 100644 --- a/persistence-query/src/test/scala/org/apache/pekko/persistence/query/journal/leveldb/EventsByTagSpec.scala +++ b/persistence-query/src/test/scala/org/apache/pekko/persistence/query/journal/leveldb/EventsByTagSpec.scala @@ -203,24 +203,22 @@ class EventsByTagSpec extends PekkoSpec(EventsByTagSpec.config) with Cleanup wit .expectNoMessage(100.millis) .request(10) .expectNext(EventEnvelope(Sequence(3L), "d", 2L, "a black night", 0L)) - } finally { + } finally probe.cancel() - } } "find events from offset (exclusive)" in { val greenSrc = queries.eventsByTag(tag = "green", offset = Sequence(2L)) val probe = greenSrc.runWith(TestSink.probe[Any]) - try { + try probe .request(10) // note that banana is not included, since exclusive offset .expectNext(EventEnvelope(Sequence(3L), "b", 2L, "a green leaf", 0L)) .expectNext(EventEnvelope(Sequence(4L), "c", 1L, "a green cucumber", 0L)) .expectNoMessage(100.millis) - } finally { + finally probe.cancel() - } } "finds events without refresh" in { diff --git a/persistence-shared/src/test/scala/org/apache/pekko/persistence/serialization/SerializerSpec.scala b/persistence-shared/src/test/scala/org/apache/pekko/persistence/serialization/SerializerSpec.scala index 3e245b787d3..70c74bd4b94 100644 --- a/persistence-shared/src/test/scala/org/apache/pekko/persistence/serialization/SerializerSpec.scala +++ b/persistence-shared/src/test/scala/org/apache/pekko/persistence/serialization/SerializerSpec.scala @@ -343,13 +343,11 @@ class MessageSerializerRemotingSpec extends PekkoSpec(remote.withFallback(custom val serialization = SerializationExtension(system) - override protected def atStartup(): Unit = { + override protected def atStartup(): Unit = remoteSystem.actorOf(Props[RemoteActor](), "remote") - } - override def afterTermination(): Unit = { + override def afterTermination(): Unit = Await.ready(remoteSystem.terminate(), Duration.Inf) - } "A message serializer" must { "custom-serialize PersistentRepr messages during remoting" in { diff --git a/persistence-tck/src/main/scala/org/apache/pekko/persistence/CapabilityFlags.scala b/persistence-tck/src/main/scala/org/apache/pekko/persistence/CapabilityFlags.scala index acac5ef412b..32201ce2e2d 100644 --- a/persistence-tck/src/main/scala/org/apache/pekko/persistence/CapabilityFlags.scala +++ b/persistence-tck/src/main/scala/org/apache/pekko/persistence/CapabilityFlags.scala @@ -22,7 +22,7 @@ sealed abstract class CapabilityFlag { val clazz = Class.forName(el.getClassName) clazz.getDeclaredMethod(el.getMethodName).getReturnType == classOf[CapabilityFlag] } - .map { _.getMethodName } + .map(_.getMethodName) .getOrElse("[unknown]") def name: String = capturedStack diff --git a/persistence-tck/src/main/scala/org/apache/pekko/persistence/TestSerializer.scala b/persistence-tck/src/main/scala/org/apache/pekko/persistence/TestSerializer.scala index 2cfd91b4e6b..848b3b5ae8a 100644 --- a/persistence-tck/src/main/scala/org/apache/pekko/persistence/TestSerializer.scala +++ b/persistence-tck/src/main/scala/org/apache/pekko/persistence/TestSerializer.scala @@ -48,7 +48,7 @@ class TestSerializer(system: ExtendedActorSystem) extends SerializerWithStringMa } } - private def verifyTransportInfo(): Unit = { + private def verifyTransportInfo(): Unit = Serialization.currentTransportInformation.value match { case null => throw new IllegalStateException("currentTransportInformation was not set") @@ -59,5 +59,4 @@ class TestSerializer(system: ExtendedActorSystem) extends SerializerWithStringMa throw new IllegalStateException( s"wrong address in currentTransportInformation, ${t.address} != ${system.provider.getDefaultAddress}") } - } } diff --git a/persistence-tck/src/main/scala/org/apache/pekko/persistence/scalatest/MayVerb.scala b/persistence-tck/src/main/scala/org/apache/pekko/persistence/scalatest/MayVerb.scala index ed95760fc34..c35658ca5bf 100644 --- a/persistence-tck/src/main/scala/org/apache/pekko/persistence/scalatest/MayVerb.scala +++ b/persistence-tck/src/main/scala/org/apache/pekko/persistence/scalatest/MayVerb.scala @@ -49,9 +49,8 @@ trait MayVerb { * * @see RFC 2119 */ - def may(right: => Unit)(implicit fun: StringVerbBlockRegistration, pos: Position): Unit = { + def may(right: => Unit)(implicit fun: StringVerbBlockRegistration, pos: Position): Unit = fun(leftSideString, "may", pos, () => right) - } } import scala.language.implicitConversions diff --git a/persistence-tck/src/main/scala/org/apache/pekko/persistence/snapshot/SnapshotStoreSpec.scala b/persistence-tck/src/main/scala/org/apache/pekko/persistence/snapshot/SnapshotStoreSpec.scala index 9f985ee505e..377e5a7a2ce 100644 --- a/persistence-tck/src/main/scala/org/apache/pekko/persistence/snapshot/SnapshotStoreSpec.scala +++ b/persistence-tck/src/main/scala/org/apache/pekko/persistence/snapshot/SnapshotStoreSpec.scala @@ -73,13 +73,12 @@ abstract class SnapshotStoreSpec(config: Config) def snapshotStore: ActorRef = extension.snapshotStoreFor(null) - def writeSnapshots(): Seq[SnapshotMetadata] = { + def writeSnapshots(): Seq[SnapshotMetadata] = (1 to 5).map { i => val metadata = SnapshotMetadata(pid, i + 10) snapshotStore.tell(SaveSnapshot(metadata, s"s-$i"), senderProbe.ref) senderProbe.expectMsgPF() { case SaveSnapshotSuccess(md) => md } } - } /** * The limit defines a number of bytes persistence plugin can support to store the snapshot. diff --git a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/EventStorage.scala b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/EventStorage.scala index 092656d3156..0acd508d17a 100644 --- a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/EventStorage.scala +++ b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/EventStorage.scala @@ -127,23 +127,21 @@ private[testkit] trait EventStorage extends TestKitStorage[JournalOperation, Per } } - def tryReadSeqNumber(persistenceId: String): Long = { + def tryReadSeqNumber(persistenceId: String): Long = currentPolicy.tryProcess(persistenceId, ReadSeqNum) match { case ProcessingSuccess => getHighestSeqNumber(persistenceId) case Reject(ex) => throw ex case StorageFailure(ex) => throw ex } - } - def tryDelete(persistenceId: String, toSeqNumber: Long): Unit = { + def tryDelete(persistenceId: String, toSeqNumber: Long): Unit = currentPolicy.tryProcess(persistenceId, DeleteEvents(toSeqNumber)) match { case ProcessingSuccess => deleteToSeqNumber(persistenceId, toSeqNumber) case Reject(ex) => throw ex case StorageFailure(ex) => throw ex } - } - def currentPersistenceIds(afterId: Option[String], limit: Long): Source[String, NotUsed] = { + def currentPersistenceIds(afterId: Option[String], limit: Long): Source[String, NotUsed] = afterId match { case Some(id) => keys().sorted.dropWhile(_ != id) match { @@ -154,8 +152,6 @@ private[testkit] trait EventStorage extends TestKitStorage[JournalOperation, Per Source(keys().sorted).take(limit) } - } - private def mapAny(key: String, elems: immutable.Seq[Any]): immutable.Seq[PersistentRepr] = { val sn = getHighestSeqNumber(key) + 1 elems.zipWithIndex.map(p => PersistentRepr(p._1, p._2 + sn, key)) diff --git a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/PersistenceTestKitPlugin.scala b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/PersistenceTestKitPlugin.scala index c12d206ad13..eef59246b1c 100644 --- a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/PersistenceTestKitPlugin.scala +++ b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/PersistenceTestKitPlugin.scala @@ -44,8 +44,8 @@ class PersistenceTestKitPlugin(@unused cfg: Config, cfgPath: String) extends Asy } private val eventStream = context.system.eventStream - override def asyncWriteMessages(messages: immutable.Seq[AtomicWrite]): Future[immutable.Seq[Try[Unit]]] = { - Future.fromTry(Try(messages.map(aw => { + override def asyncWriteMessages(messages: immutable.Seq[AtomicWrite]): Future[immutable.Seq[Try[Unit]]] = + Future.fromTry(Try(messages.map { aw => val timestamp = CurrentTime.now() val data = aw.payload.map(pl => pl.payload match { @@ -59,8 +59,7 @@ class PersistenceTestKitPlugin(@unused cfg: Config, cfgPath: String) extends Asy } } result - }))) - } + })) override def asyncDeleteMessagesTo(persistenceId: String, toSequenceNr: Long): Future[Unit] = Future.fromTry(Try(storage.tryDelete(persistenceId, toSequenceNr))) diff --git a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/ProcessingPolicy.scala b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/ProcessingPolicy.scala index 1d7c0bc0215..6f2c2642e97 100644 --- a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/ProcessingPolicy.scala +++ b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/ProcessingPolicy.scala @@ -95,13 +95,12 @@ object ProcessingPolicy { cond: (String, U) => Boolean) extends PolicyType { - override def tryProcess(persistenceId: String, processingUnit: U): ProcessingResult = { + override def tryProcess(persistenceId: String, processingUnit: U): ProcessingResult = if (cond(persistenceId, processingUnit)) { returnOnTrigger } else { returnNonTrigger } - } } diff --git a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/SnapshotStorage.scala b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/SnapshotStorage.scala index 0a4d9b1ac26..5d3e0292afe 100644 --- a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/SnapshotStorage.scala +++ b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/SnapshotStorage.scala @@ -37,7 +37,7 @@ private[testkit] trait SnapshotStorage override protected val DefaultPolicy = SnapshotPolicies.PassAll - def tryAdd(meta: SnapshotMetadata, payload: Any): Unit = { + def tryAdd(meta: SnapshotMetadata, payload: Any): Unit = currentPolicy.tryProcess(meta.persistenceId, WriteSnapshot(SnapshotMeta(meta.sequenceNr, meta.timestamp), payload)) match { case ProcessingSuccess => @@ -46,7 +46,6 @@ private[testkit] trait SnapshotStorage case f: ProcessingFailure => throw f.error } - } def tryRead(persistenceId: String, criteria: SnapshotSelectionCriteria): Option[SelectedSnapshot] = { val selectedSnapshot = @@ -58,22 +57,20 @@ private[testkit] trait SnapshotStorage } } - def tryDelete(persistenceId: String, selectionCriteria: SnapshotSelectionCriteria): Unit = { + def tryDelete(persistenceId: String, selectionCriteria: SnapshotSelectionCriteria): Unit = currentPolicy.tryProcess(persistenceId, DeleteSnapshotsByCriteria(selectionCriteria)) match { case ProcessingSuccess => delete(persistenceId, v => selectionCriteria.matches(v._1)) case f: ProcessingFailure => throw f.error } - } - def tryDelete(meta: SnapshotMetadata): Unit = { + def tryDelete(meta: SnapshotMetadata): Unit = currentPolicy.tryProcess(meta.persistenceId, DeleteSnapshotByMeta(SnapshotMeta(meta.sequenceNr, meta.timestamp))) match { case ProcessingSuccess => delete(meta.persistenceId, _._1.sequenceNr == meta.sequenceNr) case f: ProcessingFailure => throw f.error } - } } diff --git a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/internal/EventSourcedBehaviorTestKitImpl.scala b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/internal/EventSourcedBehaviorTestKitImpl.scala index 93d10ff3f98..2228598875d 100644 --- a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/internal/EventSourcedBehaviorTestKitImpl.scala +++ b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/internal/EventSourcedBehaviorTestKitImpl.scala @@ -53,9 +53,8 @@ import pekko.stream.scaladsl.Sink override def hasNoEvents: Boolean = events.isEmpty - override def event: Event = { + override def event: Event = if (events.nonEmpty) events.head else throw new AssertionError("No events") - } override def eventOfType[E <: Event: ClassTag]: E = ofType(event, "event") @@ -69,7 +68,7 @@ import pekko.stream.scaladsl.Sink ofType(reply, "reply") // cast with nice error message - private def ofType[A: ClassTag](obj: Any, errorParam: String): A = { + private def ofType[A: ClassTag](obj: Any, errorParam: String): A = obj match { case a: A => a case other => @@ -78,7 +77,6 @@ import pekko.stream.scaladsl.Sink s"Expected $errorParam class [${expectedClass.getName}], " + s"but was [${other.getClass.getName}]") } - } override def hasNoReply: Boolean = replyOption.isEmpty } @@ -124,9 +122,9 @@ import pekko.stream.scaladsl.Sink private def internalActor = actor.unsafeUpcast[Any] private val persistenceId: PersistenceId = { internalActor ! EventSourcedBehaviorImpl.GetPersistenceId(probe.ref) - try { + try probe.expectMessageType[PersistenceId] - } catch { + catch { case NonFatal(_) => throw new IllegalArgumentException("Only EventSourcedBehavior, or nested EventSourcedBehavior allowed.") } @@ -158,14 +156,13 @@ import pekko.stream.scaladsl.Sink actor ! command val reply = - try { + try replyProbe.receiveMessage() - } catch { + catch { case NonFatal(_) => throw new AssertionError(s"Missing expected reply for command [$command].") - } finally { + } finally replyProbe.stop() - } val newState = getState() val newEvents = getEvents(seqNrBefore + 1) @@ -199,7 +196,7 @@ import pekko.stream.scaladsl.Sink stateProbe.receiveMessage().currentState } - private def preCommandCheck(command: Command): Unit = { + private def preCommandCheck(command: Command): Unit = if (serializationSettings.enabled) { if (serializationSettings.verifyCommands) verifySerializationAndThrow(command, "Command") @@ -210,9 +207,8 @@ import pekko.stream.scaladsl.Sink emptyStateVerified = true } } - } - private def postCommandCheck(newEvents: immutable.Seq[Event], newState: State, reply: Option[Any]): Unit = { + private def postCommandCheck(newEvents: immutable.Seq[Event], newState: State, reply: Option[Any]): Unit = if (serializationSettings.enabled) { if (serializationSettings.verifyEvents) { newEvents.foreach(verifySerializationAndThrow(_, "Event")) @@ -225,7 +221,6 @@ import pekko.stream.scaladsl.Sink reply.foreach(verifySerializationAndThrow(_, "Reply")) } } - } override def restart(): RestartResult[State] = { actorTestKit.stop(actor) @@ -246,14 +241,13 @@ import pekko.stream.scaladsl.Sink restart() } - private def verifySerializationAndThrow(obj: Any, errorMessagePrefix: String): Unit = { - try { + private def verifySerializationAndThrow(obj: Any, errorMessagePrefix: String): Unit = + try serializationTestKit.verifySerialization(obj, serializationSettings.verifyEquality) - } catch { + catch { case NonFatal(exc) => throw new IllegalArgumentException(s"$errorMessagePrefix [$obj] isn't serializable.", exc) } - } override def initialize(state: State, events: Event*): Unit = internalInitialize(Some(state), events: _*) diff --git a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/internal/InMemStorageExtension.scala b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/internal/InMemStorageExtension.scala index 3846ebd6492..f28d196457d 100644 --- a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/internal/InMemStorageExtension.scala +++ b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/internal/InMemStorageExtension.scala @@ -57,13 +57,13 @@ final class InMemStorageExtension(system: ExtendedActorSystem) extends Extension def storageFor(key: String): EventStorage = stores.computeIfAbsent(key, - _ => { + _ => // we don't really care about the key here, we just want separate instances if (PersistenceTestKit.Settings(system).serialize) { new SerializedEventStorageImpl(system) } else { new SimpleEventStorageImpl } - }) + ) } diff --git a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/internal/PersistenceInitImpl.scala b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/internal/PersistenceInitImpl.scala index 7dd2384c1db..67cda2ac864 100644 --- a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/internal/PersistenceInitImpl.scala +++ b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/internal/PersistenceInitImpl.scala @@ -27,9 +27,8 @@ import pekko.persistence.RecoveryCompleted */ @InternalApi private[pekko] object PersistenceInitImpl { - def props(journalPluginId: String, snapshotPluginId: String, persistenceId: String): Props = { + def props(journalPluginId: String, snapshotPluginId: String, persistenceId: String): Props = Props(new PersistenceInitImpl(journalPluginId, snapshotPluginId, persistenceId)) - } } /** diff --git a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/internal/TestKitStorage.scala b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/internal/TestKitStorage.scala index ba36b054483..da97a47dd45 100644 --- a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/internal/TestKitStorage.scala +++ b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/internal/TestKitStorage.scala @@ -77,7 +77,7 @@ sealed trait InMemStorage[K, R] extends InternalReprSupport[R] { .map(toRepr) } - def add(key: K, p: R): Unit = { + def add(key: K, p: R): Unit = lock.synchronized { if (!expectNextQueue.contains(key)) { expectNextQueue = expectNextQueue + (key -> Vector.empty) @@ -89,7 +89,6 @@ sealed trait InMemStorage[K, R] extends InternalReprSupport[R] { } add(key, Vector(p)) } - } /** * Adds elements ordered by seqnum, sets new seqnum as max(old, max(newElemsSeqNums))) @@ -159,9 +158,9 @@ sealed trait InMemStorage[K, R] extends InternalReprSupport[R] { def deleteToSeqNumber(key: K, toSeqNumberInclusive: Long): Unit = updateOrSetNew(key, - value => { + value => value.dropWhile(reprToSeqNum(_) <= toSeqNumberInclusive) - }) + ) def clearAllPreservingSeqNumbers(): Unit = lock.synchronized { eventsMap.keys.foreach(removePreservingSeqNumber) diff --git a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/javadsl/EventSourcedBehaviorTestKit.scala b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/javadsl/EventSourcedBehaviorTestKit.scala index e42d3b68d7a..6ffa04151e8 100644 --- a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/javadsl/EventSourcedBehaviorTestKit.scala +++ b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/javadsl/EventSourcedBehaviorTestKit.scala @@ -93,9 +93,8 @@ object EventSourcedBehaviorTestKit { verifyEquality: Boolean = this.verifyEquality, verifyCommands: Boolean = this.verifyCommands, verifyEvents: Boolean = this.verifyEvents, - verifyState: Boolean = this.verifyState): SerializationSettings = { + verifyState: Boolean = this.verifyState): SerializationSettings = new SerializationSettings(enabled, verifyEquality, verifyCommands, verifyEvents, verifyState) - } } /** diff --git a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/query/internal/EventsByPersistenceIdStage.scala b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/query/internal/EventsByPersistenceIdStage.scala index 7a4149e2216..d3d160e6ac2 100644 --- a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/query/internal/EventsByPersistenceIdStage.scala +++ b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/query/internal/EventsByPersistenceIdStage.scala @@ -34,7 +34,7 @@ final private[pekko] class EventsByPersistenceIdStage( val out: Outlet[EventEnvelope] = Outlet("EventsByPersistenceIdSource") override def shape: SourceShape[EventEnvelope] = SourceShape(out) - override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = { + override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = new GraphStageLogicWithLogging(shape) with OutHandler { private var currentSequenceNr = math.max(fromSequenceNr, 1) private var stageActorRef: ActorRef = null @@ -54,7 +54,7 @@ final private[pekko] class EventsByPersistenceIdStage( } } - private def tryPush(): Unit = { + private def tryPush(): Unit = if (isAvailable(out)) { val event = storage.tryRead(persistenceId, currentSequenceNr, currentSequenceNr, 1) log.debug("tryPush available. Query for {} {} result {}", currentSequenceNr, currentSequenceNr, event) @@ -76,15 +76,11 @@ final private[pekko] class EventsByPersistenceIdStage( } else { log.debug("tryPush, no demand") } - } - override def onPull(): Unit = { + override def onPull(): Unit = tryPush() - } setHandler(out, this) } - } - } diff --git a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/query/scaladsl/PersistenceTestKitReadJournal.scala b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/query/scaladsl/PersistenceTestKitReadJournal.scala index 859f731e53a..69574491755 100644 --- a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/query/scaladsl/PersistenceTestKitReadJournal.scala +++ b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/query/scaladsl/PersistenceTestKitReadJournal.scala @@ -71,14 +71,13 @@ final class PersistenceTestKitReadJournal(system: ExtendedActorSystem, @unused c override def eventsByPersistenceId( persistenceId: String, fromSequenceNr: Long = 0, - toSequenceNr: Long = Long.MaxValue): Source[EventEnvelope, NotUsed] = { + toSequenceNr: Long = Long.MaxValue): Source[EventEnvelope, NotUsed] = Source.fromGraph(new EventsByPersistenceIdStage(persistenceId, fromSequenceNr, toSequenceNr, storage)) - } override def currentEventsByPersistenceId( persistenceId: String, fromSequenceNr: Long = 0, - toSequenceNr: Long = Long.MaxValue): Source[EventEnvelope, NotUsed] = { + toSequenceNr: Long = Long.MaxValue): Source[EventEnvelope, NotUsed] = Source(storage.tryRead(persistenceId, fromSequenceNr, toSequenceNr, Long.MaxValue)).map { pr => EventEnvelope( Sequence(pr.sequenceNr), @@ -88,7 +87,6 @@ final class PersistenceTestKitReadJournal(system: ExtendedActorSystem, @unused c pr.timestamp, pr.metadata) } - } override def currentEventsByTag(tag: String, offset: Offset = NoOffset): Source[EventEnvelope, NotUsed] = { offset match { diff --git a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/scaladsl/EventSourcedBehaviorTestKit.scala b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/scaladsl/EventSourcedBehaviorTestKit.scala index 4e73dff87df..52f1ef9a3cc 100644 --- a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/scaladsl/EventSourcedBehaviorTestKit.scala +++ b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/scaladsl/EventSourcedBehaviorTestKit.scala @@ -96,9 +96,8 @@ object EventSourcedBehaviorTestKit { verifyEquality: Boolean = this.verifyEquality, verifyCommands: Boolean = this.verifyCommands, verifyEvents: Boolean = this.verifyEvents, - verifyState: Boolean = this.verifyState): SerializationSettings = { + verifyState: Boolean = this.verifyState): SerializationSettings = new SerializationSettings(enabled, verifyEquality, verifyCommands, verifyEvents, verifyState) - } } /** diff --git a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/scaladsl/PersistenceTestKit.scala b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/scaladsl/PersistenceTestKit.scala index 379ecd75a00..f6358deab26 100644 --- a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/scaladsl/PersistenceTestKit.scala +++ b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/scaladsl/PersistenceTestKit.scala @@ -338,9 +338,8 @@ class SnapshotTestKit(system: ActorSystem) override protected val storage: SnapshotStorage = SnapshotStorageEmulatorExtension(system) - override def getItem(persistenceId: String, nextInd: Int): Option[Any] = { + override def getItem(persistenceId: String, nextInd: Int): Option[Any] = storage.firstInExpectNextQueue(persistenceId).map(reprToAny) - } override def expectNextPersisted[A](persistenceId: String, event: A): A = { val item = super.expectNextPersisted(persistenceId, event) diff --git a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/state/javadsl/PersistenceTestKitDurableStateStore.scala b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/state/javadsl/PersistenceTestKitDurableStateStore.scala index ea95141fc66..deff28fd354 100644 --- a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/state/javadsl/PersistenceTestKitDurableStateStore.scala +++ b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/state/javadsl/PersistenceTestKitDurableStateStore.scala @@ -50,12 +50,10 @@ class PersistenceTestKitDurableStateStore[A](stateStore: SStore[A]) def deleteObject(persistenceId: String, revision: Long): CompletionStage[Done] = stateStore.deleteObject(persistenceId, revision).asJava - def changes(tag: String, offset: Offset): Source[DurableStateChange[A], pekko.NotUsed] = { + def changes(tag: String, offset: Offset): Source[DurableStateChange[A], pekko.NotUsed] = stateStore.changes(tag, offset).asJava - } - def currentChanges(tag: String, offset: Offset): Source[DurableStateChange[A], pekko.NotUsed] = { + def currentChanges(tag: String, offset: Offset): Source[DurableStateChange[A], pekko.NotUsed] = stateStore.currentChanges(tag, offset).asJava - } override def currentChangesBySlices( entityType: String, diff --git a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/state/scaladsl/PersistenceTestKitDurableStateStore.scala b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/state/scaladsl/PersistenceTestKitDurableStateStore.scala index 9af65831d55..03601cf3691 100644 --- a/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/state/scaladsl/PersistenceTestKitDurableStateStore.scala +++ b/persistence-testkit/src/main/scala/org/apache/pekko/persistence/testkit/state/scaladsl/PersistenceTestKitDurableStateStore.scala @@ -108,13 +108,12 @@ class PersistenceTestKitDurableStateStore[A](val system: ExtendedActorSystem) Source(store.values.toVector.filter(byTagFromOffset).sortBy(_.globalOffset)) .concat(changesSource) .filter(byTagFromOffsetNotDeleted) - .statefulMap(() => EarliestOffset)((globalOffsetSeen, record) => { + .statefulMap(() => EarliestOffset)((globalOffsetSeen, record) => if (record.globalOffset > globalOffsetSeen) { (record.globalOffset, Some(record)) } else { (globalOffsetSeen, None) - } - }, _ => None) + }, _ => None) .collect { case Some(record) => record } .map(_.toDurableStateChange) } @@ -170,13 +169,12 @@ class PersistenceTestKitDurableStateStore[A](val system: ExtendedActorSystem) Source(store.values.toVector.filter(bySliceFromOffset).sortBy(_.globalOffset)) .concat(changesSource) .filter(bySliceFromOffsetNotDeleted) - .statefulMap(() => EarliestOffset)((globalOffsetSeen, record) => { + .statefulMap(() => EarliestOffset)((globalOffsetSeen, record) => if (record.globalOffset > globalOffsetSeen) { (record.globalOffset, Some(record)) } else { (globalOffsetSeen, None) - } - }, _ => None) + }, _ => None) .collect { case Some(record) => record } .map(_.toDurableStateChange) } @@ -211,12 +209,11 @@ private final case class Record[A]( value: Option[A], tag: String, timestamp: Long = System.currentTimeMillis) { - def toDurableStateChange: DurableStateChange[A] = { + def toDurableStateChange: DurableStateChange[A] = value match { case Some(v) => new UpdatedDurableState(persistenceId, revision, v, Sequence(globalOffset), timestamp) case None => new DeletedDurableState(persistenceId, revision, Sequence(globalOffset), timestamp) } - } } diff --git a/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/javadsl/CommonSnapshotTests.scala b/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/javadsl/CommonSnapshotTests.scala index 1743480c28f..890bfc73e43 100644 --- a/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/javadsl/CommonSnapshotTests.scala +++ b/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/javadsl/CommonSnapshotTests.scala @@ -71,7 +71,7 @@ trait CommonSnapshotTests extends JavaDslUtils { val err = new Exception("BOOM!") val newPolicy = new SnapshotStorage.SnapshotPolicies.PolicyType { - override def tryProcess(persistenceId: String, processingUnit: SnapshotOperation): ProcessingResult = { + override def tryProcess(persistenceId: String, processingUnit: SnapshotOperation): ProcessingResult = processingUnit match { case WriteSnapshot(_, msgs) => val ex = msgs match { @@ -85,7 +85,6 @@ trait CommonSnapshotTests extends JavaDslUtils { } case _ => ProcessingSuccess } - } } withPolicy(newPolicy) diff --git a/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/javadsl/CommonTestKitTests.scala b/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/javadsl/CommonTestKitTests.scala index d3b1d27d5b4..8da7178e8d2 100644 --- a/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/javadsl/CommonTestKitTests.scala +++ b/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/javadsl/CommonTestKitTests.scala @@ -111,7 +111,7 @@ trait CommonTestKitTests extends JavaDslUtils { val err = new Exception("BOOM!") val newPolicy = new EventStorage.JournalPolicies.PolicyType { - override def tryProcess(persistenceId: String, processingUnit: JournalOperation): ProcessingResult = { + override def tryProcess(persistenceId: String, processingUnit: JournalOperation): ProcessingResult = processingUnit match { case WriteEvents(msgs) => val ex = msgs.exists { @@ -125,7 +125,6 @@ trait CommonTestKitTests extends JavaDslUtils { } case _ => ProcessingSuccess } - } } withPolicy(newPolicy) diff --git a/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/javadsl/JavaDslUtils.scala b/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/javadsl/JavaDslUtils.scala index ff677c848d4..23fecf7ab4a 100644 --- a/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/javadsl/JavaDslUtils.scala +++ b/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/javadsl/JavaDslUtils.scala @@ -34,12 +34,12 @@ trait JavaDslUtils extends CommonUtils { override protected def commandHandler(): CommandHandler[TestCommand, Evt, EmptyState] = newCommandHandlerBuilder() .forAnyState() - .onAnyCommand((command: TestCommand) => { + .onAnyCommand { (command: TestCommand) => command match { case Cmd(data) => Effect.persist(Evt(data)) case Passivate => Effect.stop().thenRun((_: EmptyState) => replyOnRecovery.foreach(_ ! Stopped)) } - }) + } override protected def eventHandler(): EventHandler[EmptyState, Evt] = newEventHandlerBuilder().forAnyState().onAnyEvent(_ => emptyState) @@ -49,13 +49,12 @@ trait JavaDslUtils extends CommonUtils { override def signalHandler(): SignalHandler[EmptyState] = newSignalHandlerBuilder().onSignal(RecoveryCompleted, _ => replyOnRecovery.foreach(_ ! Recovered)).build - override def tagsFor(event: Evt): util.Set[String] = { + override def tagsFor(event: Evt): util.Set[String] = if (setConstantTag) { util.Collections.singleton("tag") } else { super.tagsFor(event) } - } } } diff --git a/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/query/CurrentEventsByTagSpec.scala b/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/query/CurrentEventsByTagSpec.scala index bfcba39caf6..68457d5d959 100644 --- a/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/query/CurrentEventsByTagSpec.scala +++ b/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/query/CurrentEventsByTagSpec.scala @@ -36,12 +36,11 @@ class CurrentEventsByTagSpec private val queries = PersistenceQuery(system).readJournalFor[PersistenceTestKitReadJournal](PersistenceTestKitReadJournal.Identifier) - def setupEmpty(persistenceId: String): ActorRef[Command] = { + def setupEmpty(persistenceId: String): ActorRef[Command] = spawn( testBehaviour(persistenceId).withTagger(evt => if (evt.indexOf('-') > 0) Set(evt.split('-')(1), "all") else Set("all"))) - } "Persistent test kit currentEventsByTag query" must { diff --git a/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/query/EventsByPersistenceIdSpec.scala b/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/query/EventsByPersistenceIdSpec.scala index bf2eb166f35..d1eabf53e3a 100644 --- a/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/query/EventsByPersistenceIdSpec.scala +++ b/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/query/EventsByPersistenceIdSpec.scala @@ -39,7 +39,7 @@ object EventsByPersistenceIdSpec { case class Command(evt: String, ack: ActorRef[Done]) case class State() - def testBehaviour(persistenceId: String) = { + def testBehaviour(persistenceId: String) = EventSourcedBehavior[Command, String, State]( PersistenceId.ofUniqueId(persistenceId), State(), @@ -48,7 +48,6 @@ object EventsByPersistenceIdSpec { command.ack ! Done }, (state, _) => state) - } } @@ -75,9 +74,8 @@ class EventsByPersistenceIdSpec ref } - def setupEmpty(persistenceId: String): ActorRef[Command] = { + def setupEmpty(persistenceId: String): ActorRef[Command] = spawn(testBehaviour(persistenceId)) - } "Persistent test kit live query EventsByPersistenceId" must { "find new events" in { diff --git a/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/scaladsl/CommonSnapshotTests.scala b/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/scaladsl/CommonSnapshotTests.scala index ea555f695cf..eb4aa1c23f2 100644 --- a/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/scaladsl/CommonSnapshotTests.scala +++ b/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/scaladsl/CommonSnapshotTests.scala @@ -92,7 +92,7 @@ trait CommonSnapshotTests extends ScalaDslUtils { val err = new Exception("BOOM!") val newPolicy = new SnapshotStorage.SnapshotPolicies.PolicyType { - override def tryProcess(persistenceId: String, processingUnit: SnapshotOperation): ProcessingResult = { + override def tryProcess(persistenceId: String, processingUnit: SnapshotOperation): ProcessingResult = processingUnit match { case WriteSnapshot(_, msgs) => val ex = msgs match { @@ -106,7 +106,6 @@ trait CommonSnapshotTests extends ScalaDslUtils { } case _ => ProcessingSuccess } - } } withPolicy(newPolicy) diff --git a/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/scaladsl/CommonTestKitTests.scala b/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/scaladsl/CommonTestKitTests.scala index 8b7703af3e1..78d71faeccd 100644 --- a/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/scaladsl/CommonTestKitTests.scala +++ b/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/scaladsl/CommonTestKitTests.scala @@ -129,7 +129,7 @@ trait CommonTestKitTests extends ScalaDslUtils { val err = new Exception("BOOM!") val newPolicy = new EventStorage.JournalPolicies.PolicyType { - override def tryProcess(persistenceId: String, processingUnit: JournalOperation): ProcessingResult = { + override def tryProcess(persistenceId: String, processingUnit: JournalOperation): ProcessingResult = processingUnit match { case WriteEvents(msgs) => val ex = msgs.exists { @@ -143,7 +143,6 @@ trait CommonTestKitTests extends ScalaDslUtils { } case _ => ProcessingSuccess } - } } withPolicy(newPolicy) diff --git a/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/scaladsl/EventSourcedBehaviorNoSnapshotTestKitSpec.scala b/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/scaladsl/EventSourcedBehaviorNoSnapshotTestKitSpec.scala index 716658a09ad..d449d0ab9b3 100644 --- a/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/scaladsl/EventSourcedBehaviorNoSnapshotTestKitSpec.scala +++ b/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/scaladsl/EventSourcedBehaviorNoSnapshotTestKitSpec.scala @@ -30,11 +30,10 @@ class EventSourcedBehaviorNoSnapshotTestKitSpec with AnyWordSpecLike with LogCapturing { - private def createTestKit() = { + private def createTestKit() = EventSourcedBehaviorTestKit[TestCounter.Command, TestCounter.Event, TestCounter.State]( system, TestCounter(PersistenceId.ofUniqueId("test"))) - } "EventSourcedBehaviorTestKit" when { "snapshots are not enabled" must { diff --git a/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/scaladsl/EventSourcedBehaviorTestKitSpec.scala b/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/scaladsl/EventSourcedBehaviorTestKitSpec.scala index 98e38ebf4c8..c40ebafd3a7 100644 --- a/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/scaladsl/EventSourcedBehaviorTestKitSpec.scala +++ b/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/scaladsl/EventSourcedBehaviorTestKitSpec.scala @@ -79,7 +79,7 @@ object EventSourcedBehaviorTestKitSpec { private def counter( ctx: ActorContext[Command], persistenceId: PersistenceId, - emptyState: State): EventSourcedBehavior[Command, Event, State] = { + emptyState: State): EventSourcedBehavior[Command, Event, State] = EventSourcedBehavior.withEnforcedReplies[Command, Event, State]( persistenceId, emptyState, @@ -135,7 +135,6 @@ object EventSourcedBehaviorTestKitSpec { case (null, _) => NullState() case (NullState(), _) => NullState() }) - } } } @@ -149,15 +148,13 @@ class EventSourcedBehaviorTestKitSpec private val persistenceId = PersistenceId.ofUniqueId("test") private val behavior = TestCounter(persistenceId) - private def createTestKitNull() = { + private def createTestKitNull() = EventSourcedBehaviorTestKit[TestCounter.Command, TestCounter.Event, TestCounter.State]( system, TestCounter(persistenceId, null)) - } - private def createTestKit() = { + private def createTestKit() = EventSourcedBehaviorTestKit[TestCounter.Command, TestCounter.Event, TestCounter.State](system, behavior) - } "EventSourcedBehaviorTestKit" must { diff --git a/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/scaladsl/PersistenceTestKitJournalCompatSpec.scala b/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/scaladsl/PersistenceTestKitJournalCompatSpec.scala index a30e72ac758..19a03e8aa13 100644 --- a/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/scaladsl/PersistenceTestKitJournalCompatSpec.scala +++ b/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/scaladsl/PersistenceTestKitJournalCompatSpec.scala @@ -29,7 +29,7 @@ class PersistenceTestKitJournalCompatSpec extends JournalSpec(config = Persisten override def beforeAll(): Unit = { super.beforeAll() InMemStorageExtension(system).setPolicy(new JournalPolicies.PolicyType { - override def tryProcess(persistenceId: String, op: JournalOperation): ProcessingResult = { + override def tryProcess(persistenceId: String, op: JournalOperation): ProcessingResult = op match { case WriteEvents(batch) => val allSerializable = @@ -42,7 +42,6 @@ class PersistenceTestKitJournalCompatSpec extends JournalSpec(config = Persisten case _ => ProcessingSuccess } - } }) } diff --git a/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/scaladsl/ScalaDslUtils.scala b/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/scaladsl/ScalaDslUtils.scala index 54e44371c65..57c533db925 100644 --- a/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/scaladsl/ScalaDslUtils.scala +++ b/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/scaladsl/ScalaDslUtils.scala @@ -34,12 +34,11 @@ trait ScalaDslUtils extends CommonUtils { def eventSourcedBehavior(pid: String, replyOnRecovery: Option[ActorRef[Any]] = None) = EventSourcedBehavior[TestCommand, Evt, EmptyState](PersistenceId.ofUniqueId(pid), EmptyState(), - (_, cmd) => { + (_, cmd) => cmd match { case Cmd(data) => Effect.persist(Evt(data)) case Passivate => Effect.stop().thenRun(_ => replyOnRecovery.foreach(_ ! Stopped)) - } - }, (_, _) => EmptyState()).snapshotWhen((_, _, _) => true).receiveSignal { + }, (_, _) => EmptyState()).snapshotWhen((_, _, _) => true).receiveSignal { case (_, RecoveryCompleted) => replyOnRecovery.foreach(_ ! Recovered) } @@ -47,12 +46,11 @@ trait ScalaDslUtils extends CommonUtils { EventSourcedBehavior[TestCommand, Evt, NonEmptyState]( PersistenceId.ofUniqueId(pid), NonEmptyState(""), - (_, cmd) => { + (_, cmd) => cmd match { case Cmd(data) => Effect.persist(Evt(data)) case Passivate => Effect.stop().thenRun(_ => replyOnRecovery.foreach(_ ! Stopped)) - } - }, + }, (state: NonEmptyState, event: Evt) => NonEmptyState(s"${state.data}${event.data}")).receiveSignal { case (_, RecoveryCompleted) => replyOnRecovery.foreach(_ ! Recovered) } diff --git a/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/state/scaladsl/PersistenceTestKitDurableStateStoreSpec.scala b/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/state/scaladsl/PersistenceTestKitDurableStateStoreSpec.scala index faf69d35536..c7a0df30f15 100644 --- a/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/state/scaladsl/PersistenceTestKitDurableStateStoreSpec.scala +++ b/persistence-testkit/src/test/scala/org/apache/pekko/persistence/testkit/state/scaladsl/PersistenceTestKitDurableStateStoreSpec.scala @@ -211,9 +211,8 @@ class PersistenceTestKitDurableStateStoreSpec val record = Record(1, "name-1") val tag = "tag-1" val ids = (1 to 20).map(i => s"id-$i") - for (id <- ids) { + for (id <- ids) stateStore.upsertObject(id, 1, record, tag) - } val resultIds = stateStore.currentPersistenceIds(None, Long.MaxValue).runWith(Sink.seq).futureValue resultIds should have size 20 @@ -226,9 +225,8 @@ class PersistenceTestKitDurableStateStoreSpec val record = Record(1, "name-1") val tag = "tag-1" val ids = (1 to 20).map(i => s"id-$i") - for (id <- ids) { + for (id <- ids) stateStore.upsertObject(id, 1, record, tag) - } val page1 = stateStore.currentPersistenceIds(None, 9).runWith(Sink.seq).futureValue page1 should have size 9 diff --git a/persistence-typed-tests/src/test/scala/docs/org/apache/pekko/persistence/typed/ReplicatedAuctionExampleSpec.scala b/persistence-typed-tests/src/test/scala/docs/org/apache/pekko/persistence/typed/ReplicatedAuctionExampleSpec.scala index 920905327b7..f0fe50dcd91 100644 --- a/persistence-typed-tests/src/test/scala/docs/org/apache/pekko/persistence/typed/ReplicatedAuctionExampleSpec.scala +++ b/persistence-typed-tests/src/test/scala/docs/org/apache/pekko/persistence/typed/ReplicatedAuctionExampleSpec.scala @@ -192,7 +192,7 @@ object ReplicatedAuctionExampleSpec { // #setup // #command-handler - def commandHandler(state: AuctionState, command: Command): Effect[Event, AuctionState] = { + def commandHandler(state: AuctionState, command: Command): Effect[Event, AuctionState] = state.phase match { case Closing(_) | Closed => command match { @@ -238,7 +238,6 @@ object ReplicatedAuctionExampleSpec { Effect.none } } - } // #command-handler // #event-handler @@ -256,7 +255,7 @@ object ReplicatedAuctionExampleSpec { // #event-handler // #event-triggers - private def eventTriggers(event: Event, newState: AuctionState): Unit = { + private def eventTriggers(event: Event, newState: AuctionState): Unit = event match { case finished: AuctionFinished => newState.phase match { @@ -276,9 +275,8 @@ object ReplicatedAuctionExampleSpec { } case _ => // no trigger for this event } - } - private def shouldClose(state: AuctionState): Boolean = { + private def shouldClose(state: AuctionState): Boolean = responsibleForClosing && (state.phase match { case Closing(alreadyFinishedAtDc) => val allDone = allReplicas.diff(alreadyFinishedAtDc).isEmpty @@ -292,7 +290,6 @@ object ReplicatedAuctionExampleSpec { case _ => false }) - } // #event-triggers // #setup diff --git a/persistence-typed-tests/src/test/scala/docs/org/apache/pekko/persistence/typed/ReplicatedBlogExampleSpec.scala b/persistence-typed-tests/src/test/scala/docs/org/apache/pekko/persistence/typed/ReplicatedBlogExampleSpec.scala index 652343e98d1..a88b79f4544 100644 --- a/persistence-typed-tests/src/test/scala/docs/org/apache/pekko/persistence/typed/ReplicatedBlogExampleSpec.scala +++ b/persistence-typed-tests/src/test/scala/docs/org/apache/pekko/persistence/typed/ReplicatedBlogExampleSpec.scala @@ -60,7 +60,7 @@ object ReplicatedBlogExampleSpec { final case class PostAdded(postId: String, content: PostContent, timestamp: LwwTime) extends Event final case class BodyChanged(postId: String, newContent: PostContent, timestamp: LwwTime) extends Event - def apply(entityId: String, replicaId: ReplicaId, allReplicaIds: Set[ReplicaId]): Behavior[Command] = { + def apply(entityId: String, replicaId: ReplicaId, allReplicaIds: Set[ReplicaId]): Behavior[Command] = Behaviors.setup[Command] { ctx => ReplicatedEventSourcing.commonJournalConfig( ReplicationId("blog", entityId, replicaId), @@ -73,14 +73,13 @@ object ReplicatedBlogExampleSpec { (state, event) => eventHandler(ctx, replicationContext, state, event)) } } - } // #command-handler private def commandHandler( ctx: ActorContext[Command], replicationContext: ReplicationContext, state: BlogState, - cmd: Command): Effect[Event, BlogState] = { + cmd: Command): Effect[Event, BlogState] = cmd match { case AddPost(_, content, replyTo) => val evt = @@ -109,7 +108,6 @@ object ReplicatedBlogExampleSpec { state.content.foreach(content => gp.replyTo ! content) Effect.none } - } // #command-handler // #event-handler diff --git a/persistence-typed-tests/src/test/scala/docs/org/apache/pekko/persistence/typed/ReplicatedEventSourcingCompileOnlySpec.scala b/persistence-typed-tests/src/test/scala/docs/org/apache/pekko/persistence/typed/ReplicatedEventSourcingCompileOnlySpec.scala index 5e4215390bd..f4979aee2a2 100644 --- a/persistence-typed-tests/src/test/scala/docs/org/apache/pekko/persistence/typed/ReplicatedEventSourcingCompileOnlySpec.scala +++ b/persistence-typed-tests/src/test/scala/docs/org/apache/pekko/persistence/typed/ReplicatedEventSourcingCompileOnlySpec.scala @@ -42,14 +42,13 @@ object ReplicatedEventSourcingCompileOnlySpec { def apply( system: ActorSystem[_], entityId: String, - replicaId: ReplicaId): EventSourcedBehavior[Command, State, Event] = { + replicaId: ReplicaId): EventSourcedBehavior[Command, State, Event] = ReplicatedEventSourcing.commonJournalConfig( ReplicationId("MyReplicatedEntity", entityId, replicaId), AllReplicas, queryPluginId) { replicationContext => EventSourcedBehavior[Command, State, Event](???, ???, ???, ???) } - } // #factory-shared } @@ -58,13 +57,12 @@ object ReplicatedEventSourcingCompileOnlySpec { def apply( system: ActorSystem[_], entityId: String, - replicaId: ReplicaId): EventSourcedBehavior[Command, State, Event] = { + replicaId: ReplicaId): EventSourcedBehavior[Command, State, Event] = ReplicatedEventSourcing.perReplicaJournalConfig( ReplicationId("MyReplicatedEntity", entityId, replicaId), Map(DCA -> "journalForDCA", DCB -> "journalForDCB")) { replicationContext => EventSourcedBehavior[Command, State, Event](???, ???, ???, ???) } - } // #factory } diff --git a/persistence-typed-tests/src/test/scala/docs/org/apache/pekko/persistence/typed/ReplicatedMovieWatchListExampleSpec.scala b/persistence-typed-tests/src/test/scala/docs/org/apache/pekko/persistence/typed/ReplicatedMovieWatchListExampleSpec.scala index 3c1270e9fb8..a9d3988b85e 100644 --- a/persistence-typed-tests/src/test/scala/docs/org/apache/pekko/persistence/typed/ReplicatedMovieWatchListExampleSpec.scala +++ b/persistence-typed-tests/src/test/scala/docs/org/apache/pekko/persistence/typed/ReplicatedMovieWatchListExampleSpec.scala @@ -37,7 +37,7 @@ object ReplicatedMovieWatchListExampleSpec { final case class GetMovieList(replyTo: ActorRef[MovieList]) extends Command final case class MovieList(movieIds: Set[String]) - def apply(entityId: String, replicaId: ReplicaId, allReplicaIds: Set[ReplicaId]): Behavior[Command] = { + def apply(entityId: String, replicaId: ReplicaId, allReplicaIds: Set[ReplicaId]): Behavior[Command] = ReplicatedEventSourcing.commonJournalConfig( ReplicationId("movies", entityId, replicaId), allReplicaIds, @@ -48,9 +48,8 @@ object ReplicatedMovieWatchListExampleSpec { (state, cmd) => commandHandler(state, cmd), (state, event) => eventHandler(state, event)) } - } - private def commandHandler(state: ORSet[String], cmd: Command): Effect[ORSet.DeltaOp, ORSet[String]] = { + private def commandHandler(state: ORSet[String], cmd: Command): Effect[ORSet.DeltaOp, ORSet[String]] = cmd match { case AddMovie(movieId) => Effect.persist(state + movieId) @@ -60,11 +59,9 @@ object ReplicatedMovieWatchListExampleSpec { replyTo ! MovieList(state.elements) Effect.none } - } - private def eventHandler(state: ORSet[String], event: ORSet.DeltaOp): ORSet[String] = { + private def eventHandler(state: ORSet[String], event: ORSet.DeltaOp): ORSet[String] = state.applyOperation(event) - } } // #movie-entity diff --git a/persistence-typed-tests/src/test/scala/docs/org/apache/pekko/persistence/typed/ReplicatedShoppingCartExampleSpec.scala b/persistence-typed-tests/src/test/scala/docs/org/apache/pekko/persistence/typed/ReplicatedShoppingCartExampleSpec.scala index 259597b46c7..562a91c1769 100644 --- a/persistence-typed-tests/src/test/scala/docs/org/apache/pekko/persistence/typed/ReplicatedShoppingCartExampleSpec.scala +++ b/persistence-typed-tests/src/test/scala/docs/org/apache/pekko/persistence/typed/ReplicatedShoppingCartExampleSpec.scala @@ -50,7 +50,7 @@ object ReplicatedShoppingCartExampleSpec { final case class State(items: Map[ProductId, Counter]) - def apply(entityId: String, replicaId: ReplicaId, allReplicaIds: Set[ReplicaId]): Behavior[Command] = { + def apply(entityId: String, replicaId: ReplicaId, allReplicaIds: Set[ReplicaId]): Behavior[Command] = ReplicatedEventSourcing.commonJournalConfig( ReplicationId("blog", entityId, replicaId), allReplicaIds, @@ -61,9 +61,8 @@ object ReplicatedShoppingCartExampleSpec { (state, cmd) => commandHandler(state, cmd), (state, event) => eventHandler(state, event)) } - } - private def commandHandler(state: State, cmd: Command): Effect[Event, State] = { + private def commandHandler(state: State, cmd: Command): Effect[Event, State] = cmd match { case AddItem(productId, count) => Effect.persist(ItemUpdated(productId, Counter.Updated(count))) @@ -76,9 +75,8 @@ object ReplicatedShoppingCartExampleSpec { replyTo ! CartItems(items) Effect.none } - } - private def eventHandler(state: State, event: Event): State = { + private def eventHandler(state: State, event: Event): State = event match { case ItemUpdated(id, update) => val newItems = state.items.get(id) match { @@ -87,7 +85,6 @@ object ReplicatedShoppingCartExampleSpec { } State(newItems) } - } } // #shopping-cart } diff --git a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/EventSourcedBehaviorLoggingSpec.scala b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/EventSourcedBehaviorLoggingSpec.scala index 8e646e04ff3..600f2499128 100644 --- a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/EventSourcedBehaviorLoggingSpec.scala +++ b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/EventSourcedBehaviorLoggingSpec.scala @@ -41,7 +41,7 @@ object EventSourcedBehaviorLoggingSpec { final case class Event(msg: String) extends CborSerializable - def apply(id: PersistenceId): Behavior[Command] = { + def apply(id: PersistenceId): Behavior[Command] = Behaviors.setup { ctx => EventSourcedBehavior[Command, Event, Set[Event]]( id, @@ -57,7 +57,6 @@ object EventSourcedBehaviorLoggingSpec { }, (state, event) => state + event) } - } } } diff --git a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/MultiJournalReplicationSpec.scala b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/MultiJournalReplicationSpec.scala index e0150b6bfa0..dec2aa0642f 100644 --- a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/MultiJournalReplicationSpec.scala +++ b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/MultiJournalReplicationSpec.scala @@ -41,7 +41,7 @@ object MultiJournalReplicationSpec { case class StoreMe(text: String, ack: ActorRef[Done]) extends Command private val writeJournalPerReplica = Map("R1" -> "journal1.journal", "R2" -> "journal2.journal") - def apply(entityId: String, replicaId: String): Behavior[Command] = { + def apply(entityId: String, replicaId: String): Behavior[Command] = ReplicatedEventSourcing .perReplicaJournalConfig( ReplicationId("MultiJournalSpec", entityId, ReplicaId(replicaId)), @@ -59,7 +59,6 @@ object MultiJournalReplicationSpec { }, (state, event) => state + event)) .withJournalPluginId(writeJournalPerReplica(replicaId)) - } } def separateJournalsConfig: Config = ConfigFactory.parseString(s""" diff --git a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/ReplicatedEventSourcingSpec.scala b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/ReplicatedEventSourcingSpec.scala index 10c8a07ebc4..f54fe7f8c39 100644 --- a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/ReplicatedEventSourcingSpec.scala +++ b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/ReplicatedEventSourcingSpec.scala @@ -51,7 +51,7 @@ object ReplicatedEventSourcingSpec { def eventSourcedBehavior( replicationContext: ReplicationContext, - probe: Option[ActorRef[EventAndContext]]): EventSourcedBehavior[Command, String, State] = { + probe: Option[ActorRef[EventAndContext]]): EventSourcedBehavior[Command, String, State] = EventSourcedBehavior[Command, String, State]( replicationContext.persistenceId, State(Nil), @@ -83,7 +83,6 @@ object ReplicatedEventSourcingSpec { replicationContext.concurrent)) state.copy(all = event :: state.all) }) - } def testBehavior( entityId: String, diff --git a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/ReplicatedEventSourcingTaggingSpec.scala b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/ReplicatedEventSourcingTaggingSpec.scala index 928ed902d43..806deb9477c 100644 --- a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/ReplicatedEventSourcingTaggingSpec.scala +++ b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/ReplicatedEventSourcingTaggingSpec.scala @@ -50,7 +50,7 @@ object ReplicatedEventSourcingTaggingSpec { def apply( entityId: String, replica: ReplicaId, - allReplicas: Set[ReplicaId]): EventSourcedBehavior[Command, String, State] = { + allReplicas: Set[ReplicaId]): EventSourcedBehavior[Command, String, State] = // #tagging ReplicatedEventSourcing.commonJournalConfig( ReplicationId("TaggingSpec", entityId, replica), @@ -76,8 +76,7 @@ object ReplicatedEventSourcingTaggingSpec { if (replicationContext.origin != replicationContext.replicaId) Set.empty else if (event.length > 10) Set("long-strings", "strings") else Set("strings"))) - // #tagging - } + // #tagging } } @@ -103,13 +102,12 @@ class ReplicatedEventSourcingTaggingSpec probe.receiveMessages(1) val allEvents = Set("from r1", "from r2", "a very long string from r1") - for (replica <- r1 :: r2 :: Nil) { + for (replica <- r1 :: r2 :: Nil) eventually { val probe = testKit.createTestProbe[Set[String]]() replica ! ReplicatedStringSet.GetStrings(probe.ref) probe.receiveMessage() should ===(allEvents) } - } val query = PersistenceQuery(system).readJournalFor[CurrentEventsByTagQuery](PersistenceTestKitReadJournal.Identifier) diff --git a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/ReplicationIllegalAccessSpec.scala b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/ReplicationIllegalAccessSpec.scala index c918b016eed..ed9b19e8475 100644 --- a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/ReplicationIllegalAccessSpec.scala +++ b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/ReplicationIllegalAccessSpec.scala @@ -37,7 +37,7 @@ object ReplicationIllegalAccessSpec { case class State(all: List[String]) extends CborSerializable - def apply(entityId: String, replica: ReplicaId): Behavior[Command] = { + def apply(entityId: String, replica: ReplicaId): Behavior[Command] = ReplicatedEventSourcing.commonJournalConfig( ReplicationId("IllegalAccessSpec", entityId, replica), AllReplicas, @@ -72,7 +72,6 @@ object ReplicationIllegalAccessSpec { } }, (state, event) => state.copy(all = event :: state.all))) - } } diff --git a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/ReplicationSnapshotSpec.scala b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/ReplicationSnapshotSpec.scala index b2e646a4613..f482e28d93b 100644 --- a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/ReplicationSnapshotSpec.scala +++ b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/ReplicationSnapshotSpec.scala @@ -44,14 +44,13 @@ object ReplicationSnapshotSpec { def behaviorWithSnapshotting( entityId: String, replicaId: ReplicaId, - probe: Option[ActorRef[EventAndContext]]): Behavior[Command] = { + probe: Option[ActorRef[EventAndContext]]): Behavior[Command] = ReplicatedEventSourcing.commonJournalConfig( ReplicationId(EntityType, entityId, replicaId), AllReplicas, PersistenceTestKitReadJournal.Identifier)(replicationContext => eventSourcedBehavior(replicationContext, probe).snapshotWhen((_, _, sequenceNr) => sequenceNr % 2 == 0)) - } } class ReplicationSnapshotSpec diff --git a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/crdt/CounterSpec.scala b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/crdt/CounterSpec.scala index 9b029f404e5..fb6114aa033 100644 --- a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/crdt/CounterSpec.scala +++ b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/crdt/CounterSpec.scala @@ -91,13 +91,11 @@ class CounterSpec extends ReplicationBaseSpec { r2Probe.expectMessage(2L) } - for (n <- 1 to 10) { + for (n <- 1 to 10) if (n % 2 == 0) r1 ! Increment else r1 ! Decrement - } - for (_ <- 1 to 10) { + for (_ <- 1 to 10) r2 ! Increment - } eventually { r1 ! Get(r1Probe.ref) diff --git a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/crdt/LwwSpec.scala b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/crdt/LwwSpec.scala index 688aa171a96..e930413148e 100644 --- a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/crdt/LwwSpec.scala +++ b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/crdt/LwwSpec.scala @@ -44,7 +44,7 @@ object LwwSpec { object LwwRegistry { - def apply(entityId: String, replica: ReplicaId): Behavior[Command] = { + def apply(entityId: String, replica: ReplicaId): Behavior[Command] = ReplicatedEventSourcing.commonJournalConfig( ReplicationId("LwwRegistrySpec", entityId, replica), AllReplicas, @@ -76,7 +76,6 @@ object LwwSpec { else state }) } - } } } diff --git a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/crdt/ORSetSpec.scala b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/crdt/ORSetSpec.scala index 3adb76484cc..6bebfeb6fc4 100644 --- a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/crdt/ORSetSpec.scala +++ b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/crdt/ORSetSpec.scala @@ -36,8 +36,7 @@ object ORSetSpec { final case class AddAll(elems: Set[String]) extends Command final case class Remove(elem: String) extends Command - def apply(entityId: String, replica: ReplicaId): Behavior[ORSetEntity.Command] = { - + def apply(entityId: String, replica: ReplicaId): Behavior[ORSetEntity.Command] = ReplicatedEventSourcing.commonJournalConfig( ReplicationId("ORSetSpec", entityId, replica), AllReplicas, @@ -59,7 +58,6 @@ object ORSetSpec { }, (state, operation) => state.applyOperation(operation)) } - } } } @@ -73,20 +71,18 @@ class ORSetSpec extends ReplicationBaseSpec { val r1GetProbe = createTestProbe[Set[String]]() val r2GetProbe = createTestProbe[Set[String]]() - def assertForAllReplicas(state: Set[String]): Unit = { + def assertForAllReplicas(state: Set[String]): Unit = eventually { r1 ! Get(r1GetProbe.ref) r1GetProbe.expectMessage(state) r2 ! Get(r2GetProbe.ref) r2GetProbe.expectMessage(state) } - } } - def randomDelay(): Unit = { + def randomDelay(): Unit = // exercise different timing scenarios Thread.sleep(Random.nextInt(200).toLong) - } "ORSet Replicated Entity" should { diff --git a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedBehaviorFailureSpec.scala b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedBehaviorFailureSpec.scala index bba7de2f3ec..db0ba08b947 100644 --- a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedBehaviorFailureSpec.scala +++ b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedBehaviorFailureSpec.scala @@ -65,7 +65,7 @@ class ChaosJournal extends InmemJournal { } } - override def asyncReadHighestSequenceNr(persistenceId: String, fromSequenceNr: Long): Future[Long] = { + override def asyncReadHighestSequenceNr(persistenceId: String, fromSequenceNr: Long): Future[Long] = if (persistenceId == "fail-recovery-once" && failRecovery) { failRecovery = false Future.failed(TestException("Nah")) @@ -74,7 +74,6 @@ class ChaosJournal extends InmemJournal { } else { super.asyncReadHighestSequenceNr(persistenceId, fromSequenceNr) } - } } object EventSourcedBehaviorFailureSpec { diff --git a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedBehaviorInterceptorSpec.scala b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedBehaviorInterceptorSpec.scala index b97314721b1..44c356ffdce 100644 --- a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedBehaviorInterceptorSpec.scala +++ b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedBehaviorInterceptorSpec.scala @@ -73,9 +73,8 @@ class EventSourcedBehaviorInterceptorSpec override def aroundReceive( ctx: TypedActorContext[String], msg: String, - target: BehaviorInterceptor.ReceiveTarget[String]): Behavior[String] = { + target: BehaviorInterceptor.ReceiveTarget[String]): Behavior[String] = target(ctx, msg.toUpperCase()) - } } diff --git a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedBehaviorReplySpec.scala b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedBehaviorReplySpec.scala index fe5e92221a6..e074313313f 100644 --- a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedBehaviorReplySpec.scala +++ b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedBehaviorReplySpec.scala @@ -45,7 +45,7 @@ object EventSourcedBehaviorReplySpec { def counter( ctx: ActorContext[Command[_]], - persistenceId: PersistenceId): EventSourcedBehavior[Command[_], Event, State] = { + persistenceId: PersistenceId): EventSourcedBehavior[Command[_], Event, State] = EventSourcedBehavior.withEnforcedReplies[Command[_], Event, State]( persistenceId, emptyState = State(0, Vector.empty), @@ -70,7 +70,6 @@ object EventSourcedBehaviorReplySpec { case Incremented(delta) => State(state.value + delta, state.history :+ state.value) }) - } } class EventSourcedBehaviorReplySpec diff --git a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedBehaviorRetentionSpec.scala b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedBehaviorRetentionSpec.scala index b094c716a5b..0b2660c0282 100644 --- a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedBehaviorRetentionSpec.scala +++ b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedBehaviorRetentionSpec.scala @@ -61,8 +61,7 @@ object EventSourcedBehaviorRetentionSpec extends Matchers { persistenceId: PersistenceId, probe: Option[ActorRef[(State, Event)]] = None, snapshotSignalProbe: Option[ActorRef[WrappedSignal]] = None, - eventSignalProbe: Option[ActorRef[Try[EventSourcedSignal]]] = None) - : EventSourcedBehavior[Command, Event, State] = { + eventSignalProbe: Option[ActorRef[Try[EventSourcedSignal]]] = None): EventSourcedBehavior[Command, Event, State] = EventSourcedBehavior[Command, Event, State]( persistenceId, emptyState = State(0, Vector.empty), @@ -100,7 +99,6 @@ object EventSourcedBehaviorRetentionSpec extends Matchers { case (_, e: EventSourcedSignal) => eventSignalProbe.foreach(_ ! Success(e)) } - } implicit class WrappedSignalProbeAssert(probe: TestProbe[WrappedSignal]) { def expectSnapshotCompleted(sequenceNumber: Int): SnapshotCompleted = { diff --git a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedBehaviorSpec.scala b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedBehaviorSpec.scala index 24ede2b59da..b10b4dc1868 100644 --- a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedBehaviorSpec.scala +++ b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedBehaviorSpec.scala @@ -65,9 +65,8 @@ object EventSourcedBehaviorSpec { override def loadAsync( persistenceId: String, - criteria: ClassicSnapshotSelectionCriteria): Future[Option[SelectedSnapshot]] = { + criteria: ClassicSnapshotSelectionCriteria): Future[Option[SelectedSnapshot]] = Promise().future // never completed - } override def saveAsync(metadata: ClassicSnapshotMetadata, snapshot: Any): Future[Unit] = { state = state.updated(metadata.persistenceId, (snapshot, metadata)) @@ -643,7 +642,7 @@ class EventSourcedBehaviorSpec "fail fast if default journal plugin is not defined" in { // new ActorSystem without persistence config val testkit2 = ActorTestKit(ActorTestKitBase.testNameFromCallStack(), ConfigFactory.parseString("")) - try { + try LoggingTestKit .error[ActorInitializationException] .withMessageContains("Default journal plugin is not configured") @@ -652,15 +651,14 @@ class EventSourcedBehaviorSpec val probe = testkit2.createTestProbe() probe.expectTerminated(ref) }(testkit2.system) - } finally { + finally testkit2.shutdownTestKit() - } } "fail fast if given journal plugin is not defined" in { // new ActorSystem without persistence config val testkit2 = ActorTestKit(ActorTestKitBase.testNameFromCallStack(), ConfigFactory.parseString("")) - try { + try LoggingTestKit .error[ActorInitializationException] .withMessageContains("Journal plugin [missing] configuration doesn't exist") @@ -669,9 +667,8 @@ class EventSourcedBehaviorSpec val probe = testkit2.createTestProbe() probe.expectTerminated(ref) }(testkit2.system) - } finally { + finally testkit2.shutdownTestKit() - } } "warn if default snapshot plugin is not defined" in { @@ -681,7 +678,7 @@ class EventSourcedBehaviorSpec ConfigFactory.parseString(s""" pekko.persistence.journal.plugin = "pekko.persistence.journal.inmem" """)) - try { + try LoggingTestKit .warn("No default snapshot store configured") .expect { @@ -691,9 +688,8 @@ class EventSourcedBehaviorSpec ref ! GetValue(probe.ref) probe.expectMessage(State(0, Vector.empty)) }(testkit2.system) - } finally { + finally testkit2.shutdownTestKit() - } } "fail fast if given snapshot plugin is not defined" in { @@ -703,7 +699,7 @@ class EventSourcedBehaviorSpec ConfigFactory.parseString(s""" pekko.persistence.journal.plugin = "pekko.persistence.journal.inmem" """)) - try { + try LoggingTestKit .error[ActorInitializationException] .withMessageContains("Snapshot store plugin [missing] configuration doesn't exist") @@ -712,9 +708,8 @@ class EventSourcedBehaviorSpec val probe = testkit2.createTestProbe() probe.expectTerminated(ref) }(testkit2.system) - } finally { + finally testkit2.shutdownTestKit() - } } "allow enumerating all ids" in { diff --git a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedBehaviorStashSpec.scala b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedBehaviorStashSpec.scala index 16883b014d5..063e846b69e 100644 --- a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedBehaviorStashSpec.scala +++ b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedBehaviorStashSpec.scala @@ -88,15 +88,14 @@ object EventSourcedBehaviorStashSpec { def eventSourcedCounter( persistenceId: PersistenceId, - signalProbe: Option[ActorRef[String]]): EventSourcedBehavior[Command[_], Event, State] = { + signalProbe: Option[ActorRef[String]]): EventSourcedBehavior[Command[_], Event, State] = EventSourcedBehavior .withEnforcedReplies[Command[_], Event, State]( persistenceId, emptyState = State(0, active = true), - commandHandler = (state, command) => { + commandHandler = (state, command) => if (state.active) active(state, command) - else inactive(state, command) - }, + else inactive(state, command), eventHandler = (state, evt) => evt match { case Incremented(delta) => @@ -118,9 +117,8 @@ object EventSourcedBehaviorStashSpec { case (state, RecoveryCompleted) => signalProbe.foreach(_ ! s"RecoveryCompleted-${state.value}") case (_, PostStop) => signalProbe.foreach(_ ! "PostStop") } - } - private def active(state: State, command: Command[_]): ReplyEffect[Event, State] = { + private def active(state: State, command: Command[_]): ReplyEffect[Event, State] = command match { case Increment(id, replyTo) => Effect.persist(Incremented(1)).thenReply(replyTo)(_ => Ack(id)) @@ -144,9 +142,8 @@ object EventSourcedBehaviorStashSpec { latch.await(30, TimeUnit.SECONDS) Effect.reply(replyTo)(Ack(id)) } - } - private def inactive(state: State, command: Command[_]): ReplyEffect[Event, State] = { + private def inactive(state: State, command: Command[_]): ReplyEffect[Event, State] = command match { case _: Increment => Effect.stash() @@ -169,7 +166,6 @@ object EventSourcedBehaviorStashSpec { case _: Slow => Effect.stash() } - } } class EventSourcedBehaviorStashSpec @@ -638,9 +634,8 @@ class EventSourcedBehaviorStashSpec } probe.expectTerminated(c, 10.seconds) }(failStashTestKit.system) - } finally { + } finally failStashTestKit.shutdownTestKit() - } } "stop from PoisonPill even though user stash is not empty" in { diff --git a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedEventAdapterSpec.scala b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedEventAdapterSpec.scala index 0c8ec10a50c..bd6723169db 100644 --- a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedEventAdapterSpec.scala +++ b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedEventAdapterSpec.scala @@ -47,10 +47,9 @@ object EventSourcedEventAdapterSpec { class FilterEventAdapter extends EventAdapter[String, String] { override def toJournal(e: String): String = e.toUpperCase() - override def fromJournal(p: String, manifest: String): EventSeq[String] = { + override def fromJournal(p: String, manifest: String): EventSeq[String] = if (p == "B") EventSeq.empty else EventSeq.single(p) - } override def manifest(event: String): String = "" } @@ -58,9 +57,8 @@ object EventSourcedEventAdapterSpec { class SplitEventAdapter extends EventAdapter[String, String] { override def toJournal(e: String): String = e.toUpperCase() - override def fromJournal(p: String, manifest: String): EventSeq[String] = { + override def fromJournal(p: String, manifest: String): EventSeq[String] = EventSeq(p.map("<" + _.toString + ">")) - } override def manifest(event: String): String = "" } @@ -68,9 +66,8 @@ object EventSourcedEventAdapterSpec { class EventAdapterWithManifest extends EventAdapter[String, String] { override def toJournal(e: String): String = e.toUpperCase() - override def fromJournal(p: String, manifest: String): EventSeq[String] = { + override def fromJournal(p: String, manifest: String): EventSeq[String] = EventSeq.single(p + manifest) - } override def manifest(event: String): String = event.length.toString } diff --git a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedSequenceNumberSpec.scala b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedSequenceNumberSpec.scala index 47262847532..18084a3da02 100644 --- a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedSequenceNumberSpec.scala +++ b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedSequenceNumberSpec.scala @@ -44,37 +44,35 @@ class EventSourcedSequenceNumberSpec private def behavior(pid: PersistenceId, probe: ActorRef[String]): Behavior[String] = Behaviors.setup(ctx => EventSourcedBehavior[String, String, String](pid, "", - { - (state, command) => - state match { - case "stashing" => - command match { - case "unstash" => - probe ! s"${EventSourcedBehavior.lastSequenceNumber(ctx)} unstash" - Effect.persist("normal").thenUnstashAll() - case _ => - Effect.stash() - } - case _ => - command match { - case "cmd" => - probe ! s"${EventSourcedBehavior.lastSequenceNumber(ctx)} onCommand" - Effect - .persist("evt") - .thenRun(_ => probe ! s"${EventSourcedBehavior.lastSequenceNumber(ctx)} thenRun") - case "cmd3" => - probe ! s"${EventSourcedBehavior.lastSequenceNumber(ctx)} onCommand" - Effect - .persist("evt1", "evt2", "evt3") - .thenRun(_ => probe ! s"${EventSourcedBehavior.lastSequenceNumber(ctx)} thenRun") - case "stash" => - probe ! s"${EventSourcedBehavior.lastSequenceNumber(ctx)} stash" - Effect.persist("stashing") - case "snapshot" => - Effect.persist("snapshot") - } - } - }, + (state, command) => + state match { + case "stashing" => + command match { + case "unstash" => + probe ! s"${EventSourcedBehavior.lastSequenceNumber(ctx)} unstash" + Effect.persist("normal").thenUnstashAll() + case _ => + Effect.stash() + } + case _ => + command match { + case "cmd" => + probe ! s"${EventSourcedBehavior.lastSequenceNumber(ctx)} onCommand" + Effect + .persist("evt") + .thenRun(_ => probe ! s"${EventSourcedBehavior.lastSequenceNumber(ctx)} thenRun") + case "cmd3" => + probe ! s"${EventSourcedBehavior.lastSequenceNumber(ctx)} onCommand" + Effect + .persist("evt1", "evt2", "evt3") + .thenRun(_ => probe ! s"${EventSourcedBehavior.lastSequenceNumber(ctx)} thenRun") + case "stash" => + probe ! s"${EventSourcedBehavior.lastSequenceNumber(ctx)} stash" + Effect.persist("stashing") + case "snapshot" => + Effect.persist("snapshot") + } + }, { (_, evt) => probe ! s"${EventSourcedBehavior.lastSequenceNumber(ctx)} eventHandler $evt" evt diff --git a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedStashOverflowSpec.scala b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedStashOverflowSpec.scala index 316015ca75f..9308793377a 100644 --- a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedStashOverflowSpec.scala +++ b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/EventSourcedStashOverflowSpec.scala @@ -38,17 +38,16 @@ object EventSourcedStashOverflowSpec { EventSourcedBehavior[Command, String, List[String]]( persistenceId, Nil, - { (_, command) => + (_, command) => command match { case DoNothing(replyTo) => Effect.persist(List.empty[String]).thenRun(_ => replyTo ! Done) - } - }, - { (state, event) => + }, + (state, event) => // original reproducer slept 2 seconds here but a pure application of an event seems unlikely to take that long // so instead we delay recovery using a special journal event :: state - }) + ) } def conf = @@ -82,9 +81,8 @@ class EventSourcedStashOverflowSpec val droppedMessageProbe = testKit.createDroppedMessageProbe() val stashCapacity = testKit.config.getInt("pekko.persistence.typed.stash-capacity") - for (_ <- 0 to (stashCapacity * 2)) { + for (_ <- 0 to (stashCapacity * 2)) es.tell(EventSourcedStringList.DoNothing(probe.ref)) - } // capacity + 1 should mean that we get a dropped last message when all stash is filled // while the actor is stuck in replay because journal isn't responding droppedMessageProbe.receiveMessage() diff --git a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/NullEmptyStateSpec.scala b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/NullEmptyStateSpec.scala index 4696f272a5e..b8d82c35b1e 100644 --- a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/NullEmptyStateSpec.scala +++ b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/NullEmptyStateSpec.scala @@ -42,12 +42,11 @@ class NullEmptyStateSpec EventSourcedBehavior[String, String, String]( persistenceId, emptyState = null, - commandHandler = (_, command) => { + commandHandler = (_, command) => if (command == "stop") Effect.stop() else - Effect.persist(command) - }, + Effect.persist(command), eventHandler = (state, event) => { probe.tell("eventHandler:" + state + ":" + event) if (state == null) event else state + event diff --git a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/PerformanceSpec.scala b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/PerformanceSpec.scala index a8b181576fb..61781c79cf9 100644 --- a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/PerformanceSpec.scala +++ b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/PerformanceSpec.scala @@ -61,9 +61,8 @@ object PerformanceSpec { private var startTime: Long = 0L private var stopTime: Long = 0L - def startMeasure(): Unit = { + def startMeasure(): Unit = startTime = System.nanoTime - } def stopMeasure(): Double = { stopTime = System.nanoTime @@ -80,7 +79,7 @@ object PerformanceSpec { def failureWasDefined: Boolean = failAt != -1L } - def behavior(name: String, probe: TestProbe[Reply])(other: (Command, Parameters) => Effect[String, String]) = { + def behavior(name: String, probe: TestProbe[Reply])(other: (Command, Parameters) => Effect[String, String]) = Behaviors .supervise { val parameters = Parameters() @@ -102,21 +101,20 @@ object PerformanceSpec { } } .onFailure(SupervisorStrategy.restart.withLoggingEnabled(false)) - } def eventSourcedTestPersistenceBehavior(name: String, probe: TestProbe[Reply]) = behavior(name, probe) { case (CommandWithEvent(evt), parameters) => Effect .persist(evt) - .thenRun(_ => { + .thenRun { _ => parameters.persistCalls += 1 if (parameters.every(1000)) print(".") if (parameters.shouldFail) { probe.ref ! ExpectedFail throw TestException("boom") } - }) + } case _ => Effect.none } } @@ -142,7 +140,7 @@ class PerformanceSpec probe: TestProbe[Reply], failAt: Option[Long], description: String): Unit = { - failAt.foreach { persistentActor ! FailAt(_) } + failAt.foreach(persistentActor ! FailAt(_)) val m = new Measure(loadCycles) m.startMeasure() val parameters = Parameters(0, failAt = failAt.getOrElse(-1)) diff --git a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/PrimitiveStateSpec.scala b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/PrimitiveStateSpec.scala index 7f76ce277f5..7e9c58c25af 100644 --- a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/PrimitiveStateSpec.scala +++ b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/PrimitiveStateSpec.scala @@ -39,12 +39,11 @@ class PrimitiveStateSpec EventSourcedBehavior[Int, Int, Int]( persistenceId, emptyState = 0, - commandHandler = (_, command) => { + commandHandler = (_, command) => if (command < 0) Effect.stop() else - Effect.persist(command) - }, + Effect.persist(command), eventHandler = (state, event) => { probe.tell("eventHandler:" + state + ":" + event) state + event diff --git a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/SlowInMemorySnapshotStore.scala b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/SlowInMemorySnapshotStore.scala index 958128cb111..48c109ff715 100644 --- a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/SlowInMemorySnapshotStore.scala +++ b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/SlowInMemorySnapshotStore.scala @@ -26,11 +26,10 @@ class SlowInMemorySnapshotStore extends SnapshotStore { private var state = Map.empty[String, (Any, ClassicSnapshotMetadata)] - def loadAsync(persistenceId: String, criteria: ClassicSnapshotSelectionCriteria): Future[Option[SelectedSnapshot]] = { + def loadAsync(persistenceId: String, criteria: ClassicSnapshotSelectionCriteria): Future[Option[SelectedSnapshot]] = Future.successful(state.get(persistenceId).map { case (snap, meta) => SelectedSnapshot(meta, snap) }) - } def saveAsync(metadata: ClassicSnapshotMetadata, snapshot: Any): Future[Unit] = { val snapshotState = snapshot.asInstanceOf[MutableState] diff --git a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/SnapshotMutableStateSpec.scala b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/SnapshotMutableStateSpec.scala index e152a2721d9..75a0c363e86 100644 --- a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/SnapshotMutableStateSpec.scala +++ b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/SnapshotMutableStateSpec.scala @@ -48,7 +48,7 @@ object SnapshotMutableStateSpec { def counter( persistenceId: PersistenceId, - probe: ActorRef[String]): EventSourcedBehavior[Command, Event, MutableState] = { + probe: ActorRef[String]): EventSourcedBehavior[Command, Event, MutableState] = EventSourcedBehavior[Command, Event, MutableState]( persistenceId, emptyState = new MutableState(0), @@ -73,7 +73,6 @@ object SnapshotMutableStateSpec { case (_, SnapshotFailed(meta, _)) => probe ! s"snapshot-failure-${meta.sequenceNr}" } - } } diff --git a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/SnapshotRecoveryWithEmptyJournalSpec.scala b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/SnapshotRecoveryWithEmptyJournalSpec.scala index 6773be9edc4..42aa2912572 100644 --- a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/SnapshotRecoveryWithEmptyJournalSpec.scala +++ b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/SnapshotRecoveryWithEmptyJournalSpec.scala @@ -44,7 +44,7 @@ object SnapshotRecoveryWithEmptyJournalSpec { """)) object TestActor { - def apply(name: String, probe: ActorRef[Any]): Behavior[String] = { + def apply(name: String, probe: ActorRef[Any]): Behavior[String] = Behaviors.setup { context => EventSourcedBehavior[String, String, List[String]]( PersistenceId.ofUniqueId(name), @@ -59,7 +59,6 @@ object SnapshotRecoveryWithEmptyJournalSpec { }, (state, event) => event :: state) } - } } } diff --git a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/state/scaladsl/DurableStateBehaviorInterceptorSpec.scala b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/state/scaladsl/DurableStateBehaviorInterceptorSpec.scala index 603f84bc785..26936e48830 100644 --- a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/state/scaladsl/DurableStateBehaviorInterceptorSpec.scala +++ b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/state/scaladsl/DurableStateBehaviorInterceptorSpec.scala @@ -68,9 +68,8 @@ class DurableStateBehaviorInterceptorSpec override def aroundReceive( ctx: TypedActorContext[String], msg: String, - target: BehaviorInterceptor.ReceiveTarget[String]): Behavior[String] = { + target: BehaviorInterceptor.ReceiveTarget[String]): Behavior[String] = target(ctx, msg.toUpperCase()) - } } val ref = spawn(Behaviors.intercept(() => toUpper)(testBehavior(pid, probe.ref))) diff --git a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/state/scaladsl/DurableStateBehaviorReplySpec.scala b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/state/scaladsl/DurableStateBehaviorReplySpec.scala index b8c9b0cfad7..977e3222cf6 100644 --- a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/state/scaladsl/DurableStateBehaviorReplySpec.scala +++ b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/state/scaladsl/DurableStateBehaviorReplySpec.scala @@ -50,7 +50,7 @@ object DurableStateBehaviorReplySpec { def counter(persistenceId: PersistenceId): Behavior[Command[_]] = Behaviors.setup(ctx => counter(ctx, persistenceId)) - def counter(ctx: ActorContext[Command[_]], persistenceId: PersistenceId): DurableStateBehavior[Command[_], State] = { + def counter(ctx: ActorContext[Command[_]], persistenceId: PersistenceId): DurableStateBehavior[Command[_], State] = DurableStateBehavior.withEnforcedReplies[Command[_], State]( persistenceId, emptyState = State(0), @@ -78,7 +78,6 @@ object DurableStateBehaviorReplySpec { case _ => ??? }) - } } diff --git a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/state/scaladsl/NullEmptyStateSpec.scala b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/state/scaladsl/NullEmptyStateSpec.scala index 1a61bc71ef3..efa4848fbea 100644 --- a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/state/scaladsl/NullEmptyStateSpec.scala +++ b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/state/scaladsl/NullEmptyStateSpec.scala @@ -43,14 +43,14 @@ class NullEmptyStateSpec DurableStateBehavior[String, String]( persistenceId, emptyState = null, - commandHandler = (state, command) => { + commandHandler = (state, command) => if (command == "stop") Effect.stop() else if (state == null) Effect.persist(command).thenReply(probe)(newState => newState) else Effect.persist(s"$state:$command").thenReply(probe)(newState => newState) - }) + ) "A typed persistent actor with null empty state" must { "persist and update state" in { diff --git a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/state/scaladsl/PrimitiveStateSpec.scala b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/state/scaladsl/PrimitiveStateSpec.scala index d8024102245..4b1914c46d0 100644 --- a/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/state/scaladsl/PrimitiveStateSpec.scala +++ b/persistence-typed-tests/src/test/scala/org/apache/pekko/persistence/typed/state/scaladsl/PrimitiveStateSpec.scala @@ -40,12 +40,12 @@ class PrimitiveStateSpec DurableStateBehavior[Int, Int]( persistenceId, emptyState = 0, - commandHandler = (state, command) => { + commandHandler = (state, command) => if (command < 0) Effect.stop() else Effect.persist(state + command).thenReply(probe)(newState => newState.toString) - }) + ) "A typed persistent actor with primitive state" must { "persist primitive state and update" in { diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/PersistenceId.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/PersistenceId.scala index 8eb0a95d25c..1fd882b4675 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/PersistenceId.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/PersistenceId.scala @@ -120,7 +120,7 @@ object PersistenceId { * Extract the `entityTypeHint` from a persistence id String with the default separator `|`. * If the separator `|` is not found it return the empty String (`""`). */ - def extractEntityType(id: String): String = { + def extractEntityType(id: String): String = if (ReplicationId.isReplicationId(id)) ReplicationId.fromString(id).typeName else { @@ -128,13 +128,12 @@ object PersistenceId { if (i == -1) "" else id.substring(0, i) } - } /** * Extract the `entityId` from a persistence id String with the default separator `|`. * If the separator `|` is not found it return the `id`. */ - def extractEntityId(id: String): String = { + def extractEntityId(id: String): String = if (ReplicationId.isReplicationId(id)) ReplicationId.fromString(id).entityId else { @@ -142,7 +141,6 @@ object PersistenceId { if (i == -1) id else id.substring(i + 1) } - } def unapply(persistenceId: PersistenceId): Option[(String, String)] = Some((persistenceId.entityTypeHint, persistenceId.entityId)) diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/ReplicationId.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/ReplicationId.scala index 516a97a1150..450ef3196ac 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/ReplicationId.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/ReplicationId.scala @@ -21,9 +21,8 @@ object ReplicationId { ReplicationId(split(0), split(1), ReplicaId(split(2))) } - def isReplicationId(id: String): Boolean = { + def isReplicationId(id: String): Boolean = id.count(_ == Separator) == 2 - } /** * @param typeName The name of the entity type e.g. account, user. Made part of the persistence id so that entity ids don't need to be unique across different replicated entities @@ -58,7 +57,6 @@ final class ReplicationId(val typeName: String, val entityId: String, val replic override def toString: String = s"ReplicationId($typeName, $entityId, $replicaId)" - def withReplica(newReplica: ReplicaId): ReplicationId = { + def withReplica(newReplica: ReplicaId): ReplicationId = new ReplicationId(typeName, entityId, newReplica) - } } diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/crdt/LwwTime.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/crdt/LwwTime.scala index 2cd7dcf5bef..60640c588ed 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/crdt/LwwTime.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/crdt/LwwTime.scala @@ -34,10 +34,9 @@ final case class LwwTime(timestamp: Long, originReplica: ReplicaId) { * equal the `dc` identifiers are compared and the * one sorted first in alphanumeric order wins. */ - def isAfter(other: LwwTime): Boolean = { + def isAfter(other: LwwTime): Boolean = if (timestamp > other.timestamp) true else if (timestamp < other.timestamp) false else if (other.originReplica.id.compareTo(originReplica.id) > 0) true else false - } } diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/crdt/ORSet.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/crdt/ORSet.scala index 9fbf0941619..517e71598db 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/crdt/ORSet.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/crdt/ORSet.scala @@ -67,13 +67,12 @@ object ORSet { case DeltaGroup(ops) => DeltaGroup(this +: ops) } - private def concatElementsMap(thatMap: Map[A, Dot]): Map[A, Dot] = { + private def concatElementsMap(thatMap: Map[A, Dot]): Map[A, Dot] = if (thatMap.size == 1) { val head = thatMap.head underlying.elementsMap.updated(head._1, head._2) } else underlying.elementsMap ++ thatMap - } } /** INTERNAL API */ @@ -162,7 +161,7 @@ object ORSet { rhs: ORSet[A]): Map[A, ORSet.Dot] = mergeCommonKeys(commonKeys.iterator, lhs, rhs) - private def mergeCommonKeys[A](commonKeys: Iterator[A], lhs: ORSet[A], rhs: ORSet[A]): Map[A, ORSet.Dot] = { + private def mergeCommonKeys[A](commonKeys: Iterator[A], lhs: ORSet[A], rhs: ORSet[A]): Map[A, ORSet.Dot] = commonKeys.foldLeft(Map.empty[A, ORSet.Dot]) { case (acc, k) => val lhsDots = lhs.elementsMap(k) @@ -222,7 +221,6 @@ object ORSet { else acc.updated(k, merged) } } - } /** * INTERNAL API @@ -239,7 +237,7 @@ object ORSet { keys: Iterator[A], elementsMap: Map[A, ORSet.Dot], vvector: VersionVector, - accumulator: Map[A, ORSet.Dot]): Map[A, ORSet.Dot] = { + accumulator: Map[A, ORSet.Dot]): Map[A, ORSet.Dot] = keys.foldLeft(accumulator) { case (acc, k) => val dots = elementsMap(k) @@ -251,7 +249,6 @@ object ORSet { acc.updated(k, newDots) } } - } } /** @@ -338,7 +335,7 @@ final class ORSet[A] private[pekko] ( * Scala API: Add several elements to the set. * `elems` must not be empty. */ - def addAll(elems: Set[A]): ORSet.DeltaOp = { + def addAll(elems: Set[A]): ORSet.DeltaOp = if (elems.size == 0) throw new IllegalArgumentException("addAll elems must not be empty") else if (elems.size == 1) add(elems.head) else { @@ -352,7 +349,6 @@ final class ORSet[A] private[pekko] ( } mergedOps } - } /** * Removes an element from the set. @@ -380,7 +376,7 @@ final class ORSet[A] private[pekko] ( * Scala API: Remove several elements from the set. * `elems` must not be empty. */ - def removeAll(elems: Set[A]): ORSet.DeltaOp = { + def removeAll(elems: Set[A]): ORSet.DeltaOp = if (elems.size == 0) throw new IllegalArgumentException("removeAll elems must not be empty") else if (elems.size == 1) remove(elems.head) else { @@ -394,7 +390,6 @@ final class ORSet[A] private[pekko] ( } mergedOps } - } /** * Removes all elements from the set, but keeps the history. @@ -419,7 +414,7 @@ final class ORSet[A] private[pekko] ( * and the other Set version vector dominates those dots, then we need to drop those dots. * Keep only common dots, and dots that are not dominated by the other sides version vector */ - private def merge(that: ORSet[A], addDeltaOp: Boolean): ORSet[A] = { + private def merge(that: ORSet[A], addDeltaOp: Boolean): ORSet[A] = if (this eq that) this else { val commonKeys = @@ -441,9 +436,8 @@ final class ORSet[A] private[pekko] ( new ORSet(originReplica, entries, mergedVvector) } - } - override def applyOperation(thatDelta: ORSet.DeltaOp): ORSet[A] = { + override def applyOperation(thatDelta: ORSet.DeltaOp): ORSet[A] = thatDelta match { case d: ORSet.AddDeltaOp[A @unchecked] => merge(d.underlying, addDeltaOp = true) case d: ORSet.RemoveDeltaOp[A @unchecked] => mergeRemoveDelta(d) @@ -457,7 +451,6 @@ final class ORSet[A] private[pekko] ( throw new IllegalArgumentException("ORSet.DeltaGroup should not be nested") } } - } private def mergeRemoveDelta(thatDelta: ORSet.RemoveDeltaOp[A]): ORSet[A] = { val that = thatDelta.underlying diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/delivery/EventSourcedProducerQueue.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/delivery/EventSourcedProducerQueue.scala index 8af725db33c..e3b85705db9 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/delivery/EventSourcedProducerQueue.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/delivery/EventSourcedProducerQueue.scala @@ -59,7 +59,7 @@ object EventSourcedProducerQueue { * Scala API: Factory method from Config corresponding to * `pekko.reliable-delivery.producer-controller.event-sourced-durable-queue`. */ - def apply(config: Config): Settings = { + def apply(config: Config): Settings = new Settings( restartMaxBackoff = config.getDuration("restart-max-backoff").asScala, snapshotEvery = config.getInt("snapshot-every"), @@ -68,7 +68,6 @@ object EventSourcedProducerQueue { cleanupUnusedAfter = config.getDuration("cleanup-unused-after").asScala, journalPluginId = config.getString("journal-plugin-id"), snapshotPluginId = config.getString("snapshot-plugin-id")) - } /** * Java API: Factory method from config `pekko.reliable-delivery.producer-controller.event-sourced-durable-queue` @@ -171,13 +170,12 @@ object EventSourcedProducerQueue { private case class CleanupTick[A]() extends DurableProducerQueue.Command[A] - def apply[A](persistenceId: PersistenceId): Behavior[DurableProducerQueue.Command[A]] = { + def apply[A](persistenceId: PersistenceId): Behavior[DurableProducerQueue.Command[A]] = Behaviors.setup { context => apply(persistenceId, Settings(context.system)) } - } - def apply[A](persistenceId: PersistenceId, settings: Settings): Behavior[DurableProducerQueue.Command[A]] = { + def apply[A](persistenceId: PersistenceId, settings: Settings): Behavior[DurableProducerQueue.Command[A]] = Behaviors.setup { context => context.setLoggerName(classOf[EventSourcedProducerQueue[A]]) val impl = new EventSourcedProducerQueue[A](context, settings.cleanupUnusedAfter) @@ -206,7 +204,6 @@ object EventSourcedProducerQueue { .restartWithBackoff(1.second.min(settings.restartMaxBackoff), settings.restartMaxBackoff, 0.1)) } } - } /** * Java API @@ -305,7 +302,7 @@ private class EventSourcedProducerQueue[A]( }.toSet } - def onCommandBeforeInitialCleanup(state: State[A], command: Command[A]): Effect[Event, State[A]] = { + def onCommandBeforeInitialCleanup(state: State[A], command: Command[A]): Effect[Event, State[A]] = command match { case _: CleanupTick[_] => val old = oldUnconfirmedToCleanup(state) @@ -321,9 +318,8 @@ private class EventSourcedProducerQueue[A]( case _ => Effect.stash() } - } - def onEvent(state: State[A], event: Event): State[A] = { + def onEvent(state: State[A], event: Event): State[A] = event match { case sent: MessageSent[A] @unchecked => state.addMessageSent(sent) @@ -332,6 +328,5 @@ private class EventSourcedProducerQueue[A]( case Cleanup(confirmationQualifiers) => state.cleanup(confirmationQualifiers).cleanupPartialChunkedMessages() } - } } diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/BehaviorSetup.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/BehaviorSetup.scala index cf8a2ae87f7..917f94c34eb 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/BehaviorSetup.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/BehaviorSetup.scala @@ -136,7 +136,7 @@ private[pekko] final class BehaviorSetup[C, E, S]( * `catchAndLog=true` should be used for "unknown" signals in the phases before Running * to avoid restart loops if restart supervision is used. */ - def onSignal[T](state: S, signal: Signal, catchAndLog: Boolean): Boolean = { + def onSignal[T](state: S, signal: Signal, catchAndLog: Boolean): Boolean = try { var handled = true signalHandler.applyOrElse((state, signal), (_: (S, Signal)) => handled = false) @@ -152,9 +152,8 @@ private[pekko] final class BehaviorSetup[C, E, S]( throw ex } } - } - def shouldSnapshot(state: S, event: E, sequenceNr: Long): SnapshotAfterPersist = { + def shouldSnapshot(state: S, event: E, sequenceNr: Long): SnapshotAfterPersist = retention match { case DisabledRetentionCriteria => if (snapshotWhen(state, event, sequenceNr)) SnapshotWithoutRetention @@ -165,7 +164,6 @@ private[pekko] final class BehaviorSetup[C, E, S]( else NoSnapshot case unexpected => throw new IllegalStateException(s"Unexpected retention criteria: $unexpected") } - } } diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/EventSourcedBehaviorImpl.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/EventSourcedBehaviorImpl.scala index 40a08328b8e..a4653ba56ea 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/EventSourcedBehaviorImpl.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/EventSourcedBehaviorImpl.scala @@ -138,7 +138,7 @@ private[pekko] final case class EventSourcedBehaviorImpl[Command, Event, State]( val stashState = new StashState(ctx.asInstanceOf[ActorContext[InternalProtocol]], settings) // This method ensures that the MDC is set before we use the internal logger - def internalLogger() = { + def internalLogger() = if (settings.useContextLoggerForInternalLogging) ctx.log else { // MDC is cleared (if used) from aroundReceive in ActorAdapter after processing each message, @@ -146,7 +146,6 @@ private[pekko] final case class EventSourcedBehaviorImpl[Command, Event, State]( ctx.log loggerForInternal } - } val actualSignalHandler: PartialFunction[(State, Signal), Unit] = signalHandler.orElse { // default signal handler is always the fallback @@ -262,9 +261,8 @@ private[pekko] final case class EventSourcedBehaviorImpl[Command, Event, State]( } override def withSnapshotSelectionCriteria( - selection: SnapshotSelectionCriteria): EventSourcedBehavior[Command, Event, State] = { + selection: SnapshotSelectionCriteria): EventSourcedBehavior[Command, Event, State] = copy(recovery = Recovery(selection.toClassic)) - } override def snapshotWhen(predicate: (State, Event, Long) => Boolean): EventSourcedBehavior[Command, Event, State] = copy(snapshotWhen = predicate) @@ -285,19 +283,16 @@ private[pekko] final case class EventSourcedBehaviorImpl[Command, Event, State]( backoffStrategy: BackoffSupervisorStrategy): EventSourcedBehavior[Command, Event, State] = copy(supervisionStrategy = backoffStrategy) - override def withRecovery(recovery: TypedRecovery): EventSourcedBehavior[Command, Event, State] = { + override def withRecovery(recovery: TypedRecovery): EventSourcedBehavior[Command, Event, State] = copy(recovery = recovery.toClassic) - } - override def withEventPublishing(enabled: Boolean): EventSourcedBehavior[Command, Event, State] = { + override def withEventPublishing(enabled: Boolean): EventSourcedBehavior[Command, Event, State] = copy(publishEvents = enabled) - } override private[pekko] def withReplication( - context: ReplicationContextImpl): EventSourcedBehavior[Command, Event, State] = { + context: ReplicationContextImpl): EventSourcedBehavior[Command, Event, State] = copy( replication = Some(ReplicationSetup(context.replicationId.replicaId, context.replicasAndQueryPlugins, context))) - } } /** Protocol used internally by the eventsourced behaviors. */ diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/ExternalInteractions.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/ExternalInteractions.scala index 21747792d2c..54843d70b76 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/ExternalInteractions.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/ExternalInteractions.scala @@ -94,7 +94,7 @@ private[pekko] trait JournalInteractions[C, E, S] { ctx: ActorContext[_], cmd: Any, state: Running.RunningState[S], - events: immutable.Seq[EventToPersist]): Running.RunningState[S] = { + events: immutable.Seq[EventToPersist]): Running.RunningState[S] = if (events.nonEmpty) { var newState = state @@ -123,7 +123,6 @@ private[pekko] trait JournalInteractions[C, E, S] { newState } else state - } @InternalStableApi private[pekko] def onWritesInitiated( @@ -138,9 +137,8 @@ private[pekko] trait JournalInteractions[C, E, S] { setup.selfClassic) } - protected def requestRecoveryPermit(): Unit = { + protected def requestRecoveryPermit(): Unit = setup.persistence.recoveryPermitter.tell(RecoveryPermitter.RequestRecoveryPermit, setup.selfClassic) - } /** Intended to be used in .onSignal(returnPermitOnStop) by behaviors */ protected def returnPermitOnStop @@ -154,13 +152,12 @@ private[pekko] trait JournalInteractions[C, E, S] { } /** Mutates setup, by setting the `holdingRecoveryPermit` to false */ - protected def tryReturnRecoveryPermit(reason: String): Unit = { + protected def tryReturnRecoveryPermit(reason: String): Unit = if (setup.holdingRecoveryPermit) { setup.internalLogger.debug("Returning recovery permit, reason: {}", reason) setup.persistence.recoveryPermitter.tell(RecoveryPermitter.ReturnRecoveryPermit, setup.selfClassic) setup.holdingRecoveryPermit = false } // else, no need to return the permit - } /** * On [[pekko.persistence.SaveSnapshotSuccess]], if `SnapshotCountRetentionCriteria.deleteEventsOnSnapshot` @@ -198,9 +195,8 @@ private[pekko] trait SnapshotInteractions[C, E, S] { * Instructs the snapshot store to load the specified snapshot and send it via an [[SnapshotOffer]] * to the running [[PersistentActor]]. */ - protected def loadSnapshot(criteria: SnapshotSelectionCriteria, toSequenceNr: Long): Unit = { + protected def loadSnapshot(criteria: SnapshotSelectionCriteria, toSequenceNr: Long): Unit = setup.snapshotStore.tell(LoadSnapshot(setup.persistenceId.id, criteria, toSequenceNr), setup.selfClassic) - } protected def internalSaveSnapshot(state: Running.RunningState[S]): Unit = { setup.internalLogger.debug("Saving snapshot sequenceNr [{}]", state.seqNr) @@ -222,12 +218,11 @@ private[pekko] trait SnapshotInteractions[C, E, S] { } /** Deletes the snapshots up to and including the `sequenceNr`. */ - protected def internalDeleteSnapshots(fromSequenceNr: Long, toSequenceNr: Long): Unit = { + protected def internalDeleteSnapshots(fromSequenceNr: Long, toSequenceNr: Long): Unit = if (toSequenceNr > 0) { val snapshotCriteria = SnapshotSelectionCriteria(minSequenceNr = fromSequenceNr, maxSequenceNr = toSequenceNr) setup.internalLogger.debug2("Deleting snapshots from sequenceNr [{}] to [{}]", fromSequenceNr, toSequenceNr) setup.snapshotStore .tell(SnapshotProtocol.DeleteSnapshots(setup.persistenceId.id, snapshotCriteria), setup.selfClassic) } - } } diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/ReplayingEvents.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/ReplayingEvents.scala index 3149255a3c6..c883cfcb39d 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/ReplayingEvents.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/ReplayingEvents.scala @@ -104,7 +104,7 @@ private[pekko] final class ReplayingEvents[C, E, S]( def onRecoveryFailed(@unused context: ActorContext[_], @unused reason: Throwable, @unused event: Option[Any]): Unit = () - override def onMessage(msg: InternalProtocol): Behavior[InternalProtocol] = { + override def onMessage(msg: InternalProtocol): Behavior[InternalProtocol] = msg match { case JournalResponse(r) => onJournalResponse(r) case SnapshotterResponse(r) => onSnapshotterResponse(r) @@ -116,7 +116,6 @@ private[pekko] final class ReplayingEvents[C, E, S]( case get: GetSeenSequenceNr => stashInternal(get) case RecoveryPermitGranted => Behaviors.unhandled // should not happen, we already have the permit } - } override def onSignal: PartialFunction[Signal, Behavior[InternalProtocol]] = { case PoisonPill => @@ -127,8 +126,8 @@ private[pekko] final class ReplayingEvents[C, E, S]( else Behaviors.unhandled } - private def onJournalResponse(response: JournalProtocol.Response): Behavior[InternalProtocol] = { - try { + private def onJournalResponse(response: JournalProtocol.Response): Behavior[InternalProtocol] = + try response match { case ReplayedMessage(repr) => var eventForErrorReporting: OptionVal[Any] = OptionVal.None @@ -203,16 +202,15 @@ private[pekko] final class ReplayingEvents[C, E, S]( case _ => Behaviors.unhandled } - } catch { + catch { case ex: UnstashException[_] => // let supervisor handle it, don't treat it as recovery failure throw ex case NonFatal(cause) => onRecoveryFailure(cause, None) } - } - private def onInternalCommand(cmd: InternalProtocol): Behavior[InternalProtocol] = { + private def onInternalCommand(cmd: InternalProtocol): Behavior[InternalProtocol] = // during recovery, stash all incoming commands if (state.receivedPoisonPill) { if (setup.settings.logOnStashing) @@ -221,7 +219,6 @@ private[pekko] final class ReplayingEvents[C, E, S]( } else { stashInternal(cmd) } - } protected def onRecoveryTick(snapshot: Boolean): Behavior[InternalProtocol] = if (!snapshot) { @@ -314,9 +311,8 @@ private[pekko] final class ReplayingEvents[C, E, S]( tryUnstashOne(new running.HandlingCommands(initialRunningState)) } } - } finally { + } finally setup.cancelRecoveryTimer() - } override def currentSequenceNumber: Long = state.seqNr diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/ReplayingSnapshot.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/ReplayingSnapshot.scala index e28411d96d9..442bc7a096f 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/ReplayingSnapshot.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/ReplayingSnapshot.scala @@ -65,7 +65,7 @@ private[pekko] class ReplayingSnapshot[C, E, S](override val setup: BehaviorSetu loadSnapshot(setup.recovery.fromSnapshot, setup.recovery.toSequenceNr) - def stay(receivedPoisonPill: Boolean): Behavior[InternalProtocol] = { + def stay(receivedPoisonPill: Boolean): Behavior[InternalProtocol] = Behaviors .receiveMessage[InternalProtocol] { case SnapshotterResponse(r) => onSnapshotterResponse(r, receivedPoisonPill) @@ -91,7 +91,6 @@ private[pekko] class ReplayingSnapshot[C, E, S](override val setup: BehaviorSetu if (setup.onSignal(setup.emptyState, signal, catchAndLog = true)) Behaviors.same else Behaviors.unhandled }) - } stay(receivedPoisonPillInPreviousPhase) } @@ -131,18 +130,15 @@ private[pekko] class ReplayingSnapshot[C, E, S](override val setup: BehaviorSetu onRecoveryFailure(ex) } else Behaviors.same // ignore, since we received the snapshot already - def onCommand(cmd: IncomingCommand[C]): Behavior[InternalProtocol] = { + def onCommand(cmd: IncomingCommand[C]): Behavior[InternalProtocol] = // during recovery, stash all incoming commands stashInternal(cmd) - } - def onReplicatedEvent(evt: InternalProtocol.ReplicatedEventEnvelope[E]): Behavior[InternalProtocol] = { + def onReplicatedEvent(evt: InternalProtocol.ReplicatedEventEnvelope[E]): Behavior[InternalProtocol] = stashInternal(evt) - } - def onPublishedEvent(event: PublishedEventImpl): Behavior[InternalProtocol] = { + def onPublishedEvent(event: PublishedEventImpl): Behavior[InternalProtocol] = stashInternal(event) - } def onJournalResponse(response: JournalProtocol.Response): Behavior[InternalProtocol] = { setup.internalLogger.debug( diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/ReplicationSetup.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/ReplicationSetup.scala index f34afe1a84b..ca63f951fc0 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/ReplicationSetup.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/ReplicationSetup.scala @@ -75,9 +75,8 @@ private[pekko] final class ReplicationContextImpl( override def persistenceId: PersistenceId = replicationId.persistenceId - override def currentTimeMillis(): Long = { + override def currentTimeMillis(): Long = WallClock.AlwaysIncreasingClock.currentTimeMillis() - } override def recoveryRunning: Boolean = { checkAccess("recoveryRunning") _recoveryRunning diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/RequestingRecoveryPermit.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/RequestingRecoveryPermit.scala index d3bf7a6076d..0d84a8f3871 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/RequestingRecoveryPermit.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/RequestingRecoveryPermit.scala @@ -50,7 +50,7 @@ private[pekko] class RequestingRecoveryPermit[C, E, S](override val setup: Behav // request a permit, as only once we obtain one we can start replaying requestRecoveryPermit() - def stay(receivedPoisonPill: Boolean): Behavior[InternalProtocol] = { + def stay(receivedPoisonPill: Boolean): Behavior[InternalProtocol] = Behaviors .receiveMessage[InternalProtocol] { case InternalProtocol.RecoveryPermitGranted => @@ -73,7 +73,6 @@ private[pekko] class RequestingRecoveryPermit[C, E, S](override val setup: Behav if (setup.onSignal(setup.emptyState, signal, catchAndLog = true)) Behaviors.same else Behaviors.unhandled } - } stay(receivedPoisonPill = false) } diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/RetentionCriteriaImpl.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/RetentionCriteriaImpl.scala index 6caa28b80dd..5d29ed95dfd 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/RetentionCriteriaImpl.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/RetentionCriteriaImpl.scala @@ -34,17 +34,15 @@ import pekko.persistence.typed.scaladsl def snapshotWhen(currentSequenceNr: Long): Boolean = currentSequenceNr % snapshotEveryNEvents == 0 - def deleteUpperSequenceNr(lastSequenceNr: Long): Long = { + def deleteUpperSequenceNr(lastSequenceNr: Long): Long = // Delete old events, retain the latest math.max(0, lastSequenceNr - (keepNSnapshots.toLong * snapshotEveryNEvents)) - } - def deleteLowerSequenceNr(upperSequenceNr: Long): Long = { + def deleteLowerSequenceNr(upperSequenceNr: Long): Long = // We could use 0 as fromSequenceNr to delete all older snapshots, but that might be inefficient for // large ranges depending on how it's implemented in the snapshot plugin. Therefore we use the // same window as defined for how much to keep in the retention criteria math.max(0, upperSequenceNr - (keepNSnapshots.toLong * snapshotEveryNEvents)) - } override def withDeleteEventsOnSnapshot: SnapshotCountRetentionCriteriaImpl = copy(deleteEventsOnSnapshot = true) diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/Running.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/Running.scala index f3846b930e1..a04b9102574 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/Running.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/Running.scala @@ -192,7 +192,7 @@ private[pekko] object Running { replicationControl = state.replicationControl.updated(replicaId, new ReplicationStreamControl { - override def fastForward(sequenceNumber: Long): Unit = { + override def fastForward(sequenceNumber: Long): Unit = // (logging is safe here since invoked on message receive OptionVal(controlRef.get) match { case OptionVal.Some(control) => @@ -207,7 +207,6 @@ private[pekko] object Running { replicaId, sequenceNumber) } - } })) } else { state @@ -218,9 +217,8 @@ private[pekko] object Running { private val timestampFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS") private val UTC = ZoneId.of("UTC") - def formatTimestamp(time: Long): String = { + def formatTimestamp(time: Long): String = timestampFormatter.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(time), UTC)) - } } // =============================================== @@ -244,9 +242,8 @@ private[pekko] object Running { _currentSequenceNumber = state.seqNr - private def alreadySeen(e: ReplicatedEvent[_]): Boolean = { + private def alreadySeen(e: ReplicatedEvent[_]): Boolean = e.originSequenceNr <= state.seenPerReplica.getOrElse(e.originReplica, 0L) - } def onMessage(msg: InternalProtocol): Behavior[InternalProtocol] = msg match { case IncomingCommand(c: C @unchecked) => onCommand(state, c) @@ -451,7 +448,7 @@ private[pekko] object Running { private def handleEventPersist( event: E, cmd: Any, - sideEffects: immutable.Seq[SideEffect[S]]): (Behavior[InternalProtocol], Boolean) = { + sideEffects: immutable.Seq[SideEffect[S]]): (Behavior[InternalProtocol], Boolean) = try { // apply the event before persist so that validation exception is handled before persisting // the invalid event, in case such validation is implemented in the event handler. @@ -501,15 +498,13 @@ private[pekko] object Running { shouldPublish = true, sideEffects), false) - } finally { + } finally setup.replication.foreach(_.clearContext()) - } - } private def handleEventPersistAll( events: immutable.Seq[E], cmd: Any, - sideEffects: immutable.Seq[SideEffect[S]]): (Behavior[InternalProtocol], Boolean) = { + sideEffects: immutable.Seq[SideEffect[S]]): (Behavior[InternalProtocol], Boolean) = if (events.nonEmpty) { try { // apply the event before persist so that validation exception is handled before persisting @@ -564,14 +559,12 @@ private[pekko] object Running { shouldPublish = true, sideEffects = sideEffects), false) - } finally { + } finally setup.replication.foreach(_.clearContext()) - } } else { // run side-effects even when no events are emitted (applySideEffects(sideEffects, state), true) } - } @tailrec def applyEffects( msg: Any, state: RunningState[S], @@ -654,7 +647,7 @@ private[pekko] object Running { private var eventCounter = 0 - override def onMessage(msg: InternalProtocol): Behavior[InternalProtocol] = { + override def onMessage(msg: InternalProtocol): Behavior[InternalProtocol] = msg match { case JournalResponse(r) => onJournalResponse(r) case in: IncomingCommand[C @unchecked] => onCommand(in) @@ -666,9 +659,8 @@ private[pekko] object Running { case RecoveryTickEvent(_) => Behaviors.unhandled case RecoveryPermitGranted => Behaviors.unhandled } - } - def onCommand(cmd: IncomingCommand[C]): Behavior[InternalProtocol] = { + def onCommand(cmd: IncomingCommand[C]): Behavior[InternalProtocol] = if (state.receivedPoisonPill) { if (setup.settings.logOnStashing) setup.internalLogger.debug("Discarding message [{}], because actor is to be stopped.", cmd) @@ -676,28 +668,25 @@ private[pekko] object Running { } else { stashInternal(cmd) } - } def onGetSeenSequenceNr(get: GetSeenSequenceNr): PersistingEvents = { get.replyTo ! state.seenPerReplica(get.replica) this } - def onReplicatedEvent(event: InternalProtocol.ReplicatedEventEnvelope[E]): Behavior[InternalProtocol] = { + def onReplicatedEvent(event: InternalProtocol.ReplicatedEventEnvelope[E]): Behavior[InternalProtocol] = if (state.receivedPoisonPill) { Behaviors.unhandled } else { stashInternal(event) } - } - def onPublishedEvent(event: PublishedEventImpl): Behavior[InternalProtocol] = { + def onPublishedEvent(event: PublishedEventImpl): Behavior[InternalProtocol] = if (state.receivedPoisonPill) { Behaviors.unhandled } else { stashInternal(event) } - } final def onJournalResponse(response: Response): Behavior[InternalProtocol] = { if (setup.internalLogger.isDebugEnabled) { @@ -780,9 +769,8 @@ private[pekko] object Running { else Behaviors.unhandled } - override def currentSequenceNumber: Long = { + override def currentSequenceNumber: Long = _currentSequenceNumber - } } // =============================================== @@ -796,7 +784,7 @@ private[pekko] object Running { with WithSeqNrAccessible { setup.setMdcPhase(PersistenceMdc.StoringSnapshot) - def onCommand(cmd: IncomingCommand[C]): Behavior[InternalProtocol] = { + def onCommand(cmd: IncomingCommand[C]): Behavior[InternalProtocol] = if (state.receivedPoisonPill) { if (setup.settings.logOnStashing) setup.internalLogger.debug("Discarding message [{}], because actor is to be stopped.", cmd) @@ -804,7 +792,6 @@ private[pekko] object Running { } else { stashInternal(cmd) } - } def onSaveSnapshotResponse(response: SnapshotProtocol.Response): Unit = { val signal = response match { @@ -906,7 +893,7 @@ private[pekko] object Running { def applySideEffect( effect: SideEffect[S], state: RunningState[S], - behavior: Behavior[InternalProtocol]): Behavior[InternalProtocol] = { + behavior: Behavior[InternalProtocol]): Behavior[InternalProtocol] = effect match { case _: Stop.type @unchecked => Behaviors.stopped @@ -919,7 +906,6 @@ private[pekko] object Running { callback.sideEffect(state.state) behavior } - } /** * Handle journal responses for non-persist events workloads. diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/StashManagement.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/StashManagement.scala index 8a1d917f979..b7210940a60 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/StashManagement.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/StashManagement.scala @@ -95,41 +95,37 @@ private[pekko] trait StashManagement[C, E, S] { * `unstashAll` was called, i.e. if subsequent commands stash more, those will * not be unstashed until `unstashAll` is called again. */ - protected def unstashAll(): Unit = { + protected def unstashAll(): Unit = if (stashState.userStashBuffer.nonEmpty) { logUnstashAll() stashState.startUnstashAll() // tryUnstashOne is called from EventSourcedRunning at the end of processing each command // or when persist is completed } - } protected def isUnstashAllInProgress: Boolean = stashState.isUnstashAllInProgress - private def logStashMessage(msg: InternalProtocol, buffer: StashBuffer[InternalProtocol]): Unit = { + private def logStashMessage(msg: InternalProtocol, buffer: StashBuffer[InternalProtocol]): Unit = if (setup.settings.logOnStashing) setup.internalLogger.debugN( "Stashing message to {} stash: [{}] ", if (buffer eq stashState.internalStashBuffer) "internal" else "user", msg) - } - private def logUnstashMessage(buffer: StashBuffer[InternalProtocol]): Unit = { + private def logUnstashMessage(buffer: StashBuffer[InternalProtocol]): Unit = if (setup.settings.logOnStashing) setup.internalLogger.debugN( "Unstashing message from {} stash: [{}]", if (buffer eq stashState.internalStashBuffer) "internal" else "user", buffer.head) - } - private def logUnstashAll(): Unit = { + private def logUnstashAll(): Unit = if (setup.settings.logOnStashing) setup.internalLogger.debug2( "Unstashing all [{}] messages from user stash, first is: [{}]", stashState.userStashBuffer.size, stashState.userStashBuffer.head) - } } @@ -154,10 +150,9 @@ private[pekko] class StashState(ctx: ActorContext[InternalProtocol], settings: E def isUnstashAllInProgress: Boolean = unstashAllInProgress > 0 - def decrementUnstashAllProgress(): Unit = { + def decrementUnstashAllProgress(): Unit = if (isUnstashAllInProgress) unstashAllInProgress -= 1 - } def startUnstashAll(): Unit = unstashAllInProgress = _userStashBuffer.size diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/VersionVector.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/VersionVector.scala index d8a2ab99e2b..28636f42708 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/VersionVector.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/internal/VersionVector.scala @@ -208,9 +208,8 @@ private[pekko] sealed abstract class VersionVector { * 4. Version 1 is CONCURRENT (<>) to Version 2 otherwise. * }}} */ - def compareTo(that: VersionVector): Ordering = { + def compareTo(that: VersionVector): Ordering = compareOnlyTo(that, FullOrder) - } def merge(that: VersionVector): VersionVector @@ -234,10 +233,9 @@ private[pekko] sealed abstract class VersionVector { else ManyVersionVector(TreeMap(key -> version, k -> v)) } - override def updated(k: String, v: Long): VersionVector = { + override def updated(k: String, v: Long): VersionVector = if (k == key) copy(version = v) else ManyVersionVector(TreeMap(key -> version, k -> v)) - } override def versionAt(k: String): Long = if (k == key) version @@ -251,7 +249,7 @@ private[pekko] sealed abstract class VersionVector { @InternalApi private[pekko] override def versionsIterator: Iterator[(String, Long)] = Iterator.single((key, version)) - override def merge(that: VersionVector): VersionVector = { + override def merge(that: VersionVector): VersionVector = that match { case OneVersionVector(n2, v2) => if (key == n2) if (version >= v2) this else OneVersionVector(n2, v2) @@ -263,7 +261,6 @@ private[pekko] sealed abstract class VersionVector { else vs2.updated(key, version) VersionVector(mergedVersions) } - } override def toString: String = s"VersionVector($key -> $version)" @@ -304,7 +301,7 @@ private[pekko] sealed abstract class VersionVector { @InternalApi private[pekko] override def versionsIterator: Iterator[(String, Long)] = versions.iterator - override def merge(that: VersionVector): VersionVector = { + override def merge(that: VersionVector): VersionVector = if (that.isEmpty) this else if (this.isEmpty) that else @@ -324,7 +321,6 @@ private[pekko] sealed abstract class VersionVector { else versions.updated(n2, v2) VersionVector(mergedVersions) } - } override def toString: String = versions.map { case (k, v) => k + " -> " + v }.mkString("VersionVector(", ", ", ")") diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/javadsl/CommandHandler.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/javadsl/CommandHandler.scala index 0395615e4c2..570877246d3 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/javadsl/CommandHandler.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/javadsl/CommandHandler.scala @@ -205,7 +205,7 @@ final class CommandHandlerBuilderByState[Command, Event, S <: State, State] @Int private var cases: List[CommandHandlerCase[Command, Event, State]] = Nil - private def addCase(predicate: Command => Boolean, handler: BiFunction[S, Command, Effect[Event, State]]): Unit = { + private def addCase(predicate: Command => Boolean, handler: BiFunction[S, Command, Effect[Event, State]]): Unit = cases = CommandHandlerCase[Command, Event, State]( commandPredicate = predicate, statePredicate = state => @@ -213,7 +213,6 @@ final class CommandHandlerBuilderByState[Command, Event, S <: State, State] @Int else statePredicate.test(state.asInstanceOf[S]) && stateClass.isAssignableFrom(state.getClass), handler.asInstanceOf[BiFunction[State, Command, Effect[Event, State]]]) :: cases - } /** * Matches any command which the given `predicate` returns true for. @@ -277,12 +276,11 @@ final class CommandHandlerBuilderByState[Command, Event, S <: State, State] @Int */ def onCommand[C <: Command]( commandClass: Class[C], - handler: JFunction[C, Effect[Event, State]]): CommandHandlerBuilderByState[Command, Event, S, State] = { + handler: JFunction[C, Effect[Event, State]]): CommandHandlerBuilderByState[Command, Event, S, State] = onCommand[C](commandClass, new BiFunction[S, C, Effect[Event, State]] { override def apply(state: S, cmd: C): Effect[Event, State] = handler(cmd) }) - } /** * Matches commands that are of the given `commandClass` or subclass thereof. @@ -295,12 +293,11 @@ final class CommandHandlerBuilderByState[Command, Event, S <: State, State] @Int */ def onCommand[C <: Command]( commandClass: Class[C], - handler: Supplier[Effect[Event, State]]): CommandHandlerBuilderByState[Command, Event, S, State] = { + handler: Supplier[Effect[Event, State]]): CommandHandlerBuilderByState[Command, Event, S, State] = onCommand[C](commandClass, new BiFunction[S, C, Effect[Event, State]] { override def apply(state: S, cmd: C): Effect[Event, State] = handler.get() }) - } /** * Matches any command. diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/javadsl/CommandHandlerWithReply.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/javadsl/CommandHandlerWithReply.scala index 4d9a1440d09..d77dd50a075 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/javadsl/CommandHandlerWithReply.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/javadsl/CommandHandlerWithReply.scala @@ -217,7 +217,7 @@ final class CommandHandlerWithReplyBuilderByState[Command, Event, S <: State, St private def addCase( predicate: Command => Boolean, - handler: BiFunction[S, Command, ReplyEffect[Event, State]]): Unit = { + handler: BiFunction[S, Command, ReplyEffect[Event, State]]): Unit = cases = CommandHandlerCase[Command, Event, State]( commandPredicate = predicate, statePredicate = state => @@ -225,7 +225,6 @@ final class CommandHandlerWithReplyBuilderByState[Command, Event, S <: State, St else statePredicate.test(state.asInstanceOf[S]) && stateClass.isAssignableFrom(state.getClass), handler.asInstanceOf[BiFunction[State, Command, ReplyEffect[Event, State]]]) :: cases - } /** * Matches any command which the given `predicate` returns true for. @@ -285,12 +284,11 @@ final class CommandHandlerWithReplyBuilderByState[Command, Event, S <: State, St * otherwise you risk to 'shadow' part of your command handlers. */ def onCommand[C <: Command](commandClass: Class[C], handler: JFunction[C, ReplyEffect[Event, State]]) - : CommandHandlerWithReplyBuilderByState[Command, Event, S, State] = { + : CommandHandlerWithReplyBuilderByState[Command, Event, S, State] = onCommand[C](commandClass, new BiFunction[S, C, ReplyEffect[Event, State]] { override def apply(state: S, cmd: C): ReplyEffect[Event, State] = handler(cmd) }) - } /** * Matches commands that are of the given `commandClass` or subclass thereof. @@ -303,12 +301,11 @@ final class CommandHandlerWithReplyBuilderByState[Command, Event, S <: State, St */ def onCommand[C <: Command]( commandClass: Class[C], - handler: Supplier[ReplyEffect[Event, State]]): CommandHandlerWithReplyBuilderByState[Command, Event, S, State] = { + handler: Supplier[ReplyEffect[Event, State]]): CommandHandlerWithReplyBuilderByState[Command, Event, S, State] = onCommand[C](commandClass, new BiFunction[S, C, ReplyEffect[Event, State]] { override def apply(state: S, cmd: C): ReplyEffect[Event, State] = handler.get() }) - } /** * Matches any command. diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/javadsl/EventHandler.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/javadsl/EventHandler.scala index d561dd99861..1f2d25a7029 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/javadsl/EventHandler.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/javadsl/EventHandler.scala @@ -204,14 +204,13 @@ final class EventHandlerBuilderByState[S <: State, State, Event]( private var cases: List[EventHandlerCase[State, Event]] = Nil - private def addCase(eventPredicate: Event => Boolean, handler: BiFunction[State, Event, State]): Unit = { + private def addCase(eventPredicate: Event => Boolean, handler: BiFunction[State, Event, State]): Unit = cases = EventHandlerCase[State, Event]( statePredicate = state => if (state == null) statePredicate.test(state.asInstanceOf[S]) else statePredicate.test(state.asInstanceOf[S]) && stateClass.isAssignableFrom(state.getClass), eventPredicate = eventPredicate, handler) :: cases - } /** * Match any event which is an instance of `E` or a subtype of `E`. @@ -239,12 +238,11 @@ final class EventHandlerBuilderByState[S <: State, State, Event]( */ def onEvent[E <: Event]( eventClass: Class[E], - handler: JFunction[E, State]): EventHandlerBuilderByState[S, State, Event] = { + handler: JFunction[E, State]): EventHandlerBuilderByState[S, State, Event] = onEvent[E](eventClass, new BiFunction[S, E, State] { override def apply(state: S, event: E): State = handler(event) }) - } /** * Match any event which is an instance of `E` or a subtype of `E`. diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/javadsl/EventSourcedBehavior.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/javadsl/EventSourcedBehavior.scala index c133bcbdbdb..517e9f87733 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/javadsl/EventSourcedBehavior.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/javadsl/EventSourcedBehavior.scala @@ -36,9 +36,8 @@ abstract class EventSourcedBehavior[Command, Event, State] private[pekko] ( /** * @param persistenceId stable unique identifier for the event sourced behavior */ - def this(persistenceId: PersistenceId) = { + def this(persistenceId: PersistenceId) = this(persistenceId, Optional.empty[BackoffSupervisorStrategy]) - } /** * If using onPersistFailure the supervision is only around the event sourced behavior not any outer setup/withTimers @@ -48,9 +47,8 @@ abstract class EventSourcedBehavior[Command, Event, State] private[pekko] ( * @param persistenceId stable unique identifier for the event sourced behavior * @param onPersistFailure BackoffSupervisionStrategy for persist failures */ - def this(persistenceId: PersistenceId, onPersistFailure: BackoffSupervisorStrategy) = { + def this(persistenceId: PersistenceId, onPersistFailure: BackoffSupervisorStrategy) = this(persistenceId, Optional.ofNullable(onPersistFailure)) - } /** * Factory of effects. @@ -110,9 +108,8 @@ abstract class EventSourcedBehavior[Command, Event, State] private[pekko] ( /** * @return A new, mutable, command handler builder */ - protected def newCommandHandlerBuilder(): CommandHandlerBuilder[Command, Event, State] = { + protected def newCommandHandlerBuilder(): CommandHandlerBuilder[Command, Event, State] = CommandHandlerBuilder.builder[Command, Event, State]() - } /** * @return A new, mutable, event handler builder @@ -240,9 +237,8 @@ abstract class EventSourcedBehavior[Command, Event, State] private[pekko] ( /** * The last sequence number that was persisted, can only be called from inside the handlers of an `EventSourcedBehavior` */ - final def lastSequenceNumber(ctx: ActorContext[_]): Long = { + final def lastSequenceNumber(ctx: ActorContext[_]): Long = scaladsl.EventSourcedBehavior.lastSequenceNumber(ctx.asScala) - } } @@ -256,13 +252,11 @@ abstract class EventSourcedBehaviorWithEnforcedReplies[Command, Event, State]( backoffSupervisorStrategy: Optional[BackoffSupervisorStrategy]) extends EventSourcedBehavior[Command, Event, State](persistenceId, backoffSupervisorStrategy) { - def this(persistenceId: PersistenceId) = { + def this(persistenceId: PersistenceId) = this(persistenceId, Optional.empty[BackoffSupervisorStrategy]) - } - def this(persistenceId: PersistenceId, backoffSupervisorStrategy: BackoffSupervisorStrategy) = { + def this(persistenceId: PersistenceId, backoffSupervisorStrategy: BackoffSupervisorStrategy) = this(persistenceId, Optional.ofNullable(backoffSupervisorStrategy)) - } /** * Implement by handling incoming commands and return an `Effect()` to persist or signal other effects @@ -279,9 +273,8 @@ abstract class EventSourcedBehaviorWithEnforcedReplies[Command, Event, State]( /** * @return A new, mutable, command handler builder */ - protected def newCommandHandlerWithReplyBuilder(): CommandHandlerWithReplyBuilder[Command, Event, State] = { + protected def newCommandHandlerWithReplyBuilder(): CommandHandlerWithReplyBuilder[Command, Event, State] = CommandHandlerWithReplyBuilder.builder[Command, Event, State]() - } /** * Use [[EventSourcedBehaviorWithEnforcedReplies#newCommandHandlerWithReplyBuilder]] instead, or diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/javadsl/ReplicatedEventSourcedBehavior.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/javadsl/ReplicatedEventSourcedBehavior.scala index 74e890afbda..79eb8ddd783 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/javadsl/ReplicatedEventSourcedBehavior.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/javadsl/ReplicatedEventSourcedBehavior.scala @@ -43,10 +43,9 @@ abstract class ReplicatedEventSourcedBehavior[Command, Event, State]( /** * INTERNAL API: DeferredBehavior init, not for user extension */ - @InternalApi override def apply(context: TypedActorContext[Command]): Behavior[Command] = { + @InternalApi override def apply(context: TypedActorContext[Command]): Behavior[Command] = createEventSourcedBehavior() // context not user extendable so there should never be any other impls .withReplication(replicationContext.asInstanceOf[ReplicationContextImpl]) .withEventPublishing(withEventPublishing) - } } diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/scaladsl/PersistentFSMMigration.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/scaladsl/PersistentFSMMigration.scala index dda90f75e26..aafd160cb7d 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/scaladsl/PersistentFSMMigration.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/scaladsl/PersistentFSMMigration.scala @@ -35,11 +35,10 @@ object PersistentFSMMigration { def snapshotAdapter[State](adapt: (String, Any, Option[FiniteDuration]) => State): SnapshotAdapter[State] = new SnapshotAdapter[State] { override def toJournal(state: State): Any = state - override def fromJournal(from: Any): State = { + override def fromJournal(from: Any): State = from match { case PersistentFSMSnapshot(stateIdentifier, data, timeout) => adapt(stateIdentifier, data, timeout) case data => data.asInstanceOf[State] } - } } } diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/serialization/ReplicatedEventSourcingSerializer.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/serialization/ReplicatedEventSourcingSerializer.scala index 66fc3a55db1..fb74ae6b74a 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/serialization/ReplicatedEventSourcingSerializer.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/serialization/ReplicatedEventSourcingSerializer.scala @@ -50,7 +50,7 @@ import scala.collection.immutable.TreeMap if (aSize == bSize) { val aIter = aByteString.iterator val bIter = bByteString.iterator - @tailrec def findDiff(): Int = { + @tailrec def findDiff(): Int = if (aIter.hasNext) { val aByte = aIter.nextByte() val bByte = bIter.nextByte() @@ -58,7 +58,6 @@ import scala.collection.immutable.TreeMap else if (aByte > bByte) 1 else findDiff() } else 0 - } findDiff() } else if (aSize < bSize) -1 else 1 @@ -274,7 +273,7 @@ import scala.collection.immutable.TreeMap b.build() } - def replicatedEventMetadataToProto(rem: ReplicatedEventMetadata): ReplicatedEventSourcing.ReplicatedEventMetadata = { + def replicatedEventMetadataToProto(rem: ReplicatedEventMetadata): ReplicatedEventSourcing.ReplicatedEventMetadata = ReplicatedEventSourcing.ReplicatedEventMetadata .newBuilder() .setOriginSequenceNr(rem.originSequenceNr) @@ -282,24 +281,21 @@ import scala.collection.immutable.TreeMap .setOriginReplica(rem.originReplica.id) .setVersionVector(versionVectorToProto(rem.version)) .build() - } - def replicatedSnapshotMetadataToByteArray(rsm: ReplicatedSnapshotMetadata): Array[Byte] = { + def replicatedSnapshotMetadataToByteArray(rsm: ReplicatedSnapshotMetadata): Array[Byte] = ReplicatedEventSourcing.ReplicatedSnapshotMetadata .newBuilder() .setVersion(versionVectorToProto(rsm.version)) .addAllSeenPerReplica(rsm.seenPerReplica.map(seenToProto).asJava) .build() .toByteArray - } - def seenToProto(t: (ReplicaId, Long)): ReplicatedEventSourcing.ReplicatedSnapshotMetadata.Seen = { + def seenToProto(t: (ReplicaId, Long)): ReplicatedEventSourcing.ReplicatedSnapshotMetadata.Seen = ReplicatedEventSourcing.ReplicatedSnapshotMetadata.Seen .newBuilder() .setReplicaId(t._1.id) .setSequenceNr(t._2) .build() - } def orsetFromBinary(bytes: Array[Byte]): ORSet[Any] = orsetFromProto(ReplicatedEventSourcing.ORSet.parseFrom(bytes)) @@ -314,9 +310,8 @@ import scala.collection.immutable.TreeMap new ORSet.FullStateDeltaOp(orsetFromProto(ReplicatedEventSourcing.ORSet.parseFrom(bytes))) private def orsetDeltaGroupToProto(deltaGroup: ORSet.DeltaGroup[_]): ReplicatedEventSourcing.ORSetDeltaGroup = { - def createEntry(opType: ReplicatedEventSourcing.ORSetDeltaOp, u: ORSet[_]) = { + def createEntry(opType: ReplicatedEventSourcing.ORSetDeltaOp, u: ORSet[_]) = ReplicatedEventSourcing.ORSetDeltaGroup.Entry.newBuilder().setOperation(opType).setUnderlying(orsetToProto(u)) - } val b = ReplicatedEventSourcing.ORSetDeltaGroup.newBuilder() deltaGroup.ops.foreach { @@ -391,13 +386,12 @@ import scala.collection.immutable.TreeMap metadataFromProto(parsed) } - private def metadataFromProto(parsed: ReplicatedEventSourcing.ReplicatedEventMetadata): ReplicatedEventMetadata = { + private def metadataFromProto(parsed: ReplicatedEventSourcing.ReplicatedEventMetadata): ReplicatedEventMetadata = ReplicatedEventMetadata( ReplicaId(parsed.getOriginReplica), parsed.getOriginSequenceNr, versionVectorFromProto(parsed.getVersionVector), parsed.getConcurrent) - } def replicatedSnapshotMetadataFromBinary(bytes: Array[Byte]): ReplicatedSnapshotMetadata = { val parsed: ReplicatedEventSourcing.ReplicatedSnapshotMetadata = diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/internal/BehaviorSetup.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/internal/BehaviorSetup.scala index 924f03e5f44..34d5d229614 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/internal/BehaviorSetup.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/internal/BehaviorSetup.scala @@ -96,7 +96,7 @@ private[pekko] final class BehaviorSetup[C, S]( * `catchAndLog=true` should be used for "unknown" signals in the phases before Running * to avoid restart loops if restart supervision is used. */ - def onSignal[T](state: S, signal: Signal, catchAndLog: Boolean): Boolean = { + def onSignal[T](state: S, signal: Signal, catchAndLog: Boolean): Boolean = try { var handled = true signalHandler.applyOrElse((state, signal), (_: (S, Signal)) => handled = false) @@ -112,7 +112,6 @@ private[pekko] final class BehaviorSetup[C, S]( throw ex } } - } } diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/internal/DurableStateBehaviorImpl.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/internal/DurableStateBehaviorImpl.scala index b87589e68fb..f42f0c4e9d8 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/internal/DurableStateBehaviorImpl.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/internal/DurableStateBehaviorImpl.scala @@ -84,7 +84,7 @@ private[pekko] final case class DurableStateBehaviorImpl[Command, State]( val stashState = new StashState(ctx.asInstanceOf[ActorContext[InternalProtocol]], settings) // This method ensures that the MDC is set before we use the internal logger - def internalLogger() = { + def internalLogger() = if (settings.useContextLoggerForInternalLogging) ctx.log else { // MDC is cleared (if used) from aroundReceive in ActorAdapter after processing each message, @@ -92,7 +92,6 @@ private[pekko] final case class DurableStateBehaviorImpl[Command, State]( ctx.log loggerForInternal } - } val actualSignalHandler: PartialFunction[(State, Signal), Unit] = signalHandler.orElse { // default signal handler is always the fallback diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/internal/DurableStateStoreInteractions.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/internal/DurableStateStoreInteractions.scala index a2505e5fae8..d485f5d89a8 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/internal/DurableStateStoreInteractions.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/internal/DurableStateStoreInteractions.scala @@ -90,9 +90,8 @@ private[pekko] trait DurableStateStoreInteractions[C, S] { private[pekko] def onDeleteInitiated(@unused ctx: ActorContext[_], @unused cmd: Any): Unit = () - protected def requestRecoveryPermit(): Unit = { + protected def requestRecoveryPermit(): Unit = setup.persistence.recoveryPermitter.tell(RecoveryPermitter.RequestRecoveryPermit, setup.selfClassic) - } /** Intended to be used in .onSignal(returnPermitOnStop) by behaviors */ protected def returnPermitOnStop @@ -106,12 +105,11 @@ private[pekko] trait DurableStateStoreInteractions[C, S] { } /** Mutates setup, by setting the `holdingRecoveryPermit` to false */ - protected def tryReturnRecoveryPermit(reason: String): Unit = { + protected def tryReturnRecoveryPermit(reason: String): Unit = if (setup.holdingRecoveryPermit) { setup.internalLogger.debug("Returning recovery permit, reason: {}", reason) setup.persistence.recoveryPermitter.tell(RecoveryPermitter.ReturnRecoveryPermit, setup.selfClassic) setup.holdingRecoveryPermit = false } // else, no need to return the permit - } } diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/internal/Recovering.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/internal/Recovering.scala index 115d7bd4ac2..1b8f4e410ae 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/internal/Recovering.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/internal/Recovering.scala @@ -49,14 +49,13 @@ import pekko.util.unused @InternalApi private[pekko] object Recovering { - def apply[C, S](setup: BehaviorSetup[C, S], receivedPoisonPill: Boolean): Behavior[InternalProtocol] = { + def apply[C, S](setup: BehaviorSetup[C, S], receivedPoisonPill: Boolean): Behavior[InternalProtocol] = Behaviors.setup { _ => // protect against store stalling forever because of store overloaded and such setup.startRecoveryTimer() val recoveryState = RecoveryState[S](0L, null.asInstanceOf[S], receivedPoisonPill, System.nanoTime()) new Recovering(setup.setMdcPhase(PersistenceMdc.RecoveringState), recoveryState) } - } @InternalApi private[pekko] final case class RecoveryState[State]( @@ -82,7 +81,7 @@ private[pekko] class Recovering[C, S]( onRecoveryStart(setup.context) internalGet(setup.context) - override def onMessage(msg: InternalProtocol): Behavior[InternalProtocol] = { + override def onMessage(msg: InternalProtocol): Behavior[InternalProtocol] = msg match { case success: GetSuccess[S @unchecked] => onGetSuccess(success.result) case GetFailure(exc) => onGetFailure(exc) @@ -101,7 +100,6 @@ private[pekko] class Recovering[C, S]( case DeleteSuccess => Behaviors.unhandled case _: DeleteFailure => Behaviors.unhandled } - } override def onSignal: PartialFunction[Signal, Behavior[InternalProtocol]] = { case PoisonPill => @@ -147,10 +145,9 @@ private[pekko] class Recovering[C, S]( onRecoveryFailure(ex) } - def onCommand(cmd: IncomingCommand[C]): Behavior[InternalProtocol] = { + def onCommand(cmd: IncomingCommand[C]): Behavior[InternalProtocol] = // during recovery, stash all incoming commands stashInternal(cmd) - } def onGetSuccess(result: GetObjectResult[S]): Behavior[InternalProtocol] = { val state = result.value match { @@ -190,13 +187,11 @@ private[pekko] class Recovering[C, S]( val running = new Running(setup.setMdcPhase(PersistenceMdc.RunningCmds)) tryUnstashOne(new running.HandlingCommands(runningState)) } - } finally { + } finally setup.cancelRecoveryTimer() - } - def onGetFailure(cause: Throwable): Behavior[InternalProtocol] = { + def onGetFailure(cause: Throwable): Behavior[InternalProtocol] = onRecoveryFailure(cause) - } override def currentRevision: Long = recoveryState.revision diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/internal/RequestingRecoveryPermit.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/internal/RequestingRecoveryPermit.scala index 1b24c908f2f..2d7cdbbf05f 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/internal/RequestingRecoveryPermit.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/internal/RequestingRecoveryPermit.scala @@ -49,7 +49,7 @@ private[pekko] class RequestingRecoveryPermit[C, S](override val setup: Behavior // request a permit, as only once we obtain one we can start recovery requestRecoveryPermit() - def stay(receivedPoisonPill: Boolean): Behavior[InternalProtocol] = { + def stay(receivedPoisonPill: Boolean): Behavior[InternalProtocol] = Behaviors .receiveMessage[InternalProtocol] { case InternalProtocol.RecoveryPermitGranted => @@ -72,7 +72,6 @@ private[pekko] class RequestingRecoveryPermit[C, S](override val setup: Behavior if (setup.onSignal(setup.emptyState, signal, catchAndLog = true)) Behaviors.same else Behaviors.unhandled } - } stay(receivedPoisonPill = false) } diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/internal/Running.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/internal/Running.scala index d4a0a3fcba6..c5c58f15bbd 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/internal/Running.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/internal/Running.scala @@ -60,9 +60,8 @@ private[pekko] object Running { def nextRevision(): RunningState[State] = copy(revision = revision + 1) - def applyState[C, E](@unused setup: BehaviorSetup[C, State], updated: State): RunningState[State] = { + def applyState[C, E](@unused setup: BehaviorSetup[C, State], updated: State): RunningState[State] = copy(state = updated) - } } } @@ -169,9 +168,8 @@ private[pekko] object Running { } } - def adaptState(newState: S): Any = { + def adaptState(newState: S): Any = setup.snapshotAdapter.toJournal(newState) - } setup.setMdcPhase(PersistenceMdc.RunningCmds) @@ -198,7 +196,7 @@ private[pekko] object Running { extends AbstractBehavior[InternalProtocol](setup.context) with WithRevisionAccessible { - override def onMessage(msg: InternalProtocol): Behavior[InternalProtocol] = { + override def onMessage(msg: InternalProtocol): Behavior[InternalProtocol] = msg match { case UpsertSuccess => onUpsertSuccess() case UpsertFailure(exc) => onUpsertFailed(exc) @@ -211,9 +209,8 @@ private[pekko] object Running { case DeleteSuccess => Behaviors.unhandled case DeleteFailure(_) => Behaviors.unhandled } - } - def onCommand(cmd: IncomingCommand[C]): Behavior[InternalProtocol] = { + def onCommand(cmd: IncomingCommand[C]): Behavior[InternalProtocol] = if (state.receivedPoisonPill) { if (setup.settings.logOnStashing) setup.internalLogger.debug("Discarding message [{}], because actor is to be stopped.", cmd) @@ -221,7 +218,6 @@ private[pekko] object Running { } else { stashInternal(cmd) } - } final def onUpsertSuccess(): Behavior[InternalProtocol] = { if (setup.internalLogger.isDebugEnabled) { @@ -251,9 +247,8 @@ private[pekko] object Running { else Behaviors.unhandled } - override def currentRevision: Long = { + override def currentRevision: Long = _currentRevision - } } // =============================================== @@ -278,7 +273,7 @@ private[pekko] object Running { def applySideEffect( effect: SideEffect[S], state: RunningState[S], - behavior: Behavior[InternalProtocol]): Behavior[InternalProtocol] = { + behavior: Behavior[InternalProtocol]): Behavior[InternalProtocol] = effect match { case _: Stop.type @unchecked => Behaviors.stopped @@ -291,7 +286,6 @@ private[pekko] object Running { callback.sideEffect(state.state) behavior } - } @InternalStableApi private[pekko] def onWriteFailed(@unused ctx: ActorContext[_], @unused reason: Throwable): Unit = () diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/internal/StashManagement.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/internal/StashManagement.scala index 6f09122e43a..1c830e0d7e8 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/internal/StashManagement.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/internal/StashManagement.scala @@ -95,41 +95,37 @@ private[pekko] trait StashManagement[C, S] { * `unstashAll` was called, i.e. if subsequent commands stash more, those will * not be unstashed until `unstashAll` is called again. */ - protected def unstashAll(): Unit = { + protected def unstashAll(): Unit = if (stashState.userStashBuffer.nonEmpty) { logUnstashAll() stashState.startUnstashAll() // tryUnstashOne is called from Running at the end of processing each command // or when persist is completed } - } protected def isUnstashAllInProgress: Boolean = stashState.isUnstashAllInProgress - private def logStashMessage(msg: InternalProtocol, buffer: StashBuffer[InternalProtocol]): Unit = { + private def logStashMessage(msg: InternalProtocol, buffer: StashBuffer[InternalProtocol]): Unit = if (setup.settings.logOnStashing) setup.internalLogger.debugN( "Stashing message to {} stash: [{}] ", if (buffer eq stashState.internalStashBuffer) "internal" else "user", msg) - } - private def logUnstashMessage(buffer: StashBuffer[InternalProtocol]): Unit = { + private def logUnstashMessage(buffer: StashBuffer[InternalProtocol]): Unit = if (setup.settings.logOnStashing) setup.internalLogger.debugN( "Unstashing message from {} stash: [{}]", if (buffer eq stashState.internalStashBuffer) "internal" else "user", buffer.head) - } - private def logUnstashAll(): Unit = { + private def logUnstashAll(): Unit = if (setup.settings.logOnStashing) setup.internalLogger.debug2( "Unstashing all [{}] messages from user stash, first is: [{}]", stashState.userStashBuffer.size, stashState.userStashBuffer.head) - } } @@ -154,10 +150,9 @@ private[pekko] class StashState(ctx: ActorContext[InternalProtocol], settings: D def isUnstashAllInProgress: Boolean = unstashAllInProgress > 0 - def decrementUnstashAllProgress(): Unit = { + def decrementUnstashAllProgress(): Unit = if (isUnstashAllInProgress) unstashAllInProgress -= 1 - } def startUnstashAll(): Unit = unstashAllInProgress = _userStashBuffer.size diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/javadsl/CommandHandler.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/javadsl/CommandHandler.scala index f906f09a779..9bbf8507fac 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/javadsl/CommandHandler.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/javadsl/CommandHandler.scala @@ -206,7 +206,7 @@ final class CommandHandlerBuilderByState[Command, S <: State, State] @InternalAp private var cases: List[CommandHandlerCase[Command, State]] = Nil - private def addCase(predicate: Command => Boolean, handler: BiFunction[S, Command, Effect[State]]): Unit = { + private def addCase(predicate: Command => Boolean, handler: BiFunction[S, Command, Effect[State]]): Unit = cases = CommandHandlerCase[Command, State]( commandPredicate = predicate, statePredicate = state => @@ -214,7 +214,6 @@ final class CommandHandlerBuilderByState[Command, S <: State, State] @InternalAp else statePredicate.test(state.asInstanceOf[S]) && stateClass.isAssignableFrom(state.getClass), handler.asInstanceOf[BiFunction[State, Command, Effect[State]]]) :: cases - } /** * Matches any command which the given `predicate` returns true for. @@ -278,12 +277,11 @@ final class CommandHandlerBuilderByState[Command, S <: State, State] @InternalAp */ def onCommand[C <: Command]( commandClass: Class[C], - handler: JFunction[C, Effect[State]]): CommandHandlerBuilderByState[Command, S, State] = { + handler: JFunction[C, Effect[State]]): CommandHandlerBuilderByState[Command, S, State] = onCommand[C](commandClass, new BiFunction[S, C, Effect[State]] { override def apply(state: S, cmd: C): Effect[State] = handler(cmd) }) - } /** * Matches commands that are of the given `commandClass` or subclass thereof. @@ -296,12 +294,11 @@ final class CommandHandlerBuilderByState[Command, S <: State, State] @InternalAp */ def onCommand[C <: Command]( commandClass: Class[C], - handler: Supplier[Effect[State]]): CommandHandlerBuilderByState[Command, S, State] = { + handler: Supplier[Effect[State]]): CommandHandlerBuilderByState[Command, S, State] = onCommand[C](commandClass, new BiFunction[S, C, Effect[State]] { override def apply(state: S, cmd: C): Effect[State] = handler.get() }) - } /** * Matches any command. diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/javadsl/CommandHandlerWithReply.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/javadsl/CommandHandlerWithReply.scala index 9b885f96c64..e3050ea7e1e 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/javadsl/CommandHandlerWithReply.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/javadsl/CommandHandlerWithReply.scala @@ -216,7 +216,7 @@ final class CommandHandlerWithReplyBuilderByState[Command, S <: State, State] @I private var cases: List[CommandHandlerCase[Command, State]] = Nil - private def addCase(predicate: Command => Boolean, handler: BiFunction[S, Command, ReplyEffect[State]]): Unit = { + private def addCase(predicate: Command => Boolean, handler: BiFunction[S, Command, ReplyEffect[State]]): Unit = cases = CommandHandlerCase[Command, State]( commandPredicate = predicate, statePredicate = state => @@ -224,7 +224,6 @@ final class CommandHandlerWithReplyBuilderByState[Command, S <: State, State] @I else statePredicate.test(state.asInstanceOf[S]) && stateClass.isAssignableFrom(state.getClass), handler.asInstanceOf[BiFunction[State, Command, ReplyEffect[State]]]) :: cases - } /** * Matches any command which the given `predicate` returns true for. @@ -288,12 +287,11 @@ final class CommandHandlerWithReplyBuilderByState[Command, S <: State, State] @I */ def onCommand[C <: Command]( commandClass: Class[C], - handler: JFunction[C, ReplyEffect[State]]): CommandHandlerWithReplyBuilderByState[Command, S, State] = { + handler: JFunction[C, ReplyEffect[State]]): CommandHandlerWithReplyBuilderByState[Command, S, State] = onCommand[C](commandClass, new BiFunction[S, C, ReplyEffect[State]] { override def apply(state: S, cmd: C): ReplyEffect[State] = handler(cmd) }) - } /** * Matches commands that are of the given `commandClass` or subclass thereof. @@ -306,12 +304,11 @@ final class CommandHandlerWithReplyBuilderByState[Command, S <: State, State] @I */ def onCommand[C <: Command]( commandClass: Class[C], - handler: Supplier[ReplyEffect[State]]): CommandHandlerWithReplyBuilderByState[Command, S, State] = { + handler: Supplier[ReplyEffect[State]]): CommandHandlerWithReplyBuilderByState[Command, S, State] = onCommand[C](commandClass, new BiFunction[S, C, ReplyEffect[State]] { override def apply(state: S, cmd: C): ReplyEffect[State] = handler.get() }) - } /** * Matches any command. diff --git a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/javadsl/DurableStateBehavior.scala b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/javadsl/DurableStateBehavior.scala index 7aebd4422bc..fc67fb8f925 100644 --- a/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/javadsl/DurableStateBehavior.scala +++ b/persistence-typed/src/main/scala/org/apache/pekko/persistence/typed/state/javadsl/DurableStateBehavior.scala @@ -43,9 +43,8 @@ abstract class DurableStateBehavior[Command, State] private[pekko] ( /** * @param persistenceId stable unique identifier for the `DurableStateBehavior` */ - def this(persistenceId: PersistenceId) = { + def this(persistenceId: PersistenceId) = this(persistenceId, Optional.empty[BackoffSupervisorStrategy]) - } /** * If using onPersistFailure the supervision is only around the `DurableStateBehavior` not any outer setup/withTimers @@ -55,9 +54,8 @@ abstract class DurableStateBehavior[Command, State] private[pekko] ( * @param persistenceId stable unique identifier for the `DurableStateBehavior` * @param onPersistFailure BackoffSupervisionStrategy for persist failures */ - def this(persistenceId: PersistenceId, onPersistFailure: BackoffSupervisorStrategy) = { + def this(persistenceId: PersistenceId, onPersistFailure: BackoffSupervisorStrategy) = this(persistenceId, Optional.ofNullable(onPersistFailure)) - } /** * Factory of effects. @@ -104,9 +102,8 @@ abstract class DurableStateBehavior[Command, State] private[pekko] ( /** * @return A new, mutable, command handler builder */ - protected def newCommandHandlerBuilder(): CommandHandlerBuilder[Command, State] = { + protected def newCommandHandlerBuilder(): CommandHandlerBuilder[Command, State] = CommandHandlerBuilder.builder[Command, State]() - } /** * Override and define the `DurableStateStore` plugin id that this actor should use instead of the default. @@ -155,9 +152,8 @@ abstract class DurableStateBehavior[Command, State] private[pekko] ( /** * The last sequence number that was persisted, can only be called from inside the handlers of a `DurableStateBehavior` */ - final def lastSequenceNumber(ctx: ActorContext[_]): Long = { + final def lastSequenceNumber(ctx: ActorContext[_]): Long = scaladsl.DurableStateBehavior.lastSequenceNumber(ctx.asScala) - } } @@ -171,13 +167,11 @@ abstract class DurableStateBehaviorWithEnforcedReplies[Command, State]( backoffSupervisorStrategy: Optional[BackoffSupervisorStrategy]) extends DurableStateBehavior[Command, State](persistenceId, backoffSupervisorStrategy) { - def this(persistenceId: PersistenceId) = { + def this(persistenceId: PersistenceId) = this(persistenceId, Optional.empty[BackoffSupervisorStrategy]) - } - def this(persistenceId: PersistenceId, backoffSupervisorStrategy: BackoffSupervisorStrategy) = { + def this(persistenceId: PersistenceId, backoffSupervisorStrategy: BackoffSupervisorStrategy) = this(persistenceId, Optional.ofNullable(backoffSupervisorStrategy)) - } /** * Implement by handling incoming commands and return an `Effect()` to persist or signal other effects @@ -194,9 +188,8 @@ abstract class DurableStateBehaviorWithEnforcedReplies[Command, State]( /** * @return A new, mutable, command handler builder */ - protected def newCommandHandlerWithReplyBuilder(): CommandHandlerWithReplyBuilder[Command, State] = { + protected def newCommandHandlerWithReplyBuilder(): CommandHandlerWithReplyBuilder[Command, State] = CommandHandlerWithReplyBuilder.builder[Command, State]() - } /** * Use [[DurableStateBehaviorWithEnforcedReplies#newCommandHandlerWithReplyBuilder]] instead, or diff --git a/persistence-typed/src/test/scala/docs/org/apache/pekko/persistence/typed/BasicPersistentBehaviorCompileOnly.scala b/persistence-typed/src/test/scala/docs/org/apache/pekko/persistence/typed/BasicPersistentBehaviorCompileOnly.scala index 841cc1e6e32..ba18ef87932 100644 --- a/persistence-typed/src/test/scala/docs/org/apache/pekko/persistence/typed/BasicPersistentBehaviorCompileOnly.scala +++ b/persistence-typed/src/test/scala/docs/org/apache/pekko/persistence/typed/BasicPersistentBehaviorCompileOnly.scala @@ -72,14 +72,13 @@ object BasicPersistentBehaviorCompileOnly { // #command-handler // #effects - def onCommand(subscriber: ActorRef[State], state: State, command: Command): Effect[Event, State] = { + def onCommand(subscriber: ActorRef[State], state: State, command: Command): Effect[Event, State] = command match { case Add(data) => Effect.persist(Added(data)).thenRun(newState => subscriber ! newState) case Clear => Effect.persist(Cleared).thenRun((newState: State) => subscriber ! newState).thenStop() } - } // #effects // #event-handler @@ -172,14 +171,13 @@ object BasicPersistentBehaviorCompileOnly { } } - def apply(entityId: String): Behavior[Command] = { + def apply(entityId: String): Behavior[Command] = EventSourcedBehavior[Command, Event, State]( persistenceId = PersistenceId("ShoppingCart", entityId), emptyState = State(), commandHandler = (state, cmd) => throw new NotImplementedError("TODO: process the command & return an Effect"), eventHandler = (state, evt) => throw new NotImplementedError("TODO: process the event return the next state")) .withTagger(event => tagEvent(entityId, event)) - } // #tagging-query } @@ -193,10 +191,10 @@ object BasicPersistentBehaviorCompileOnly { commandHandler = (state, cmd) => throw new NotImplementedError("TODO: process the command & return an Effect"), eventHandler = (state, evt) => throw new NotImplementedError("TODO: process the event return the next state")) - .snapshotWhen((state, _, _) => { + .snapshotWhen { (state, _, _) => context.log.info2("Snapshot actor {} => state: {}", context.self.path.name, state) true - }) + } } // #wrapPersistentBehavior } diff --git a/persistence-typed/src/test/scala/docs/org/apache/pekko/persistence/typed/BlogPostEntity.scala b/persistence-typed/src/test/scala/docs/org/apache/pekko/persistence/typed/BlogPostEntity.scala index a2a086ab683..98b6b2bd1ad 100644 --- a/persistence-typed/src/test/scala/docs/org/apache/pekko/persistence/typed/BlogPostEntity.scala +++ b/persistence-typed/src/test/scala/docs/org/apache/pekko/persistence/typed/BlogPostEntity.scala @@ -67,12 +67,11 @@ object BlogPostEntity { // #commands // #behavior - def apply(entityId: String, persistenceId: PersistenceId): Behavior[Command] = { + def apply(entityId: String, persistenceId: PersistenceId): Behavior[Command] = Behaviors.setup { context => context.log.info("Starting BlogPostEntity {}", entityId) EventSourcedBehavior[Command, Event, State](persistenceId, emptyState = BlankState, commandHandler, eventHandler) } - } // #behavior // #command-handler @@ -121,12 +120,11 @@ object BlogPostEntity { } } - private def publish(state: DraftState, replyTo: ActorRef[Done]): Effect[Event, State] = { + private def publish(state: DraftState, replyTo: ActorRef[Done]): Effect[Event, State] = Effect.persist(Published(state.postId)).thenRun { _ => println(s"Blog post ${state.postId} was published") replyTo ! Done } - } private def getPost(state: DraftState, replyTo: ActorRef[PostContent]): Effect[Event, State] = { replyTo ! state.content diff --git a/persistence-typed/src/test/scala/docs/org/apache/pekko/persistence/typed/BlogPostEntityDurableState.scala b/persistence-typed/src/test/scala/docs/org/apache/pekko/persistence/typed/BlogPostEntityDurableState.scala index 00a94414a5a..d77b91ec5cb 100644 --- a/persistence-typed/src/test/scala/docs/org/apache/pekko/persistence/typed/BlogPostEntityDurableState.scala +++ b/persistence-typed/src/test/scala/docs/org/apache/pekko/persistence/typed/BlogPostEntityDurableState.scala @@ -59,12 +59,11 @@ object BlogPostEntityDurableState { // #commands // #behavior - def apply(entityId: String, persistenceId: PersistenceId): Behavior[Command] = { + def apply(entityId: String, persistenceId: PersistenceId): Behavior[Command] = Behaviors.setup { context => context.log.info("Starting BlogPostEntityDurableState {}", entityId) DurableStateBehavior[Command, State](persistenceId, emptyState = BlankState, commandHandler) } - } // #behavior // #command-handler @@ -96,27 +95,24 @@ object BlogPostEntityDurableState { } } - private def addPost(cmd: AddPost): Effect[State] = { + private def addPost(cmd: AddPost): Effect[State] = // #reply Effect.persist(DraftState(cmd.content)).thenRun { _ => // After persist is done additional side effects can be performed cmd.replyTo ! StatusReply.Success(AddPostDone(cmd.content.postId)) } - // #reply - } + // #reply - private def changeBody(state: DraftState, cmd: ChangeBody): Effect[State] = { + private def changeBody(state: DraftState, cmd: ChangeBody): Effect[State] = Effect.persist(state.withBody(cmd.newBody)).thenRun { _ => cmd.replyTo ! Done } - } - private def publish(state: DraftState, replyTo: ActorRef[Done]): Effect[State] = { + private def publish(state: DraftState, replyTo: ActorRef[Done]): Effect[State] = Effect.persist(PublishedState(state.content)).thenRun { _ => println(s"Blog post ${state.postId} was published") replyTo ! Done } - } private def getPost(state: DraftState, replyTo: ActorRef[PostContent]): Effect[State] = { replyTo ! state.content diff --git a/persistence-typed/src/test/scala/docs/org/apache/pekko/persistence/typed/DurableStatePersistentBehaviorCompileOnly.scala b/persistence-typed/src/test/scala/docs/org/apache/pekko/persistence/typed/DurableStatePersistentBehaviorCompileOnly.scala index d481e1029a4..bca032d3ce6 100644 --- a/persistence-typed/src/test/scala/docs/org/apache/pekko/persistence/typed/DurableStatePersistentBehaviorCompileOnly.scala +++ b/persistence-typed/src/test/scala/docs/org/apache/pekko/persistence/typed/DurableStatePersistentBehaviorCompileOnly.scala @@ -61,12 +61,11 @@ object DurableStatePersistentBehaviorCompileOnly { // #command-handler // #behavior - def counter(id: String): DurableStateBehavior[Command[_], State] = { + def counter(id: String): DurableStateBehavior[Command[_], State] = DurableStateBehavior.apply[Command[_], State]( persistenceId = PersistenceId.ofUniqueId(id), emptyState = State(0), commandHandler = commandHandler) - } // #behavior } @@ -76,13 +75,12 @@ object DurableStatePersistentBehaviorCompileOnly { final case class State(value: Int) extends CborSerializable - def counter(persistenceId: PersistenceId): DurableStateBehavior[Command[_], State] = { + def counter(persistenceId: PersistenceId): DurableStateBehavior[Command[_], State] = DurableStateBehavior.apply[Command[_], State]( persistenceId, emptyState = State(0), commandHandler = (state, command) => throw new NotImplementedError("TODO: process the command & return an Effect")) - } } // #structure @@ -97,7 +95,7 @@ object DurableStatePersistentBehaviorCompileOnly { final case class State(value: Int) extends CborSerializable - def counter(persistenceId: PersistenceId): DurableStateBehavior[Command[_], State] = { + def counter(persistenceId: PersistenceId): DurableStateBehavior[Command[_], State] = DurableStateBehavior.withEnforcedReplies[Command[_], State]( persistenceId, emptyState = State(0), @@ -110,7 +108,6 @@ object DurableStatePersistentBehaviorCompileOnly { case GetValue(replyTo) => Effect.reply(replyTo)(state) }) - } // #effects } diff --git a/persistence-typed/src/test/scala/docs/org/apache/pekko/persistence/typed/MovieWatchList.scala b/persistence-typed/src/test/scala/docs/org/apache/pekko/persistence/typed/MovieWatchList.scala index 3fffba188fe..f2894df6cbd 100644 --- a/persistence-typed/src/test/scala/docs/org/apache/pekko/persistence/typed/MovieWatchList.scala +++ b/persistence-typed/src/test/scala/docs/org/apache/pekko/persistence/typed/MovieWatchList.scala @@ -32,12 +32,11 @@ object MovieWatchList { final case class MovieRemoved(movieId: String) extends Event final case class MovieList(movieIds: Set[String]) { - def applyEvent(event: Event): MovieList = { + def applyEvent(event: Event): MovieList = event match { case MovieAdded(movieId) => copy(movieIds = movieIds + movieId) case MovieRemoved(movieId) => copy(movieIds = movieIds + movieId) } - } } private val commandHandler: CommandHandler[Command, Event, MovieList] = { (state, cmd) => @@ -52,12 +51,11 @@ object MovieWatchList { } } - def behavior(userId: String): Behavior[Command] = { + def behavior(userId: String): Behavior[Command] = EventSourcedBehavior[Command, Event, MovieList]( persistenceId = PersistenceId("movies", userId), emptyState = MovieList(Set.empty), commandHandler, eventHandler = (state, event) => state.applyEvent(event)) - } } diff --git a/persistence-typed/src/test/scala/docs/org/apache/pekko/persistence/typed/PersistentFsmToTypedMigrationSpec.scala b/persistence-typed/src/test/scala/docs/org/apache/pekko/persistence/typed/PersistentFsmToTypedMigrationSpec.scala index 3a6e8443796..2fbca6c65d3 100644 --- a/persistence-typed/src/test/scala/docs/org/apache/pekko/persistence/typed/PersistentFsmToTypedMigrationSpec.scala +++ b/persistence-typed/src/test/scala/docs/org/apache/pekko/persistence/typed/PersistentFsmToTypedMigrationSpec.scala @@ -96,7 +96,7 @@ object ShoppingCartBehavior { class PersistentFsmEventAdapter extends EventAdapter[DomainEvent, Any] { override def toJournal(e: DomainEvent): Any = e override def manifest(event: DomainEvent): String = "" - override def fromJournal(journalEvent: Any, manifest: String): EventSeq[DomainEvent] = { + override def fromJournal(journalEvent: Any, manifest: String): EventSeq[DomainEvent] = journalEvent match { case _: StateChangeEvent => // In this example the state transitions can be inferred from the events @@ -109,7 +109,6 @@ object ShoppingCartBehavior { EventSeq.single(other.asInstanceOf[DomainEvent]) } - } } // #event-adapter @@ -165,7 +164,7 @@ object ShoppingCartBehavior { // #command-handler // #event-handler - def eventHandler(state: State, event: DomainEvent): State = { + def eventHandler(state: State, event: DomainEvent): State = state match { case la @ LookingAround(cart) => event match { @@ -187,7 +186,6 @@ object ShoppingCartBehavior { } case Paid(_) => state // no events after paid } - } // #event-handler private def behavior(pid: PersistenceId): Behavior[Command] = @@ -238,9 +236,8 @@ class PersistentFsmToTypedMigrationSpec extends AnyWordSpec with ScalaFutures wi classicProbe.watch(fsmRef) fsmRef ! PoisonPill classicProbe.expectTerminated(fsmRef) - } finally { + } finally classicActorSystem.terminate().futureValue - } val typedTestKit = ActorTestKit("System", PersistentFsmToTypedMigrationSpec.config) try { @@ -253,9 +250,8 @@ class PersistentFsmToTypedMigrationSpec extends AnyWordSpec with ScalaFutures wi typedReplacement ! ShoppingCartBehavior.Buy typedReplacement ! ShoppingCartBehavior.Leave typedProbe.expectTerminated(typedReplacement) - } finally { + } finally typedTestKit.shutdownTestKit() - } } @@ -276,9 +272,8 @@ class PersistentFsmToTypedMigrationSpec extends AnyWordSpec with ScalaFutures wi fsmRef ! Buy fsmRef.tell(GetCurrentCart, classicProbe.ref) classicProbe.expectMsg(NonEmptyShoppingCart(Seq(shirt))) - } finally { + } finally classicActorSystem.terminate().futureValue - } val typedTestKit = ActorTestKit("TypedSystem", PersistentFsmToTypedMigrationSpec.config) try { @@ -287,9 +282,8 @@ class PersistentFsmToTypedMigrationSpec extends AnyWordSpec with ScalaFutures wi val typedReplacement = spawn(ShoppingCartBehavior(PersistenceId.ofUniqueId(pid))) typedReplacement ! ShoppingCartBehavior.GetCurrentCart(typedProbe.ref) typedProbe.expectMessage(NonEmptyShoppingCart(Seq(shirt))) - } finally { + } finally typedTestKit.shutdownTestKit() - } } } diff --git a/persistence-typed/src/test/scala/docs/org/apache/pekko/persistence/typed/StashingExample.scala b/persistence-typed/src/test/scala/docs/org/apache/pekko/persistence/typed/StashingExample.scala index 6a6e6bc7cf6..17569b0ce5e 100644 --- a/persistence-typed/src/test/scala/docs/org/apache/pekko/persistence/typed/StashingExample.scala +++ b/persistence-typed/src/test/scala/docs/org/apache/pekko/persistence/typed/StashingExample.scala @@ -47,7 +47,7 @@ object StashingExample { eventHandler = (state, event) => applyEvent(state, event)) .onPersistFailure(SupervisorStrategy.restartWithBackoff(1.second, 30.seconds, 0.2)) - private def onCommand(state: State, command: Command): Effect[Event, State] = { + private def onCommand(state: State, command: Command): Effect[Event, State] = state.taskIdInProgress match { case None => command match { @@ -81,15 +81,13 @@ object StashingExample { Effect.stash() } } - } - private def applyEvent(state: State, event: Event): State = { + private def applyEvent(state: State, event: Event): State = event match { case TaskStarted(taskId) => State(Option(taskId)) case TaskStep(_, _) => state case TaskCompleted(_) => State(None) } - } } // #stashing } diff --git a/persistence-typed/src/test/scala/org/apache/pekko/persistence/typed/internal/RecoveryPermitterSpec.scala b/persistence-typed/src/test/scala/org/apache/pekko/persistence/typed/internal/RecoveryPermitterSpec.scala index fcd3e6bcd2a..511bc8b9905 100644 --- a/persistence-typed/src/test/scala/org/apache/pekko/persistence/typed/internal/RecoveryPermitterSpec.scala +++ b/persistence-typed/src/test/scala/org/apache/pekko/persistence/typed/internal/RecoveryPermitterSpec.scala @@ -202,7 +202,7 @@ class RecoveryPermitterSpec extends ScalaTestWithActorTestKit(s""" val stopProbe = createTestProbe[ActorRef[Command]]() val parent = LoggingTestKit.error("Exception during recovery.").expect { - spawn(Behaviors.setup[Command](ctx => { + spawn(Behaviors.setup[Command] { ctx => val persistentActor = ctx.spawnAnonymous(persistentBehavior("p3", p3, p3, throwOnRecovery = true)) Behaviors.receive[Command] { @@ -214,7 +214,7 @@ class RecoveryPermitterSpec extends ScalaTestWithActorTestKit(s""" persistentActor ! message Behaviors.same } - })) + }) } p3.expectMessage(Recovered) // stop it diff --git a/persistence-typed/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/PersistentActorCompileOnlyTest.scala b/persistence-typed/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/PersistentActorCompileOnlyTest.scala index c82341ddfd3..4ada56f039a 100644 --- a/persistence-typed/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/PersistentActorCompileOnlyTest.scala +++ b/persistence-typed/src/test/scala/org/apache/pekko/persistence/typed/scaladsl/PersistentActorCompileOnlyTest.scala @@ -153,10 +153,10 @@ object PersistentActorCompileOnlyTest { case (_, MoodChanged(to)) => to }) - Behaviors.withTimers((timers: TimerScheduler[Command]) => { + Behaviors.withTimers { (timers: TimerScheduler[Command]) => timers.startTimerWithFixedDelay(MoodSwing, 10.seconds) b - }) + } } object ExplicitSnapshots { diff --git a/persistence/src/main/scala/org/apache/pekko/persistence/AtLeastOnceDelivery.scala b/persistence/src/main/scala/org/apache/pekko/persistence/AtLeastOnceDelivery.scala index 2e806316202..e4d94f8809e 100644 --- a/persistence/src/main/scala/org/apache/pekko/persistence/AtLeastOnceDelivery.scala +++ b/persistence/src/main/scala/org/apache/pekko/persistence/AtLeastOnceDelivery.scala @@ -147,9 +147,8 @@ trait AtLeastOnceDelivery extends PersistentActor with AtLeastOnceDeliveryLike { * This method will throw [[AtLeastOnceDelivery.MaxUnconfirmedMessagesExceededException]] * if [[#numberOfUnconfirmed]] is greater than or equal to [[#maxUnconfirmedMessages]]. */ - def deliver(destination: ActorPath)(deliveryIdToMessage: Long => Any): Unit = { + def deliver(destination: ActorPath)(deliveryIdToMessage: Long => Any): Unit = internalDeliver(destination)(deliveryIdToMessage) - } /** * Scala API: Send the message created by the `deliveryIdToMessage` function to @@ -171,9 +170,8 @@ trait AtLeastOnceDelivery extends PersistentActor with AtLeastOnceDeliveryLike { * This method will throw [[AtLeastOnceDelivery.MaxUnconfirmedMessagesExceededException]] * if [[#numberOfUnconfirmed]] is greater than or equal to [[#maxUnconfirmedMessages]]. */ - def deliver(destination: ActorSelection)(deliveryIdToMessage: Long => Any): Unit = { + def deliver(destination: ActorSelection)(deliveryIdToMessage: Long => Any): Unit = internalDeliver(destination)(deliveryIdToMessage) - } } @@ -248,13 +246,12 @@ trait AtLeastOnceDeliveryLike extends Eventsourced { private var deliverySequenceNr = 0L private var unconfirmed = immutable.SortedMap.empty[Long, Delivery] - private def startRedeliverTask(): Unit = { + private def startRedeliverTask(): Unit = if (redeliverTask.isEmpty) { val interval = redeliverInterval / 2 redeliverTask = Some( context.system.scheduler.scheduleWithFixedDelay(interval, interval, self, RedeliveryTick)(context.dispatcher)) } - } private def cancelRedeliveryTask(): Unit = { redeliverTask.foreach(_.cancel()) @@ -307,14 +304,13 @@ trait AtLeastOnceDeliveryLike extends Eventsourced { * @see [[#deliver]] * @return `true` the first time the `deliveryId` is confirmed, i.e. `false` for duplicate confirm */ - def confirmDelivery(deliveryId: Long): Boolean = { + def confirmDelivery(deliveryId: Long): Boolean = if (unconfirmed.contains(deliveryId)) { unconfirmed -= deliveryId if (unconfirmed.isEmpty) cancelRedeliveryTask() true } else false - } /** * Number of messages that have not been confirmed yet. diff --git a/persistence/src/main/scala/org/apache/pekko/persistence/Eventsourced.scala b/persistence/src/main/scala/org/apache/pekko/persistence/Eventsourced.scala index 8ce0562bcd3..4e748b84990 100644 --- a/persistence/src/main/scala/org/apache/pekko/persistence/Eventsourced.scala +++ b/persistence/src/main/scala/org/apache/pekko/persistence/Eventsourced.scala @@ -192,14 +192,13 @@ private[persistence] trait Eventsourced * @param event the event that was to be persisted */ @InternalStableApi - protected def onPersistFailure(cause: Throwable, event: Any, seqNr: Long): Unit = { + protected def onPersistFailure(cause: Throwable, event: Any, seqNr: Long): Unit = log.error( cause, "Failed to persist event type [{}] with sequence number [{}] for persistenceId [{}].", event.getClass.getName, seqNr, persistenceId) - } /** * Called when the journal rejected `persist` of an event. The event was not @@ -210,7 +209,7 @@ private[persistence] trait Eventsourced * @param event the event that was to be persisted */ @InternalStableApi - protected def onPersistRejected(cause: Throwable, event: Any, seqNr: Long): Unit = { + protected def onPersistRejected(cause: Throwable, event: Any, seqNr: Long): Unit = log.error( cause, "Rejected to persist event type [{}] with sequence number [{}] for persistenceId [{}] due to [{}].", @@ -218,7 +217,6 @@ private[persistence] trait Eventsourced seqNr, persistenceId, cause.getMessage) - } private def stashInternally(currMsg: Any): Unit = try internalStash.stash() @@ -273,11 +271,11 @@ private[persistence] trait Eventsourced } /** INTERNAL API. */ - override protected[pekko] def aroundPreRestart(reason: Throwable, message: Option[Any]): Unit = { + override protected[pekko] def aroundPreRestart(reason: Throwable, message: Option[Any]): Unit = try { internalStash.unstashAll() unstashAll(unstashFilterPredicate) - } finally { + } finally message match { case Some(WriteMessageSuccess(m, _)) => flushJournalBatch() @@ -292,8 +290,6 @@ private[persistence] trait Eventsourced flushJournalBatch() super.aroundPreRestart(reason, mo) } - } - } /** INTERNAL API. */ override protected[pekko] def aroundPostRestart(reason: Throwable): Unit = { @@ -308,7 +304,7 @@ private[persistence] trait Eventsourced unstashAll(unstashFilterPredicate) } finally super.aroundPostStop() - override def unhandled(message: Any): Unit = { + override def unhandled(message: Any): Unit = message match { case RecoveryCompleted => // mute case SaveSnapshotFailure(m, e) => @@ -338,11 +334,9 @@ private[persistence] trait Eventsourced e.getMessage) case m => super.unhandled(m) } - } - private def changeState(state: State): Unit = { + private def changeState(state: State): Unit = currentState = state - } private def updateLastSequenceNr(persistent: PersistentRepr): Unit = if (persistent.sequenceNr > _lastSequenceNr) _lastSequenceNr = persistent.sequenceNr @@ -363,9 +357,8 @@ private[persistence] trait Eventsourced } @InternalStableApi - private def sendBatchedEventsToJournal(journalBatch: Vector[PersistentEnvelope]): Unit = { + private def sendBatchedEventsToJournal(journalBatch: Vector[PersistentEnvelope]): Unit = journal ! WriteMessages(journalBatch, self, instanceId) - } private def log: LoggingAdapter = Logging(context.system, this) @@ -438,9 +431,8 @@ private[persistence] trait Eventsourced } @InternalStableApi - private def batchAtomicWrite(atomicWrite: AtomicWrite): Unit = { + private def batchAtomicWrite(atomicWrite: AtomicWrite): Unit = eventBatch ::= atomicWrite - } /** * Internal API @@ -529,7 +521,7 @@ private[persistence] trait Eventsourced * * @param toSequenceNr upper sequence number (inclusive) bound of persistent messages to be deleted. */ - def deleteMessages(toSequenceNr: Long): Unit = { + def deleteMessages(toSequenceNr: Long): Unit = if (toSequenceNr == Long.MaxValue || toSequenceNr <= lastSequenceNr) journal ! DeleteMessagesTo(persistenceId, toSequenceNr, self) else @@ -537,7 +529,6 @@ private[persistence] trait Eventsourced new RuntimeException( s"toSequenceNr [$toSequenceNr] must be less than or equal to lastSequenceNr [$lastSequenceNr]"), toSequenceNr) - } /** * INTERNAL API. @@ -565,30 +556,27 @@ private[persistence] trait Eventsourced /** * Returns `true` if this persistent actor is currently recovering. */ - def recoveryRunning: Boolean = { + def recoveryRunning: Boolean = // currentState is null if this is called from constructor if (currentState == null) true else currentState.recoveryRunning - } /** * Returns `true` if this persistent actor has successfully finished recovery. */ def recoveryFinished: Boolean = !recoveryRunning - override def stash(): Unit = { + override def stash(): Unit = context.asInstanceOf[ActorCell].currentMessage match { case Envelope(_: JournalProtocol.Response, _) => throw new IllegalStateException("Do not call stash inside of persist callback or during recovery.") case _ => super.stash() } - } - override def unstashAll(): Unit = { + override def unstashAll(): Unit = // Internally, all messages are processed by unstashing them from // the internal stash one-by-one. Hence, an unstashAll() from the // user stash must be prepended to the internal stash. internalStash.prepend(clearStash()) - } private trait State { def stateReceive(receive: Receive, message: Any): Unit @@ -686,15 +674,14 @@ private[persistence] trait Eventsourced journal ! ReplayMessages(lastSequenceNr + 1L, toSnr, replayMax, persistenceId, self) } - def isSnapshotOptional: Boolean = { - try { + def isSnapshotOptional: Boolean = + try Persistence(context.system).configFor(snapshotStore).getBoolean("snapshot-is-optional") - } catch { + catch { case NonFatal(exc) => log.error(exc, "Invalid snapshot-is-optional configuration.") false // fail recovery } - } try message match { case LoadSnapshotResult(snapshot, toSnr) => @@ -840,19 +827,16 @@ private[persistence] trait Eventsourced finally flushBatch() @InternalStableApi - private def writeEventSucceeded(p: PersistentRepr): Unit = { + private def writeEventSucceeded(p: PersistentRepr): Unit = peekApplyHandler(p.payload) - } @InternalStableApi - private def writeEventRejected(p: PersistentRepr, cause: Throwable): Unit = { + private def writeEventRejected(p: PersistentRepr, cause: Throwable): Unit = onPersistRejected(cause, p.payload, p.sequenceNr) - } @InternalStableApi - private def writeEventFailed(p: PersistentRepr, cause: Throwable): Unit = { + private def writeEventFailed(p: PersistentRepr, cause: Throwable): Unit = onPersistFailure(cause, p.payload, p.sequenceNr) - } /** * Common receive handler for processingCommands and persistingEvents diff --git a/persistence/src/main/scala/org/apache/pekko/persistence/Persistence.scala b/persistence/src/main/scala/org/apache/pekko/persistence/Persistence.scala index 9efbb112bc2..aadd40750f0 100644 --- a/persistence/src/main/scala/org/apache/pekko/persistence/Persistence.scala +++ b/persistence/src/main/scala/org/apache/pekko/persistence/Persistence.scala @@ -183,24 +183,21 @@ object Persistence extends ExtensionId[Persistence] with ExtensionIdProvider { @InternalApi private[pekko] def verifyPluginConfigExists( config: Config, pluginId: String, - pluginType: String): Unit = { + pluginType: String): Unit = if (!isEmpty(pluginId) && !config.hasPath(pluginId)) throw new IllegalArgumentException(s"$pluginType plugin [$pluginId] configuration doesn't exist.") - } /** * INTERNAL API * @throws java.lang.IllegalArgumentException if `pluginId` is empty (undefined) */ - @InternalApi private[pekko] def verifyPluginConfigIsDefined(pluginId: String, pluginType: String): Unit = { + @InternalApi private[pekko] def verifyPluginConfigIsDefined(pluginId: String, pluginType: String): Unit = if (isEmpty(pluginId)) throw new IllegalArgumentException(s"$pluginType plugin is not configured, see 'reference.conf'") - } /** Check for default or missing identity. */ - private def isEmpty(text: String) = { + private def isEmpty(text: String) = text == null || text.isEmpty - } } /** @@ -298,9 +295,8 @@ class Persistence(val system: ExtendedActorSystem) extends Extension { * If no adapters are registered for a given journal the EventAdapters object will simply return the identity * adapter for each class, otherwise the most specific adapter matching a given class will be returned. */ - final def adaptersFor(journalPluginId: String): EventAdapters = { + final def adaptersFor(journalPluginId: String): EventAdapters = adaptersFor(journalPluginId: String, ConfigFactory.empty) - } /** * Returns an [[pekko.persistence.journal.EventAdapters]] object which serves as a per-journal collection of bound event adapters. @@ -319,14 +315,13 @@ class Persistence(val system: ExtendedActorSystem) extends Extension { * INTERNAL API * Looks up [[pekko.persistence.journal.EventAdapters]] by journal plugin's ActorRef. */ - private[pekko] final def adaptersFor(journalPluginActor: ActorRef): EventAdapters = { + private[pekko] final def adaptersFor(journalPluginActor: ActorRef): EventAdapters = pluginExtensionId.get().values.collectFirst { case ext if ext(system).actor == journalPluginActor => ext(system).adapters } match { case Some(adapters) => adapters case _ => IdentityEventAdapters } - } /** * INTERNAL API diff --git a/persistence/src/main/scala/org/apache/pekko/persistence/Persistent.scala b/persistence/src/main/scala/org/apache/pekko/persistence/Persistent.scala index 76fbfd3a1ab..4e9cec29cf4 100644 --- a/persistence/src/main/scala/org/apache/pekko/persistence/Persistent.scala +++ b/persistence/src/main/scala/org/apache/pekko/persistence/Persistent.scala @@ -214,9 +214,8 @@ private[persistence] final case class PersistentImpl( if (this.timestamp == newTimestamp) this else copy(timestamp = newTimestamp) - override def withMetadata(metadata: Any): PersistentRepr = { + override def withMetadata(metadata: Any): PersistentRepr = copy(metadata = Some(metadata)) - } def update(sequenceNr: Long, persistenceId: String, deleted: Boolean, sender: ActorRef, writerUuid: String) = copy( @@ -248,7 +247,6 @@ private[persistence] final case class PersistentImpl( case _ => false } - override def toString: String = { + override def toString: String = s"PersistentRepr($persistenceId,$sequenceNr,$writerUuid,$timestamp,$metadata)" - } } diff --git a/persistence/src/main/scala/org/apache/pekko/persistence/PersistentActor.scala b/persistence/src/main/scala/org/apache/pekko/persistence/PersistentActor.scala index 46b230fbd3c..e6936d834d6 100644 --- a/persistence/src/main/scala/org/apache/pekko/persistence/PersistentActor.scala +++ b/persistence/src/main/scala/org/apache/pekko/persistence/PersistentActor.scala @@ -200,9 +200,8 @@ trait PersistentActor extends Eventsourced with PersistenceIdentity { * @param event event to be persisted * @param handler handler for each persisted `event` */ - def persist[A](event: A)(handler: A => Unit): Unit = { + def persist[A](event: A)(handler: A => Unit): Unit = internalPersist(event)(handler) - } /** * Asynchronously persists `events` in specified order. This is equivalent to calling @@ -212,9 +211,8 @@ trait PersistentActor extends Eventsourced with PersistenceIdentity { * @param events events to be persisted * @param handler handler for each persisted `events` */ - def persistAll[A](events: immutable.Seq[A])(handler: A => Unit): Unit = { + def persistAll[A](events: immutable.Seq[A])(handler: A => Unit): Unit = internalPersistAll(events)(handler) - } /** * Asynchronously persists `event`. On successful persistence, `handler` is called with the @@ -239,9 +237,8 @@ trait PersistentActor extends Eventsourced with PersistenceIdentity { * @param event event to be persisted * @param handler handler for each persisted `event` */ - def persistAsync[A](event: A)(handler: A => Unit): Unit = { + def persistAsync[A](event: A)(handler: A => Unit): Unit = internalPersistAsync(event)(handler) - } /** * Asynchronously persists `events` in specified order. This is equivalent to calling @@ -251,9 +248,8 @@ trait PersistentActor extends Eventsourced with PersistenceIdentity { * @param events events to be persisted * @param handler handler for each persisted `events` */ - def persistAllAsync[A](events: immutable.Seq[A])(handler: A => Unit): Unit = { + def persistAllAsync[A](events: immutable.Seq[A])(handler: A => Unit): Unit = internalPersistAllAsync(events)(handler) - } /** * Defer the handler execution until all pending handlers have been executed. @@ -272,9 +268,8 @@ trait PersistentActor extends Eventsourced with PersistenceIdentity { * @param event event to be handled in the future, when preceding persist operations have been processes * @param handler handler for the given `event` */ - def deferAsync[A](event: A)(handler: A => Unit): Unit = { + def deferAsync[A](event: A)(handler: A => Unit): Unit = internalDeferAsync(event)(handler) - } /** * Defer the handler execution until all pending handlers have been executed. It is guaranteed that no new commands @@ -294,9 +289,8 @@ trait PersistentActor extends Eventsourced with PersistenceIdentity { * @param event event to be handled in the future, when preceding persist operations have been processes * @param handler handler for the given `event` */ - def defer[A](event: A)(handler: A => Unit): Unit = { + def defer[A](event: A)(handler: A => Unit): Unit = internalDefer(event)(handler) - } } /** @@ -476,9 +470,8 @@ abstract class AbstractPersistentActor extends AbstractActor with AbstractPersis * @param event event to be handled in the future, when preceding persist operations have been processes * @param handler handler for the given `event` */ - def defer[A](event: A)(handler: Procedure[A]): Unit = { + def defer[A](event: A)(handler: Procedure[A]): Unit = internalDefer(event)(event => handler(event)) - } } diff --git a/persistence/src/main/scala/org/apache/pekko/persistence/SnapshotProtocol.scala b/persistence/src/main/scala/org/apache/pekko/persistence/SnapshotProtocol.scala index fe0ebd350ae..377d5789c28 100644 --- a/persistence/src/main/scala/org/apache/pekko/persistence/SnapshotProtocol.scala +++ b/persistence/src/main/scala/org/apache/pekko/persistence/SnapshotProtocol.scala @@ -31,13 +31,11 @@ final class SnapshotMetadata( extends Product3[String, Long, Long] with Serializable { - def this(persistenceId: String, sequenceNr: Long, timestamp: Long) = { + def this(persistenceId: String, sequenceNr: Long, timestamp: Long) = this(persistenceId, sequenceNr, timestamp, None) - } - private[pekko] def this(persistenceId: String, sequenceNr: Long, meta: Option[Any]) = { + private[pekko] def this(persistenceId: String, sequenceNr: Long, meta: Option[Any]) = this(persistenceId, sequenceNr, 0L, meta) - } def withMetadata(metadata: Any): SnapshotMetadata = new SnapshotMetadata(persistenceId, sequenceNr, timestamp, Some(metadata)) diff --git a/persistence/src/main/scala/org/apache/pekko/persistence/Snapshotter.scala b/persistence/src/main/scala/org/apache/pekko/persistence/Snapshotter.scala index a52713a25ed..56222cc5ecb 100644 --- a/persistence/src/main/scala/org/apache/pekko/persistence/Snapshotter.scala +++ b/persistence/src/main/scala/org/apache/pekko/persistence/Snapshotter.scala @@ -48,9 +48,8 @@ trait Snapshotter extends Actor { * The [[pekko.persistence.PersistentActor PersistentActor]] will be notified about the success or failure of this * via an [[pekko.persistence.SaveSnapshotSuccess SaveSnapshotSuccess]] or [[pekko.persistence.SaveSnapshotFailure SaveSnapshotFailure]] message. */ - def saveSnapshot(snapshot: Any): Unit = { + def saveSnapshot(snapshot: Any): Unit = snapshotStore ! SaveSnapshot(SnapshotMetadata(snapshotterId, snapshotSequenceNr), snapshot) - } /** * Deletes the snapshot identified by `sequenceNr`. @@ -58,9 +57,8 @@ trait Snapshotter extends Actor { * The [[pekko.persistence.PersistentActor PersistentActor]] will be notified about the status of the deletion * via an [[pekko.persistence.DeleteSnapshotSuccess DeleteSnapshotSuccess]] or [[pekko.persistence.DeleteSnapshotFailure DeleteSnapshotFailure]] message. */ - def deleteSnapshot(sequenceNr: Long): Unit = { + def deleteSnapshot(sequenceNr: Long): Unit = snapshotStore ! DeleteSnapshot(SnapshotMetadata(snapshotterId, sequenceNr)) - } /** * Deletes all snapshots matching `criteria`. @@ -68,8 +66,7 @@ trait Snapshotter extends Actor { * The [[pekko.persistence.PersistentActor PersistentActor]] will be notified about the status of the deletion * via an [[pekko.persistence.DeleteSnapshotsSuccess DeleteSnapshotsSuccess]] or [[pekko.persistence.DeleteSnapshotsFailure DeleteSnapshotsFailure]] message. */ - def deleteSnapshots(criteria: SnapshotSelectionCriteria): Unit = { + def deleteSnapshots(criteria: SnapshotSelectionCriteria): Unit = snapshotStore ! DeleteSnapshots(snapshotterId, criteria) - } } diff --git a/persistence/src/main/scala/org/apache/pekko/persistence/fsm/PersistentFSM.scala b/persistence/src/main/scala/org/apache/pekko/persistence/fsm/PersistentFSM.scala index 2ea3a3081d0..2c0eed7848e 100644 --- a/persistence/src/main/scala/org/apache/pekko/persistence/fsm/PersistentFSM.scala +++ b/persistence/src/main/scala/org/apache/pekko/persistence/fsm/PersistentFSM.scala @@ -119,16 +119,14 @@ trait PersistentFSM[S <: FSMState, D, E] extends PersistentActor with Persistent /** * Save the current state as a snapshot */ - final def saveStateSnapshot(): Unit = { + final def saveStateSnapshot(): Unit = saveSnapshot(PersistentFSMSnapshot(stateName.identifier, stateData, currentStateTimeout)) - } /** * After recovery events are handled as in usual FSM actor */ - override def receiveCommand: Receive = { + override def receiveCommand: Receive = super[PersistentFSMBase].receive - } /** * Discover the latest recorded state @@ -406,9 +404,8 @@ object PersistentFSM { replies: List[Any] = replies, notifies: Boolean = notifies, domainEvents: Seq[E] = domainEvents, - afterTransitionDo: D => Unit = afterTransitionDo): State[S, D, E] = { + afterTransitionDo: D => Unit = afterTransitionDo): State[S, D, E] = State(stateName, stateData, timeout, stopReason, replies, domainEvents, afterTransitionDo)(notifies) - } /** * Modify state transition descriptor to include a state timeout for the @@ -439,44 +436,38 @@ object PersistentFSM { * * @return this state transition descriptor */ - def replying(replyValue: Any): State[S, D, E] = { + def replying(replyValue: Any): State[S, D, E] = copy0(replies = replyValue :: replies) - } @InternalApi @deprecated( "Internal API easily to be confused with regular FSM's using. Use regular events (`applying`). Internally, `copy` can be used instead.", "Akka 2.5.5") - private[pekko] def using(@deprecatedName(Symbol("nextStateDate")) nextStateData: D): State[S, D, E] = { + private[pekko] def using(@deprecatedName(Symbol("nextStateDate")) nextStateData: D): State[S, D, E] = copy0(stateData = nextStateData) - } /** * INTERNAL API. */ @InternalApi - private[pekko] def withStopReason(reason: Reason): State[S, D, E] = { + private[pekko] def withStopReason(reason: Reason): State[S, D, E] = copy0(stopReason = Some(reason)) - } @InternalApi - private[pekko] def withNotification(notifies: Boolean): State[S, D, E] = { + private[pekko] def withNotification(notifies: Boolean): State[S, D, E] = copy0(notifies = notifies) - } /** * Specify domain events to be applied when transitioning to the new state. */ - @varargs def applying(events: E*): State[S, D, E] = { + @varargs def applying(events: E*): State[S, D, E] = copy0(domainEvents = domainEvents ++ events) - } /** * Register a handler to be triggered after the state has been persisted successfully */ - def andThen(handler: D => Unit): State[S, D, E] = { + def andThen(handler: D => Unit): State[S, D, E] = copy0(afterTransitionDo = handler) - } } /** @@ -530,11 +521,10 @@ abstract class AbstractPersistentFSM[S <: FSMState, D, E] override def receive: Receive = super.receive @throws(classOf[Exception]) - override def postStop(): Unit = { + override def postStop(): Unit = // Make sure any ambiguity is resolved on the 'scala side' so this doesn't have to // happen on the 'java side' super.postStop() - } } /** diff --git a/persistence/src/main/scala/org/apache/pekko/persistence/fsm/PersistentFSMBase.scala b/persistence/src/main/scala/org/apache/pekko/persistence/fsm/PersistentFSMBase.scala index dd280a6ade1..1dba58cae9b 100644 --- a/persistence/src/main/scala/org/apache/pekko/persistence/fsm/PersistentFSMBase.scala +++ b/persistence/src/main/scala/org/apache/pekko/persistence/fsm/PersistentFSMBase.scala @@ -365,7 +365,7 @@ trait PersistentFSMBase[S, D, E] extends Actor with Listeners with ActorLogging implicit final def total2pf(transitionHandler: (S, S) => Unit): TransitionHandler = new TransitionHandler { def isDefinedAt(in: (S, S)) = true - def apply(in: (S, S)): Unit = { transitionHandler(in._1, in._2) } + def apply(in: (S, S)): Unit = transitionHandler(in._1, in._2) } /** @@ -452,7 +452,7 @@ trait PersistentFSMBase[S, D, E] extends Actor with Listeners with ActorLogging private val stateFunctions = mutable.Map[S, StateFunction]() private val stateTimeouts = mutable.Map[S, Timeout]() - private def register(name: S, function: StateFunction, timeout: Timeout): Unit = { + private def register(name: S, function: StateFunction, timeout: Timeout): Unit = if (stateFunctions contains name) { stateFunctions(name) = stateFunctions(name).orElse(function) stateTimeouts(name) = timeout.orElse(stateTimeouts(name)) @@ -460,7 +460,6 @@ trait PersistentFSMBase[S, D, E] extends Actor with Listeners with ActorLogging stateFunctions(name) = function stateTimeouts(name) = timeout } - } /* * unhandled event handler @@ -483,7 +482,7 @@ trait PersistentFSMBase[S, D, E] extends Actor with Listeners with ActorLogging private var transitionEvent: List[TransitionHandler] = Nil private def handleTransition(prev: S, next: S): Unit = { val tuple = (prev, next) - for (te <- transitionEvent) { if (te.isDefinedAt(tuple)) te(tuple) } + for (te <- transitionEvent) if (te.isDefinedAt(tuple)) te(tuple) } /* @@ -547,7 +546,7 @@ trait PersistentFSMBase[S, D, E] extends Actor with Listeners with ActorLogging applyState(nextState) } - private[pekko] def applyState(nextState: State): Unit = { + private[pekko] def applyState(nextState: State): Unit = nextState.stopReason match { case None => makeTransition(nextState) case _ => @@ -557,9 +556,8 @@ trait PersistentFSMBase[S, D, E] extends Actor with Listeners with ActorLogging terminate(nextState) context.stop(self) } - } - private[pekko] def makeTransition(nextState: State): Unit = { + private[pekko] def makeTransition(nextState: State): Unit = if (!stateFunctions.contains(nextState.stateName)) { terminate(stay().withStopReason(Failure("Next state %s does not exist".format(nextState.stateName)))) } else { @@ -588,7 +586,6 @@ trait PersistentFSMBase[S, D, E] extends Actor with Listeners with ActorLogging } } } - } /** * Call `onTermination` hook; if you want to retain this behavior when @@ -608,7 +605,7 @@ trait PersistentFSMBase[S, D, E] extends Actor with Listeners with ActorLogging super.postStop() } - private def terminate(nextState: State): Unit = { + private def terminate(nextState: State): Unit = if (currentState.stopReason.isEmpty) { val reason = nextState.stopReason.get logTermination(reason) @@ -620,7 +617,6 @@ trait PersistentFSMBase[S, D, E] extends Actor with Listeners with ActorLogging if (terminateEvent.isDefinedAt(stopEvent)) terminateEvent(stopEvent) } - } /** * By default [[PersistentFSM.Failure]] is logged at error level and other reason diff --git a/persistence/src/main/scala/org/apache/pekko/persistence/journal/EventAdapters.scala b/persistence/src/main/scala/org/apache/pekko/persistence/journal/EventAdapters.scala index abf98ca69d0..f363390ba49 100644 --- a/persistence/src/main/scala/org/apache/pekko/persistence/journal/EventAdapters.scala +++ b/persistence/src/main/scala/org/apache/pekko/persistence/journal/EventAdapters.scala @@ -43,7 +43,7 @@ class EventAdapters( * * Falls back to [[IdentityEventAdapter]] if no adapter was defined for the given class. */ - def get(clazz: Class[_]): EventAdapter = { + def get(clazz: Class[_]): EventAdapter = map.get(clazz) match { case null => // bindings are ordered from most specific to least specific val value = bindings.filter { @@ -60,7 +60,6 @@ class EventAdapters( } case value => value } - } override def toString = s"${getClass.getName}($map, $bindings)" diff --git a/persistence/src/main/scala/org/apache/pekko/persistence/journal/PersistencePluginProxy.scala b/persistence/src/main/scala/org/apache/pekko/persistence/journal/PersistencePluginProxy.scala index f6e0bce843e..f684c7321c8 100644 --- a/persistence/src/main/scala/org/apache/pekko/persistence/journal/PersistencePluginProxy.scala +++ b/persistence/src/main/scala/org/apache/pekko/persistence/journal/PersistencePluginProxy.scala @@ -102,7 +102,7 @@ final class PersistencePluginProxy(config: Config) extends Actor with Stash with } private val startTarget: Boolean = config.getBoolean(s"start-target-${pluginType.qualifier}") - override def preStart(): Unit = { + override def preStart(): Unit = if (startTarget) { val target = pluginType match { case Journal => @@ -128,7 +128,6 @@ final class PersistencePluginProxy(config: Config) extends Actor with Stash with context.system.scheduler.scheduleOnce(initTimeout, self, InitTimeout)(context.dispatcher) } - } private val selfAddress: Address = context.system.asInstanceOf[ExtendedActorSystem].provider.getDefaultAddress diff --git a/persistence/src/main/scala/org/apache/pekko/persistence/journal/Tagged.scala b/persistence/src/main/scala/org/apache/pekko/persistence/journal/Tagged.scala index e269684b88f..f600cfa85bf 100644 --- a/persistence/src/main/scala/org/apache/pekko/persistence/journal/Tagged.scala +++ b/persistence/src/main/scala/org/apache/pekko/persistence/journal/Tagged.scala @@ -31,7 +31,6 @@ case class Tagged(payload: Any, tags: Set[String]) { /** * Java API */ - def this(payload: Any, tags: java.util.Set[String]) = { + def this(payload: Any, tags: java.util.Set[String]) = this(payload, tags.asScala.toSet) - } } diff --git a/persistence/src/main/scala/org/apache/pekko/persistence/journal/inmem/InmemJournal.scala b/persistence/src/main/scala/org/apache/pekko/persistence/journal/inmem/InmemJournal.scala index ec0c5352d5d..99e022a793c 100644 --- a/persistence/src/main/scala/org/apache/pekko/persistence/journal/inmem/InmemJournal.scala +++ b/persistence/src/main/scala/org/apache/pekko/persistence/journal/inmem/InmemJournal.scala @@ -80,7 +80,7 @@ object InmemJournal { private val eventStream = context.system.eventStream - override def asyncWriteMessages(messages: immutable.Seq[AtomicWrite]): Future[immutable.Seq[Try[Unit]]] = { + override def asyncWriteMessages(messages: immutable.Seq[AtomicWrite]): Future[immutable.Seq[Try[Unit]]] = try { for (w <- messages; p <- w.payload) { val payload = p.payload match { @@ -97,11 +97,9 @@ object InmemJournal { // serialization problem Future.failed(e) } - } - override def asyncReadHighestSequenceNr(persistenceId: String, fromSequenceNr: Long): Future[Long] = { + override def asyncReadHighestSequenceNr(persistenceId: String, fromSequenceNr: Long): Future[Long] = Future.successful(highestSequenceNr(persistenceId)) - } override def asyncReplayMessages(persistenceId: String, fromSequenceNr: Long, toSequenceNr: Long, max: Long)( recoveryCallback: PersistentRepr => Unit): Future[Unit] = { @@ -137,7 +135,7 @@ object InmemJournal { } - private def verifySerialization(event: Any): Unit = { + private def verifySerialization(event: Any): Unit = if (testSerialization) { val eventAnyRef = event.asInstanceOf[AnyRef] val bytes = serialization.serialize(eventAnyRef).get @@ -145,7 +143,6 @@ object InmemJournal { val manifest = Serializers.manifestFor(serializer, eventAnyRef) serialization.deserialize(bytes, serializer.identifier, manifest).get } - } } /** @@ -182,9 +179,8 @@ object InmemJournal { case None => Nil } - def highestSequenceNr(pid: String): Long = { + def highestSequenceNr(pid: String): Long = highestSequenceNumbers.getOrElse(pid, 0L) - } private def safeLongToInt(l: Long): Int = if (Int.MaxValue < l) Int.MaxValue else l.toInt diff --git a/persistence/src/main/scala/org/apache/pekko/persistence/journal/leveldb/LeveldbCompaction.scala b/persistence/src/main/scala/org/apache/pekko/persistence/journal/leveldb/LeveldbCompaction.scala index b21f9205440..4dd300de50f 100644 --- a/persistence/src/main/scala/org/apache/pekko/persistence/journal/leveldb/LeveldbCompaction.scala +++ b/persistence/src/main/scala/org/apache/pekko/persistence/journal/leveldb/LeveldbCompaction.scala @@ -36,7 +36,7 @@ private[persistence] trait LeveldbCompaction extends Actor with ActorLogging wit tryCompactOnDelete(persistenceId, toSeqNr) } - private def tryCompactOnDelete(persistenceId: String, toSeqNr: Long): Unit = { + private def tryCompactOnDelete(persistenceId: String, toSeqNr: Long): Unit = if (mustCompact(persistenceId, toSeqNr)) { val limit = compactionLimit(persistenceId, toSeqNr) log.info("Starting compaction for persistence id [{}] up to sequence number [{}]", persistenceId, limit) @@ -48,7 +48,6 @@ private[persistence] trait LeveldbCompaction extends Actor with ActorLogging wit } else { log.debug("No compaction required yet for persistence id [{}] up to sequence number [{}]", persistenceId, toSeqNr) } - } } /** @@ -75,9 +74,8 @@ private[persistence] trait CompactionSegmentManagement { def compactionIntervals: Map[String, Long] - def updateCompactionSegment(persistenceId: String, compactionSegment: Long): Unit = { + def updateCompactionSegment(persistenceId: String, compactionSegment: Long): Unit = latestCompactionSegments += persistenceId -> compactionSegment - } def compactionLimit(persistenceId: String, toSeqNr: Long): Long = { val interval = compactionInterval(persistenceId) diff --git a/persistence/src/main/scala/org/apache/pekko/persistence/journal/leveldb/LeveldbIdMapping.scala b/persistence/src/main/scala/org/apache/pekko/persistence/journal/leveldb/LeveldbIdMapping.scala index 99178a29825..6890c606c74 100644 --- a/persistence/src/main/scala/org/apache/pekko/persistence/journal/leveldb/LeveldbIdMapping.scala +++ b/persistence/src/main/scala/org/apache/pekko/persistence/journal/leveldb/LeveldbIdMapping.scala @@ -60,7 +60,7 @@ private[persistence] trait LeveldbIdMapping extends Actor { this: LeveldbStore = readIdMap(Map.empty, iter) } - private def readIdMap(pathMap: Map[String, Int], iter: DBIterator): Map[String, Int] = { + private def readIdMap(pathMap: Map[String, Int], iter: DBIterator): Map[String, Int] = if (!iter.hasNext) pathMap else { val nextEntry = iter.next() @@ -71,7 +71,6 @@ private[persistence] trait LeveldbIdMapping extends Actor { this: LeveldbStore = readIdMap(pathMap + (nextVal -> nextKey.mappingId), iter) } } - } private def writeIdMapping(id: String, numericId: Int): Int = { idMap = idMap + (id -> numericId) diff --git a/persistence/src/main/scala/org/apache/pekko/persistence/journal/leveldb/LeveldbJournal.scala b/persistence/src/main/scala/org/apache/pekko/persistence/journal/leveldb/LeveldbJournal.scala index 1e7cb66947d..0ad92ef4eb1 100644 --- a/persistence/src/main/scala/org/apache/pekko/persistence/journal/leveldb/LeveldbJournal.scala +++ b/persistence/src/main/scala/org/apache/pekko/persistence/journal/leveldb/LeveldbJournal.scala @@ -177,7 +177,7 @@ object SharedLeveldbJournal { * * For testing only. */ - def configToEnableJavaSerializationForTest: Config = { + def configToEnableJavaSerializationForTest: Config = ConfigFactory.parseString(s""" pekko.actor.serialization-bindings { "org.apache.pekko.persistence.journal.AsyncWriteTarget$$WriteMessages" = java-test @@ -190,5 +190,4 @@ object SharedLeveldbJournal { "scala.collection.immutable.Vector" = java-test } """) - } } diff --git a/persistence/src/main/scala/org/apache/pekko/persistence/journal/leveldb/LeveldbRecovery.scala b/persistence/src/main/scala/org/apache/pekko/persistence/journal/leveldb/LeveldbRecovery.scala index 2221eef2024..ceb81ee098a 100644 --- a/persistence/src/main/scala/org/apache/pekko/persistence/journal/leveldb/LeveldbRecovery.scala +++ b/persistence/src/main/scala/org/apache/pekko/persistence/journal/leveldb/LeveldbRecovery.scala @@ -47,7 +47,7 @@ private[persistence] trait LeveldbRecovery extends AsyncRecovery { this: Leveldb def replayMessages(persistenceId: Int, fromSequenceNr: Long, toSequenceNr: Long, max: Long)( replayCallback: PersistentRepr => Unit): Unit = { @scala.annotation.tailrec - def go(iter: DBIterator, key: Key, ctr: Long, replayCallback: PersistentRepr => Unit): Unit = { + def go(iter: DBIterator, key: Key, ctr: Long, replayCallback: PersistentRepr => Unit): Unit = if (iter.hasNext) { val nextEntry = iter.next() val nextKey = keyFromBytes(nextEntry.getKey) @@ -65,11 +65,10 @@ private[persistence] trait LeveldbRecovery extends AsyncRecovery { this: Leveldb } } } - } // need to have this to be able to read journal created with 2.3.x, which // supported deletion of individual events - def deletion(iter: DBIterator, key: Key): Boolean = { + def deletion(iter: DBIterator, key: Key): Boolean = if (iter.hasNext) { val nextEntry = iter.peekNext() val nextKey = keyFromBytes(nextEntry.getKey) @@ -79,7 +78,6 @@ private[persistence] trait LeveldbRecovery extends AsyncRecovery { this: Leveldb true } else false } else false - } withIterator { iter => val startKey = Key(persistenceId, if (fromSequenceNr < 1L) 1L else fromSequenceNr, 0) @@ -99,7 +97,7 @@ private[persistence] trait LeveldbRecovery extends AsyncRecovery { this: Leveldb replayCallback: ReplayedTaggedMessage => Unit): Unit = { @scala.annotation.tailrec - def go(iter: DBIterator, key: Key, ctr: Long, replayCallback: ReplayedTaggedMessage => Unit): Unit = { + def go(iter: DBIterator, key: Key, ctr: Long, replayCallback: ReplayedTaggedMessage => Unit): Unit = if (iter.hasNext) { val nextEntry = iter.next() val nextKey = keyFromBytes(nextEntry.getKey) @@ -113,7 +111,6 @@ private[persistence] trait LeveldbRecovery extends AsyncRecovery { this: Leveldb } } } - } withIterator { iter => // fromSequenceNr is exclusive, i.e. start with +1 @@ -125,13 +122,12 @@ private[persistence] trait LeveldbRecovery extends AsyncRecovery { this: Leveldb def readHighestSequenceNr(persistenceId: Int) = { val ro = leveldbSnapshot() - try { + try leveldb.get(keyToBytes(counterKey(persistenceId)), ro) match { case null => 0L case bytes => counterFromBytes(bytes) } - } finally { + finally ro.snapshot().close() - } } } diff --git a/persistence/src/main/scala/org/apache/pekko/persistence/journal/leveldb/LeveldbStore.scala b/persistence/src/main/scala/org/apache/pekko/persistence/journal/leveldb/LeveldbStore.scala index 79fda7ff3c0..b66fc288f00 100644 --- a/persistence/src/main/scala/org/apache/pekko/persistence/journal/leveldb/LeveldbStore.scala +++ b/persistence/src/main/scala/org/apache/pekko/persistence/journal/leveldb/LeveldbStore.scala @@ -35,9 +35,8 @@ import pekko.util.ccompat.JavaConverters._ private[persistence] object LeveldbStore { val emptyConfig = ConfigFactory.empty() - def toCompactionIntervalMap(obj: ConfigObject): Map[String, Long] = { + def toCompactionIntervalMap(obj: ConfigObject): Map[String, Long] = obj.unwrapped().asScala.map(entry => (entry._1, java.lang.Long.parseLong(entry._2.toString))).toMap - } } /** @@ -155,9 +154,9 @@ private[persistence] trait LeveldbStore def withIterator[R](body: DBIterator => R): R = { val ro = leveldbSnapshot() val iterator = leveldb.iterator(ro) - try { + try body(iterator) - } finally { + finally { iterator.close() ro.snapshot().close() } @@ -169,9 +168,8 @@ private[persistence] trait LeveldbStore val r = body(batch) leveldb.write(batch, leveldbWriteOptions) r - } finally { + } finally batch.close() - } } def persistentToBytes(p: PersistentRepr): Array[Byte] = serialization.serialize(p).get @@ -261,11 +259,10 @@ private[persistence] trait LeveldbStore tagSubscribers(tag).foreach(_ ! changed) } - override protected def newPersistenceIdAdded(id: String): Unit = { + override protected def newPersistenceIdAdded(id: String): Unit = if (hasAllPersistenceIdsSubscribers && !id.startsWith(tagPersistenceIdPrefix)) { val added = LeveldbJournal.PersistenceIdAdded(id) allPersistenceIdsSubscribers.foreach(_ ! added) } - } } diff --git a/persistence/src/main/scala/org/apache/pekko/persistence/serialization/MessageSerializer.scala b/persistence/src/main/scala/org/apache/pekko/persistence/serialization/MessageSerializer.scala index 8e43421beab..52df5058016 100644 --- a/persistence/src/main/scala/org/apache/pekko/persistence/serialization/MessageSerializer.scala +++ b/persistence/src/main/scala/org/apache/pekko/persistence/serialization/MessageSerializer.scala @@ -138,7 +138,7 @@ class MessageSerializer(val system: ExtendedActorSystem) extends BaseSerializer } @nowarn("msg=deprecated") - def stateChange(persistentStateChange: mf.PersistentStateChangeEvent): StateChangeEvent = { + def stateChange(persistentStateChange: mf.PersistentStateChangeEvent): StateChangeEvent = StateChangeEvent( persistentStateChange.getStateIdentifier, // timeout field is deprecated, left for backward compatibility. timeoutNanos is used instead. @@ -147,16 +147,14 @@ class MessageSerializer(val system: ExtendedActorSystem) extends BaseSerializer else if (persistentStateChange.hasTimeout) Some(Duration(persistentStateChange.getTimeout).asInstanceOf[duration.FiniteDuration]) else None) - } - def persistentFSMSnapshot(persistentFSMSnapshot: mf.PersistentFSMSnapshot): PersistentFSMSnapshot[Any] = { + def persistentFSMSnapshot(persistentFSMSnapshot: mf.PersistentFSMSnapshot): PersistentFSMSnapshot[Any] = PersistentFSMSnapshot( persistentFSMSnapshot.getStateIdentifier, payload(persistentFSMSnapshot.getData), if (persistentFSMSnapshot.hasTimeoutNanos) Some(Duration.fromNanos(persistentFSMSnapshot.getTimeoutNanos)) else None) - } private def atomicWriteBuilder(a: AtomicWrite) = { val builder = mf.AtomicWrite.newBuilder diff --git a/persistence/src/main/scala/org/apache/pekko/persistence/serialization/SnapshotSerializer.scala b/persistence/src/main/scala/org/apache/pekko/persistence/serialization/SnapshotSerializer.scala index 15691025f20..706e82895a0 100644 --- a/persistence/src/main/scala/org/apache/pekko/persistence/serialization/SnapshotSerializer.scala +++ b/persistence/src/main/scala/org/apache/pekko/persistence/serialization/SnapshotSerializer.scala @@ -108,7 +108,7 @@ class SnapshotSerializer(val system: ExtendedActorSystem) extends BaseSerializer // when writing the data, we want to allow the serialized data to // support Akka and Pekko serializers as required by configuration - private def migrateManifestIfNecessary(manifest: String): String = { + private def migrateManifestIfNecessary(manifest: String): String = migrationStrategy match { case NoMigration => manifest case Pekko => @@ -124,10 +124,9 @@ class SnapshotSerializer(val system: ExtendedActorSystem) extends BaseSerializer manifest } } - } // when reading the data, we want to force use of the Pekko serializer - private def migrateManifestToPekkoIfNecessary(manifest: String): String = { + private def migrateManifestToPekkoIfNecessary(manifest: String): String = migrationStrategy match { case NoMigration => manifest case _ => @@ -137,7 +136,6 @@ class SnapshotSerializer(val system: ExtendedActorSystem) extends BaseSerializer manifest } } - } private def snapshotToBinary(snapshot: AnyRef): Array[Byte] = { def serialize() = { diff --git a/persistence/src/main/scala/org/apache/pekko/persistence/snapshot/local/LocalSnapshotStore.scala b/persistence/src/main/scala/org/apache/pekko/persistence/snapshot/local/LocalSnapshotStore.scala index b8e1d7a52f7..dab206b80f7 100644 --- a/persistence/src/main/scala/org/apache/pekko/persistence/snapshot/local/LocalSnapshotStore.scala +++ b/persistence/src/main/scala/org/apache/pekko/persistence/snapshot/local/LocalSnapshotStore.scala @@ -106,9 +106,8 @@ private[persistence] class LocalSnapshotStore(config: Config) extends SnapshotSt case _: DeleteSnapshotsFailure => // ignore } - private def snapshotFiles(metadata: SnapshotMetadata): immutable.Seq[File] = { + private def snapshotFiles(metadata: SnapshotMetadata): immutable.Seq[File] = snapshotDir().listFiles(new SnapshotSeqNrFilenameFilter(metadata)).toVector - } @scala.annotation.tailrec private def load(metadata: immutable.Seq[SnapshotMetadata]): Try[Option[SelectedSnapshot]] = @@ -136,9 +135,8 @@ private[persistence] class LocalSnapshotStore(config: Config) extends SnapshotSt protected def deserialize(inputStream: InputStream): Snapshot = serializationExtension.deserialize(streamToBytes(inputStream), classOf[Snapshot]).get - protected def serialize(outputStream: OutputStream, snapshot: Snapshot): Unit = { + protected def serialize(outputStream: OutputStream, snapshot: Snapshot): Unit = outputStream.write(serializationExtension.serialize(snapshot).get) - } protected def withOutputStream(metadata: SnapshotMetadata)(p: (OutputStream) => Unit): File = { val tmpFile = snapshotFileForWrite(metadata, extension = "tmp") @@ -150,11 +148,10 @@ private[persistence] class LocalSnapshotStore(config: Config) extends SnapshotSt withStream(new BufferedInputStream(Files.newInputStream(snapshotFileForWrite(metadata).toPath())), p) private def withStream[A <: Closeable, B](stream: A, p: A => B): B = - try { + try p(stream) - } finally { + finally stream.close() - } /** Only by persistenceId and sequenceNr, timestamp is informational - accommodates for 2.13.x series files */ protected def snapshotFileForWrite(metadata: SnapshotMetadata, extension: String = ""): File = @@ -209,10 +206,9 @@ private[persistence] class LocalSnapshotStore(config: Config) extends SnapshotSt } private final class SnapshotSeqNrFilenameFilter(md: SnapshotMetadata) extends FilenameFilter { - private final def matches(pid: String, snr: String, tms: String): Boolean = { + private final def matches(pid: String, snr: String, tms: String): Boolean = pid.equals(URLEncoder.encode(md.persistenceId, defaultSystemEncoding)) && Try(snr.toLong == md.sequenceNr && (md.timestamp == 0L || tms.toLong == md.timestamp)).getOrElse(false) - } def accept(dir: File, name: String): Boolean = name match { diff --git a/persistence/src/main/scala/org/apache/pekko/persistence/state/DurableStateStoreRegistry.scala b/persistence/src/main/scala/org/apache/pekko/persistence/state/DurableStateStoreRegistry.scala index ac1a7ec4978..8c4634ccc33 100644 --- a/persistence/src/main/scala/org/apache/pekko/persistence/state/DurableStateStoreRegistry.scala +++ b/persistence/src/main/scala/org/apache/pekko/persistence/state/DurableStateStoreRegistry.scala @@ -79,17 +79,15 @@ class DurableStateStoreRegistry(system: ExtendedActorSystem) } /** Check for default or missing identity. */ - private def isEmpty(text: String) = { + private def isEmpty(text: String) = text == null || text.isEmpty - } /** * Scala API: Returns the [[pekko.persistence.state.scaladsl.DurableStateStore]] specified by the given * configuration entry. */ - final def durableStateStoreFor[T <: scaladsl.DurableStateStore[_]](pluginId: String): T = { + final def durableStateStoreFor[T <: scaladsl.DurableStateStore[_]](pluginId: String): T = pluginFor(pluginIdOrDefault(pluginId), pluginConfig(pluginId)).scaladslPlugin.asInstanceOf[T] - } /** * Java API: Returns the [[pekko.persistence.state.javadsl.DurableStateStore]] specified by the given @@ -97,8 +95,7 @@ class DurableStateStoreRegistry(system: ExtendedActorSystem) */ final def getDurableStateStoreFor[T <: javadsl.DurableStateStore[_]]( @unused clazz: Class[T], // FIXME generic Class could be problematic in Java - pluginId: String): T = { + pluginId: String): T = pluginFor(pluginIdOrDefault(pluginId), pluginConfig(pluginId)).javadslPlugin.asInstanceOf[T] - } } diff --git a/persistence/src/test/scala/org/apache/pekko/persistence/AtLeastOnceDeliveryCrashSpec.scala b/persistence/src/test/scala/org/apache/pekko/persistence/AtLeastOnceDeliveryCrashSpec.scala index 7dbd9fd1c3b..e0b4041d01a 100644 --- a/persistence/src/test/scala/org/apache/pekko/persistence/AtLeastOnceDeliveryCrashSpec.scala +++ b/persistence/src/test/scala/org/apache/pekko/persistence/AtLeastOnceDeliveryCrashSpec.scala @@ -64,11 +64,10 @@ object AtLeastOnceDeliveryCrashSpec { } } - def send() = { + def send() = deliver(testProbe.path) { id => SendingMessage(id) } - } } } diff --git a/persistence/src/test/scala/org/apache/pekko/persistence/AtLeastOnceDeliverySpec.scala b/persistence/src/test/scala/org/apache/pekko/persistence/AtLeastOnceDeliverySpec.scala index ad2f108c813..adccbcacfe3 100644 --- a/persistence/src/test/scala/org/apache/pekko/persistence/AtLeastOnceDeliverySpec.scala +++ b/persistence/src/test/scala/org/apache/pekko/persistence/AtLeastOnceDeliverySpec.scala @@ -404,15 +404,12 @@ class AtLeastOnceDeliverySpec "C" -> system.actorOf(unreliableProps(3, dstC), "unreliable-c").path) val snd = system.actorOf(senderProps(probe.ref, name, 1000.millis, 5, 1000, destinations, async = true), name) val N = 100 - for (n <- 1 to N) { + for (n <- 1 to N) snd.tell(Req("a-" + n), probe.ref) - } - for (n <- 1 to N) { + for (n <- 1 to N) snd.tell(Req("b-" + n), probe.ref) - } - for (n <- 1 to N) { + for (n <- 1 to N) snd.tell(Req("c-" + n), probe.ref) - } val deliverWithin = 20.seconds probeA.receiveN(N, deliverWithin).collect { case a: Action => a.payload }.toSet should ===( (1 to N).map(n => "a-" + n).toSet) @@ -431,9 +428,8 @@ class AtLeastOnceDeliverySpec val snd = system.actorOf(senderProps(probe.ref, name, 2.seconds, 5, 2, destinations, async = true), name) val N = 10 - for (n <- 1 to N) { + for (n <- 1 to N) snd.tell(Req("a-" + n), probe.ref) - } // initially all odd messages should go through for (n <- 1 to N if n % 2 == 1) probeA.expectMsg(Action(n, s"a-$n")) @@ -442,12 +438,11 @@ class AtLeastOnceDeliverySpec // at each redelivery round, 2 (even) messages are sent, the first goes through // without throttling, at each round half of the messages would go through var toDeliver = (1 to N).filter(_ % 2 == 0).map(_.toLong).toSet - for (n <- 1 to N) { + for (n <- 1 to N) if (n % 2 == 0) { toDeliver -= probeA.expectMsgType[Action].id probeA.expectNoMessage(100.millis) } - } toDeliver should ===(Set.empty[Long]) } diff --git a/persistence/src/test/scala/org/apache/pekko/persistence/EndToEndEventAdapterSpec.scala b/persistence/src/test/scala/org/apache/pekko/persistence/EndToEndEventAdapterSpec.scala index 0babafe0526..31c0e466e4f 100644 --- a/persistence/src/test/scala/org/apache/pekko/persistence/EndToEndEventAdapterSpec.scala +++ b/persistence/src/test/scala/org/apache/pekko/persistence/EndToEndEventAdapterSpec.scala @@ -101,7 +101,7 @@ object EndToEndEventAdapterSpec { val persistIncoming: Receive = { case GetState => - state.reverse.foreach { sender() ! _ } + state.reverse.foreach(sender() ! _) case in => persist(in) { e => state ::= e @@ -129,13 +129,11 @@ class EndToEndEventAdapterSpec extends AnyWordSpecLike with Matchers with Before val storageLocations = List("pekko.persistence.journal.leveldb.dir").map(s => new File(journalConfig.getString(s))) - override protected def beforeAll(): Unit = { + override protected def beforeAll(): Unit = storageLocations.foreach(FileUtils.deleteDirectory) - } - override protected def afterAll(): Unit = { + override protected def afterAll(): Unit = storageLocations.foreach(FileUtils.deleteDirectory) - } val noAdaptersConfig = ConfigFactory.parseString("") diff --git a/persistence/src/test/scala/org/apache/pekko/persistence/EventAdapterSpec.scala b/persistence/src/test/scala/org/apache/pekko/persistence/EventAdapterSpec.scala index 100463f7fdf..c0bab51acfa 100644 --- a/persistence/src/test/scala/org/apache/pekko/persistence/EventAdapterSpec.scala +++ b/persistence/src/test/scala/org/apache/pekko/persistence/EventAdapterSpec.scala @@ -91,7 +91,7 @@ object EventAdapterSpec { val persistIncoming: Receive = { case GetState => - state.reverse.foreach { sender() ! _ } + state.reverse.foreach(sender() ! _) case in => persist(in) { e => state ::= e diff --git a/persistence/src/test/scala/org/apache/pekko/persistence/EventSourcedActorFailureSpec.scala b/persistence/src/test/scala/org/apache/pekko/persistence/EventSourcedActorFailureSpec.scala index d5606fa0d6a..7014dbdef0d 100644 --- a/persistence/src/test/scala/org/apache/pekko/persistence/EventSourcedActorFailureSpec.scala +++ b/persistence/src/test/scala/org/apache/pekko/persistence/EventSourcedActorFailureSpec.scala @@ -32,7 +32,7 @@ object EventSourcedActorFailureSpec { class FailingInmemJournal extends InmemJournal { - override def asyncWriteMessages(messages: immutable.Seq[AtomicWrite]): Future[immutable.Seq[Try[Unit]]] = { + override def asyncWriteMessages(messages: immutable.Seq[AtomicWrite]): Future[immutable.Seq[Try[Unit]]] = if (isWrong(messages)) throw new SimulatedException("Simulated Store failure") else { val ser = checkSerializable(messages) @@ -41,7 +41,6 @@ object EventSourcedActorFailureSpec { else super.asyncWriteMessages(messages) } - } override def asyncReplayMessages(persistenceId: String, fromSequenceNr: Long, toSequenceNr: Long, max: Long)( recoveryCallback: PersistentRepr => Unit): Future[Unit] = { diff --git a/persistence/src/test/scala/org/apache/pekko/persistence/OptimizedRecoverySpec.scala b/persistence/src/test/scala/org/apache/pekko/persistence/OptimizedRecoverySpec.scala index b4a3a742fca..50e8d5be3fe 100644 --- a/persistence/src/test/scala/org/apache/pekko/persistence/OptimizedRecoverySpec.scala +++ b/persistence/src/test/scala/org/apache/pekko/persistence/OptimizedRecoverySpec.scala @@ -26,9 +26,8 @@ object OptimizedRecoverySpec { final case class Saved(s: String, seqNr: Long) case object PersistFromRecoveryCompleted - def props(name: String, recovery: Recovery, probe: ActorRef): Props = { + def props(name: String, recovery: Recovery, probe: ActorRef): Props = Props(new TestPersistentActor(name, recovery, probe)) - } } class TestPersistentActor(name: String, override val recovery: Recovery, probe: ActorRef) diff --git a/persistence/src/test/scala/org/apache/pekko/persistence/PerformanceSpec.scala b/persistence/src/test/scala/org/apache/pekko/persistence/PerformanceSpec.scala index f75ce5fc286..d1afd687f21 100644 --- a/persistence/src/test/scala/org/apache/pekko/persistence/PerformanceSpec.scala +++ b/persistence/src/test/scala/org/apache/pekko/persistence/PerformanceSpec.scala @@ -38,9 +38,8 @@ object PerformanceSpec { private var startTime: Long = 0L private var stopTime: Long = 0L - def startMeasure(): Unit = { + def startMeasure(): Unit = startTime = System.nanoTime - } def stopMeasure(): Double = { stopTime = System.nanoTime @@ -134,7 +133,7 @@ class PerformanceSpec val loadCycles = system.settings.config.getInt("pekko.persistence.performance.cycles.load") def stressPersistentActor(persistentActor: ActorRef, failAt: Option[Long], description: String): Unit = { - failAt.foreach { persistentActor ! FailAt(_) } + failAt.foreach(persistentActor ! FailAt(_)) val m = new Measure(loadCycles) m.startMeasure() (1 to loadCycles).foreach { i => diff --git a/persistence/src/test/scala/org/apache/pekko/persistence/PersistenceSpec.scala b/persistence/src/test/scala/org/apache/pekko/persistence/PersistenceSpec.scala index 67c5f4437d3..e8d242a72f0 100644 --- a/persistence/src/test/scala/org/apache/pekko/persistence/PersistenceSpec.scala +++ b/persistence/src/test/scala/org/apache/pekko/persistence/PersistenceSpec.scala @@ -61,9 +61,8 @@ abstract class PersistenceSpec(config: Config) def namedPersistentActorWithProvidedConfig[T <: NamedPersistentActor: ClassTag](providedConfig: Config) = system.actorOf(Props(implicitly[ClassTag[T]].runtimeClass, name, providedConfig)) - override protected def beforeEach(): Unit = { + override protected def beforeEach(): Unit = _name = s"$namePrefix-${counter.incrementAndGet()}" - } } object PersistenceSpec { @@ -93,13 +92,11 @@ trait Cleanup { this: PekkoSpec => "pekko.persistence.journal.leveldb.dir", "pekko.persistence.journal.leveldb-shared.store.dir").map(s => new File(system.settings.config.getString(s))) - override protected def atStartup(): Unit = { + override protected def atStartup(): Unit = storageLocations.foreach(FileUtils.deleteDirectory) - } - override protected def afterTermination(): Unit = { + override protected def afterTermination(): Unit = storageLocations.foreach(FileUtils.deleteDirectory) - } } abstract class NamedPersistentActor(name: String) extends PersistentActor { diff --git a/persistence/src/test/scala/org/apache/pekko/persistence/PersistentActorBoundedStashingSpec.scala b/persistence/src/test/scala/org/apache/pekko/persistence/PersistentActorBoundedStashingSpec.scala index f09d5dd430b..91d44048bb1 100644 --- a/persistence/src/test/scala/org/apache/pekko/persistence/PersistentActorBoundedStashingSpec.scala +++ b/persistence/src/test/scala/org/apache/pekko/persistence/PersistentActorBoundedStashingSpec.scala @@ -81,9 +81,8 @@ class SteppingInMemPersistentActorBoundedStashingSpec(strategyConfig: String) with BeforeAndAfterEach with ImplicitSender { - override def atStartup(): Unit = { + override def atStartup(): Unit = system.eventStream.publish(Mute(EventFilter.warning(pattern = ".*received dead letter from.*Cmd.*"))) - } override def beforeEach(): Unit = { super.beforeEach() diff --git a/persistence/src/test/scala/org/apache/pekko/persistence/PersistentActorRecoveryTimeoutSpec.scala b/persistence/src/test/scala/org/apache/pekko/persistence/PersistentActorRecoveryTimeoutSpec.scala index a16934b678c..c9688c917d8 100644 --- a/persistence/src/test/scala/org/apache/pekko/persistence/PersistentActorRecoveryTimeoutSpec.scala +++ b/persistence/src/test/scala/org/apache/pekko/persistence/PersistentActorRecoveryTimeoutSpec.scala @@ -44,18 +44,16 @@ object PersistentActorRecoveryTimeoutSpec { } } - override protected def onRecoveryFailure(cause: Throwable, event: Option[Any]): Unit = { + override protected def onRecoveryFailure(cause: Throwable, event: Option[Any]): Unit = probe ! Failure(cause) - } } class TestReceiveTimeoutActor(receiveTimeout: FiniteDuration, probe: ActorRef) extends NamedPersistentActor("recovery-timeout-actor-2") with ActorLogging { - override def preStart(): Unit = { + override def preStart(): Unit = context.setReceiveTimeout(receiveTimeout) - } override def receiveRecover: Receive = { case RecoveryCompleted => probe ! context.receiveTimeout diff --git a/persistence/src/test/scala/org/apache/pekko/persistence/PersistentActorSpec.scala b/persistence/src/test/scala/org/apache/pekko/persistence/PersistentActorSpec.scala index 9a473dcf085..210a370c727 100644 --- a/persistence/src/test/scala/org/apache/pekko/persistence/PersistentActorSpec.scala +++ b/persistence/src/test/scala/org/apache/pekko/persistence/PersistentActorSpec.scala @@ -220,9 +220,8 @@ object PersistentActorSpec { this.events = events } - private def handleCmd(cmd: Cmd): Unit = { + private def handleCmd(cmd: Cmd): Unit = persistAll(Seq(Evt(s"${cmd.data}-41"), Evt(s"${cmd.data}-42")))(updateState) - } def receiveCommand: Receive = commonBehavior.orElse { case c: Cmd => handleCmd(c) @@ -492,10 +491,10 @@ object PersistentActorSpec { abstract class DeferringWithPersistActor(name: String) extends ExamplePersistentActor(name) with DeferActor { val receiveCommand: Receive = { case Cmd(data) => - doDefer("d-1") { sender() ! _ } - persist(s"$data-2") { sender() ! _ } - doDefer("d-3") { sender() ! _ } - doDefer("d-4") { sender() ! _ } + doDefer("d-1")(sender() ! _) + persist(s"$data-2")(sender() ! _) + doDefer("d-3")(sender() ! _) + doDefer("d-4")(sender() ! _) } } class DeferringAsyncWithPersistActor(name: String) extends DeferringWithPersistActor(name) with DeferAsync @@ -510,10 +509,10 @@ object PersistentActorSpec { abstract class DeferringWithAsyncPersistActor(name: String) extends ExamplePersistentActor(name) with DeferActor { val receiveCommand: Receive = { case Cmd(data) => - doDefer(s"d-$data-1") { sender() ! _ } - persistAsync(s"pa-$data-2") { sender() ! _ } - doDefer(s"d-$data-3") { sender() ! _ } - doDefer(s"d-$data-4") { sender() ! _ } + doDefer(s"d-$data-1")(sender() ! _) + persistAsync(s"pa-$data-2")(sender() ! _) + doDefer(s"d-$data-3")(sender() ! _) + doDefer(s"d-$data-4")(sender() ! _) } } class DeferringAsyncWithAsyncPersistActor(name: String) extends DeferringWithAsyncPersistActor(name) with DeferAsync @@ -530,12 +529,12 @@ object PersistentActorSpec { with DeferActor { val receiveCommand: Receive = { case Cmd(data) => - persist(s"p-$data-1") { sender() ! _ } - persistAsync(s"pa-$data-2") { sender() ! _ } - doDefer(s"d-$data-3") { sender() ! _ } - doDefer(s"d-$data-4") { sender() ! _ } - persistAsync(s"pa-$data-5") { sender() ! _ } - doDefer(s"d-$data-6") { sender() ! _ } + persist(s"p-$data-1")(sender() ! _) + persistAsync(s"pa-$data-2")(sender() ! _) + doDefer(s"d-$data-3")(sender() ! _) + doDefer(s"d-$data-4")(sender() ! _) + persistAsync(s"pa-$data-5")(sender() ! _) + doDefer(s"d-$data-6")(sender() ! _) } } class DeferringAsyncMixedCallsPPADDPADPersistActor(name: String) @@ -560,9 +559,9 @@ object PersistentActorSpec { with DeferActor { val receiveCommand: Receive = { case Cmd(_) => - doDefer("d-1") { sender() ! _ } - doDefer("d-2") { sender() ! _ } - doDefer("d-3") { sender() ! _ } + doDefer("d-1")(sender() ! _) + doDefer("d-2")(sender() ! _) + doDefer("d-3")(sender() ! _) } } class DeferringAsyncWithNoPersistCallsPersistActor(name: String) @@ -1669,7 +1668,7 @@ class InmemPersistentActorSpec extends PersistentActorSpec(PersistenceSpec.confi class InmemPersistentActorWithRuntimePluginConfigSpec extends PersistentActorSpec(PersistenceSpec.config("inmem", "InmemPersistentActorWithRuntimePluginConfigSpec")) { - val providedActorConfig: Config = { + val providedActorConfig: Config = ConfigFactory .parseString(s""" | custom.persistence.snapshot-store.local.dir = target/snapshots-InmemPersistentActorWithRuntimePluginConfigSpec/ @@ -1680,7 +1679,6 @@ class InmemPersistentActorWithRuntimePluginConfigSpec .withValue( "custom.persistence.snapshot-store.local", system.settings.config.getValue("pekko.persistence.snapshot-store.local")) - } override protected def behavior1PersistentActor: ActorRef = namedPersistentActorWithProvidedConfig[Behavior1PersistentActorWithInmemRuntimePluginConfig](providedActorConfig) diff --git a/persistence/src/test/scala/org/apache/pekko/persistence/PersistentActorStashingSpec.scala b/persistence/src/test/scala/org/apache/pekko/persistence/PersistentActorStashingSpec.scala index a7b18503a4a..99d6cad4306 100644 --- a/persistence/src/test/scala/org/apache/pekko/persistence/PersistentActorStashingSpec.scala +++ b/persistence/src/test/scala/org/apache/pekko/persistence/PersistentActorStashingSpec.scala @@ -185,9 +185,8 @@ object PersistentActorStashingSpec { case _ => // ignore } - def stashWithinHandler(@unused evt: Evt) = { + def stashWithinHandler(@unused evt: Evt) = stash() - } val receiveCommand: Receive = { case Cmd("a") => persist(Evt("a"))(stashWithinHandler) @@ -204,7 +203,7 @@ object PersistentActorStashingSpec { abstract class PersistentActorStashingSpec(config: Config) extends PersistenceSpec(config) with ImplicitSender { import PersistentActorStashingSpec._ - def stash[T <: NamedPersistentActor: ClassTag](): Unit = { + def stash[T <: NamedPersistentActor: ClassTag](): Unit = "support user stash operations" in { val persistentActor = namedPersistentActor[T] persistentActor ! Cmd("a") @@ -214,9 +213,8 @@ abstract class PersistentActorStashingSpec(config: Config) extends PersistenceSp expectMsg("c") expectMsg("a") } - } - def stashWithSeveralMessages[T <: NamedPersistentActor: ClassTag](): Unit = { + def stashWithSeveralMessages[T <: NamedPersistentActor: ClassTag](): Unit = "support user stash operations with several stashed messages" in { val persistentActor = namedPersistentActor[T] val n = 10 @@ -227,9 +225,8 @@ abstract class PersistentActorStashingSpec(config: Config) extends PersistenceSp persistentActor ! GetState expectMsg(evts.toList) } - } - def stashUnderFailures[T <: NamedPersistentActor: ClassTag](): Unit = { + def stashUnderFailures[T <: NamedPersistentActor: ClassTag](): Unit = "support user stash operations under failures" in { val persistentActor = namedPersistentActor[T] val bs = (1 to 10).map("b-" + _) @@ -239,7 +236,6 @@ abstract class PersistentActorStashingSpec(config: Config) extends PersistenceSp persistentActor ! GetState expectMsg(List("a", "c") ++ bs.filter(_ != "b-2")) } - } "Stashing in a persistent actor" must { behave.like(stash[UserStashPersistentActor]()) @@ -280,7 +276,7 @@ class SteppingInMemPersistentActorStashingSpec with ImplicitSender { import PersistentActorStashingSpec._ - def stash[T <: NamedPersistentActor: ClassTag](): Unit = { + def stash[T <: NamedPersistentActor: ClassTag](): Unit = "handle async callback not happening until next message has been stashed" in { val persistentActor = namedPersistentActor[T] awaitAssert(SteppingInmemJournal.getRef("persistence-stash"), 3.seconds) @@ -307,7 +303,6 @@ class SteppingInMemPersistentActorStashingSpec } } } - } "Stashing in a persistent actor mixed with persistAsync" must { behave.like(stash[AsyncStashingPersistentActor]()) diff --git a/persistence/src/test/scala/org/apache/pekko/persistence/RecoveryPermitterSpec.scala b/persistence/src/test/scala/org/apache/pekko/persistence/RecoveryPermitterSpec.scala index 7515afc3acf..ffc86326ef7 100644 --- a/persistence/src/test/scala/org/apache/pekko/persistence/RecoveryPermitterSpec.scala +++ b/persistence/src/test/scala/org/apache/pekko/persistence/RecoveryPermitterSpec.scala @@ -36,9 +36,8 @@ object RecoveryPermitterSpec { override def persistenceId = name - override def postStop(): Unit = { + override def postStop(): Unit = probe ! "postStop" - } override def receiveRecover: Receive = { case RecoveryCompleted => diff --git a/persistence/src/test/scala/org/apache/pekko/persistence/SnapshotDirectoryFailureSpec.scala b/persistence/src/test/scala/org/apache/pekko/persistence/SnapshotDirectoryFailureSpec.scala index 079551eac9d..3436b96df50 100644 --- a/persistence/src/test/scala/org/apache/pekko/persistence/SnapshotDirectoryFailureSpec.scala +++ b/persistence/src/test/scala/org/apache/pekko/persistence/SnapshotDirectoryFailureSpec.scala @@ -52,13 +52,11 @@ class SnapshotDirectoryFailureSpec val file = new File(inUseSnapshotPath) - override protected def atStartup(): Unit = { + override protected def atStartup(): Unit = if (!file.createNewFile()) throw new IOException(s"Failed to create test file [${file.getCanonicalFile}]") - } - override protected def afterTermination(): Unit = { + override protected def afterTermination(): Unit = if (!file.delete()) throw new IOException(s"Failed to delete test file [${file.getCanonicalFile}]") - } "A local snapshot store configured with an failing directory name " must { "throw an exception at startup" in { diff --git a/persistence/src/test/scala/org/apache/pekko/persistence/SnapshotFailureRobustnessSpec.scala b/persistence/src/test/scala/org/apache/pekko/persistence/SnapshotFailureRobustnessSpec.scala index 0369188db90..8738f4b5aec 100644 --- a/persistence/src/test/scala/org/apache/pekko/persistence/SnapshotFailureRobustnessSpec.scala +++ b/persistence/src/test/scala/org/apache/pekko/persistence/SnapshotFailureRobustnessSpec.scala @@ -86,13 +86,12 @@ object SnapshotFailureRobustnessSpec { } class FailingLocalSnapshotStore(config: Config) extends LocalSnapshotStore(config) { - override def save(metadata: SnapshotMetadata, snapshot: Any): Unit = { + override def save(metadata: SnapshotMetadata, snapshot: Any): Unit = if (metadata.sequenceNr == 2 || snapshot.toString.startsWith("boom")) { val bytes = "b0rkb0rk".getBytes(StandardCharsets.UTF_8) // length >= 8 to prevent EOF exception val tmpFile = withOutputStream(metadata)(_.write(bytes)) tmpFile.renameTo(snapshotFileForWrite(metadata)) } else super.save(metadata, snapshot) - } } class DeleteFailingLocalSnapshotStore(config: Config) extends LocalSnapshotStore(config) { @@ -253,9 +252,8 @@ class SnapshotIsOptionalSpec expectMsg("boom2-2") // from event replay expectMsg(RecoveryCompleted) expectNoMessage() - } finally { + } finally system.eventStream.publish(TestEvent.UnMute(EventFilter.error(start = "Error loading snapshot ["))) - } } } diff --git a/persistence/src/test/scala/org/apache/pekko/persistence/fsm/PersistentFSMSpec.scala b/persistence/src/test/scala/org/apache/pekko/persistence/fsm/PersistentFSMSpec.scala index 6b1a9c5eab9..e92ae3447d9 100644 --- a/persistence/src/test/scala/org/apache/pekko/persistence/fsm/PersistentFSMSpec.scala +++ b/persistence/src/test/scala/org/apache/pekko/persistence/fsm/PersistentFSMSpec.scala @@ -555,14 +555,13 @@ object PersistentFSMSpec { * @param cartBeforeEvent state data of the previous state */ // #customer-apply-event - override def applyEvent(event: DomainEvent, cartBeforeEvent: ShoppingCart): ShoppingCart = { + override def applyEvent(event: DomainEvent, cartBeforeEvent: ShoppingCart): ShoppingCart = event match { case ItemAdded(item) => cartBeforeEvent.addItem(item) case OrderExecuted => cartBeforeEvent case OrderDiscarded => cartBeforeEvent.empty() case CustomerInactive => cartBeforeEvent } - } // #customer-apply-event } diff --git a/persistence/src/test/scala/org/apache/pekko/persistence/journal/SteppingInmemJournal.scala b/persistence/src/test/scala/org/apache/pekko/persistence/journal/SteppingInmemJournal.scala index 8a1f7a0c9b1..a54ece88988 100644 --- a/persistence/src/test/scala/org/apache/pekko/persistence/journal/SteppingInmemJournal.scala +++ b/persistence/src/test/scala/org/apache/pekko/persistence/journal/SteppingInmemJournal.scala @@ -151,7 +151,7 @@ final class SteppingInmemJournal extends InmemJournal { future } - private def doOrEnqueue(op: () => Future[Unit]): Unit = { + private def doOrEnqueue(op: () => Future[Unit]): Unit = if (queuedTokenRecipients.nonEmpty) { val completed = op() val tokenRecipient = queuedTokenRecipients.head @@ -161,5 +161,4 @@ final class SteppingInmemJournal extends InmemJournal { } else { queuedOps = queuedOps :+ op } - } } diff --git a/persistence/src/test/scala/org/apache/pekko/persistence/journal/chaos/ChaosJournal.scala b/persistence/src/test/scala/org/apache/pekko/persistence/journal/chaos/ChaosJournal.scala index a111626dbaf..431853abfc5 100644 --- a/persistence/src/test/scala/org/apache/pekko/persistence/journal/chaos/ChaosJournal.scala +++ b/persistence/src/test/scala/org/apache/pekko/persistence/journal/chaos/ChaosJournal.scala @@ -63,7 +63,7 @@ class ChaosJournal extends AsyncWriteJournal { case NonFatal(e) => Future.failed(e) } - override def asyncDeleteMessagesTo(persistenceId: String, toSequenceNr: Long): Future[Unit] = { + override def asyncDeleteMessagesTo(persistenceId: String, toSequenceNr: Long): Future[Unit] = try Future.successful { (1L to toSequenceNr).foreach { snr => del(persistenceId, snr) @@ -72,7 +72,6 @@ class ChaosJournal extends AsyncWriteJournal { catch { case NonFatal(e) => Future.failed(e) } - } def asyncReplayMessages(persistenceId: String, fromSequenceNr: Long, toSequenceNr: Long, max: Long)( replayCallback: (PersistentRepr) => Unit): Future[Unit] = diff --git a/persistence/src/test/scala/org/apache/pekko/persistence/journal/leveldb/JournalCompactionSpec.scala b/persistence/src/test/scala/org/apache/pekko/persistence/journal/leveldb/JournalCompactionSpec.scala index 65f6529dd04..fd7481495c8 100644 --- a/persistence/src/test/scala/org/apache/pekko/persistence/journal/leveldb/JournalCompactionSpec.scala +++ b/persistence/src/test/scala/org/apache/pekko/persistence/journal/leveldb/JournalCompactionSpec.scala @@ -154,18 +154,16 @@ object JournalCompactionSpec { class SpecComponentBuilder(val specId: String, val compactionInterval: Long) { - def config: Config = { + def config: Config = PersistenceSpec.config( "leveldb", specId, extraConfig = Some(s""" | pekko.persistence.journal.leveldb.compaction-intervals.$specId = $compactionInterval """.stripMargin)) - } - def createLogger(system: ActorSystem, watcher: ActorRef): ActorRef = { + def createLogger(system: ActorSystem, watcher: ActorRef): ActorRef = system.actorOf(EventLogger.props(specId, watcher), "logger") - } } @@ -173,9 +171,8 @@ object JournalCompactionSpec { def apply(specId: String): SpecComponentBuilder = apply(specId, 0) - def apply(specId: String, compactionInterval: Long): SpecComponentBuilder = { + def apply(specId: String, compactionInterval: Long): SpecComponentBuilder = new SpecComponentBuilder(specId, compactionInterval) - } } object EventLogger { @@ -211,9 +208,8 @@ object JournalCompactionSpec { override def persistenceId: String = specId - private def onEventPersisted(evt: Event): Unit = { + private def onEventPersisted(evt: Event): Unit = watcher ! Generated(evt.seqNr) - } private def randomText(): String = Random.nextString(1024) } diff --git a/persistence/src/test/scala/org/apache/pekko/persistence/serialization/SnapshotSerializerMigrationAkkaSpec.scala b/persistence/src/test/scala/org/apache/pekko/persistence/serialization/SnapshotSerializerMigrationAkkaSpec.scala index 952df9ed9c0..c391c043165 100644 --- a/persistence/src/test/scala/org/apache/pekko/persistence/serialization/SnapshotSerializerMigrationAkkaSpec.scala +++ b/persistence/src/test/scala/org/apache/pekko/persistence/serialization/SnapshotSerializerMigrationAkkaSpec.scala @@ -63,9 +63,8 @@ class SnapshotSerializerMigrationAkkaSpec extends PekkoSpec( intercept[NotSerializableException] { pekkoOnlySerialization.deserialize(bytes, classOf[Snapshot]).get } - } finally { + } finally pekkoOnlySystem.terminate() - } } } } diff --git a/pki/src/main/scala/org/apache/pekko/pki/pem/DERPrivateKeyLoader.scala b/pki/src/main/scala/org/apache/pekko/pki/pem/DERPrivateKeyLoader.scala index c909919947d..519e4d6be18 100644 --- a/pki/src/main/scala/org/apache/pekko/pki/pem/DERPrivateKeyLoader.scala +++ b/pki/src/main/scala/org/apache/pekko/pki/pem/DERPrivateKeyLoader.scala @@ -43,7 +43,7 @@ object DERPrivateKeyLoader { */ @ApiMayChange @throws[PEMLoadingException]("when the `derData` is for an unsupported format") - def load(derData: DERData): PrivateKey = { + def load(derData: DERData): PrivateKey = derData.label match { case "RSA PRIVATE KEY" => loadPkcs1PrivateKey(derData.bytes) @@ -52,18 +52,15 @@ object DERPrivateKeyLoader { case unknown => throw new PEMLoadingException(s"Don't know how to read a private key from PEM data with label [$unknown]") } - } private def loadPkcs1PrivateKey(bytes: Array[Byte]) = { val derInputStream = new ASN1InputStream(new DERDecoder, bytes) // Here's the specification: https://tools.ietf.org/html/rfc3447#appendix-A.1.2 - val sequence = { - try { + val sequence = + try derInputStream.readObject[ASN1Sequence]() - } finally { + finally derInputStream.close() - } - } val version = getInteger(sequence, 0, "version").intValueExact() if (version < 0 || version > 1) { throw new IllegalArgumentException(s"Unsupported PKCS1 version: $version") @@ -115,21 +112,19 @@ object DERPrivateKeyLoader { keyFactory.generatePrivate(keySpec) } - private def getInteger(sequence: ASN1Sequence, index: Int, name: String): BigInteger = { + private def getInteger(sequence: ASN1Sequence, index: Int, name: String): BigInteger = sequence.get(index) match { case integer: ASN1Integer => integer.getValue case other => throw new IllegalArgumentException(s"Expected integer tag for $name at index $index, but got: ${other.getTag}") } - } - private def getSequence(sequence: ASN1Sequence, index: Int, name: String): ASN1Sequence = { + private def getSequence(sequence: ASN1Sequence, index: Int, name: String): ASN1Sequence = sequence.get(index) match { case seq: ASN1Sequence => seq case other => throw new IllegalArgumentException(s"Expected sequence tag for $name at index $index, but got: ${other.getTag}") } - } private def loadPkcs8PrivateKey(bytes: Array[Byte]) = { val keySpec = new PKCS8EncodedKeySpec(bytes) diff --git a/pki/src/main/scala/org/apache/pekko/pki/pem/PEMDecoder.scala b/pki/src/main/scala/org/apache/pekko/pki/pem/PEMDecoder.scala index b5cbd9f31cb..0fed1b550d5 100644 --- a/pki/src/main/scala/org/apache/pekko/pki/pem/PEMDecoder.scala +++ b/pki/src/main/scala/org/apache/pekko/pki/pem/PEMDecoder.scala @@ -63,12 +63,12 @@ object PEMDecoder { @throws[PEMLoadingException]( "If the `pemData` is not valid PEM format (according to https://tools.ietf.org/html/rfc7468).") @ApiMayChange - def decode(pemData: String): DERData = { + def decode(pemData: String): DERData = pemData match { case PEMRegex(label, base64) => - try { + try new DERData(label, Base64.getMimeDecoder.decode(base64)) - } catch { + catch { case iae: IllegalArgumentException => throw new PEMLoadingException( s"Error decoding base64 data from PEM data (note: expected MIME-formatted Base64)", @@ -77,7 +77,6 @@ object PEMDecoder { case _ => throw new PEMLoadingException("Not a PEM encoded data.") } - } @ApiMayChange final class DERData(val label: String, val bytes: Array[Byte]) diff --git a/plugins/serialversion-remover-plugin/src/main/scala/org/apache/pekko/Plugin.scala b/plugins/serialversion-remover-plugin/src/main/scala/org/apache/pekko/Plugin.scala index ad9224bab47..cfd143a61ea 100644 --- a/plugins/serialversion-remover-plugin/src/main/scala/org/apache/pekko/Plugin.scala +++ b/plugins/serialversion-remover-plugin/src/main/scala/org/apache/pekko/Plugin.scala @@ -27,9 +27,8 @@ class SerialVersionRemoverPlugin extends StandardPlugin { val name = "serialversion-remover-plugin" val description = "Remove SerialVersionUid annotation from traits" - def init(options: List[String]): List[PluginPhase] = { + def init(options: List[String]): List[PluginPhase] = (new SerialVersionRemoverPhase()) :: Nil - } } class SerialVersionRemoverPhase extends PluginPhase { diff --git a/project/AddLogTimestamps.scala b/project/AddLogTimestamps.scala index 4a0269e3801..77eb8cbac9a 100644 --- a/project/AddLogTimestamps.scala +++ b/project/AddLogTimestamps.scala @@ -28,7 +28,7 @@ object AddLogTimestamps extends AutoPlugin { private val UTC = ZoneId.of("UTC") - override lazy val projectSettings: Seq[Def.Setting[_]] = { + override lazy val projectSettings: Seq[Def.Setting[_]] = logManager := { val original = logManager.value @@ -72,5 +72,4 @@ object AddLogTimestamps extends AutoPlugin { } else original } - } } diff --git a/project/CopyrightHeaderForBoilerplate.scala b/project/CopyrightHeaderForBoilerplate.scala index e26913186dc..9fd83a31454 100644 --- a/project/CopyrightHeaderForBoilerplate.scala +++ b/project/CopyrightHeaderForBoilerplate.scala @@ -21,7 +21,7 @@ object CopyrightHeaderForBoilerplate extends AutoPlugin { override lazy val requires: Plugins = BoilerplatePlugin && CopyrightHeader override lazy val trigger: PluginTrigger = allRequirements - override lazy val projectSettings: Seq[Def.Setting[_]] = { + override lazy val projectSettings: Seq[Def.Setting[_]] = Seq(Compile, Test).flatMap { config => inConfig(config) { Seq( @@ -30,5 +30,4 @@ object CopyrightHeaderForBoilerplate extends AutoPlugin { headerMappings := headerMappings.value ++ Map(HeaderFileType("template") -> cStyleComment)) } } - } } diff --git a/project/CopyrightHeaderForBuild.scala b/project/CopyrightHeaderForBuild.scala index 1fbbfdb0294..cad2fe7aaab 100644 --- a/project/CopyrightHeaderForBuild.scala +++ b/project/CopyrightHeaderForBuild.scala @@ -20,7 +20,7 @@ object CopyrightHeaderForBuild extends AutoPlugin { override lazy val requires: Plugins = CopyrightHeader override lazy val trigger: PluginTrigger = noTrigger - override lazy val projectSettings: Seq[Def.Setting[_]] = { + override lazy val projectSettings: Seq[Def.Setting[_]] = Seq(Compile, Test).flatMap { config => inConfig(config) { Seq( @@ -30,5 +30,4 @@ object CopyrightHeaderForBuild extends AutoPlugin { headerMappings := headerMappings.value ++ Map(HeaderFileType.scala -> cStyleComment)) } } - } } diff --git a/project/CopyrightHeaderForJdk9.scala b/project/CopyrightHeaderForJdk9.scala index 1707bbbc385..65252f35e41 100644 --- a/project/CopyrightHeaderForJdk9.scala +++ b/project/CopyrightHeaderForJdk9.scala @@ -28,9 +28,7 @@ object CopyrightHeaderForJdk9 extends AutoPlugin { } yield file } - override lazy val projectSettings: Seq[Def.Setting[_]] = { - + override lazy val projectSettings: Seq[Def.Setting[_]] = Seq(Compile / headerSources ++= additionalFiles.value, Test / headerSources ++= additionalFiles.value) - } } diff --git a/project/CopyrightHeaderForProtobuf.scala b/project/CopyrightHeaderForProtobuf.scala index 9d11dcd9028..58c94550abd 100644 --- a/project/CopyrightHeaderForProtobuf.scala +++ b/project/CopyrightHeaderForProtobuf.scala @@ -21,7 +21,7 @@ object CopyrightHeaderForProtobuf extends AutoPlugin { override lazy val requires = CopyrightHeader override lazy val trigger = allRequirements - override lazy val projectSettings: Seq[Def.Setting[_]] = { + override lazy val projectSettings: Seq[Def.Setting[_]] = Seq(Compile, Test).flatMap { config => inConfig(config) { Seq( @@ -30,5 +30,4 @@ object CopyrightHeaderForProtobuf extends AutoPlugin { headerMappings := headerMappings.value ++ Map(HeaderFileType("proto") -> cStyleComment)) } } - } } diff --git a/project/Doc.scala b/project/Doc.scala index a2528d2d666..fe3556b72c9 100644 --- a/project/Doc.scala +++ b/project/Doc.scala @@ -34,7 +34,7 @@ object Scaladoc extends AutoPlugin { val validateDiagrams = settingKey[Boolean]("Validate generated scaladoc diagrams") - override lazy val projectSettings = { + override lazy val projectSettings = inTask(doc)( Seq( Compile / scalacOptions ++= scaladocOptions(version.value, (ThisBuild / baseDirectory).value), @@ -48,7 +48,6 @@ object Scaladoc extends AutoPlugin { scaladocVerifier(docs) docs }) - } def scaladocOptions(ver: String, base: File): List[String] = { val urlString = GitHub.url(ver) + "/€{FILE_PATH_EXT}#L€{FILE_LINE}" @@ -70,7 +69,7 @@ object Scaladoc extends AutoPlugin { def scaladocVerifier(file: File): File = { @tailrec - def findHTMLFileWithDiagram(dirs: Seq[File]): Boolean = { + def findHTMLFileWithDiagram(dirs: Seq[File]): Boolean = if (dirs.isEmpty) false else { val curr = dirs.head @@ -97,7 +96,6 @@ object Scaladoc extends AutoPlugin { } hasDiagram || findHTMLFileWithDiagram(rest) } - } // if we have generated scaladoc and none of the files have a diagram then fail if (file.exists() && !findHTMLFileWithDiagram(List(file))) @@ -148,7 +146,7 @@ object UnidocRoot extends AutoPlugin { override lazy val projectSettings = { def unidocRootProjectFilter(ignoreProjects: Seq[ProjectReference]): ProjectFilter = - ignoreProjects.foldLeft(inAnyProject) { _ -- inProjects(_) } + ignoreProjects.foldLeft(inAnyProject)(_ -- inProjects(_)) inTask(unidoc)( Seq( @@ -162,23 +160,21 @@ object UnidocRoot extends AutoPlugin { (LocalProject("stream") / Compile / fullClasspath).value def mappingsFor(organization: String, names: List[String], location: String, - revision: String => String = identity): Seq[(File, URL)] = { + revision: String => String = identity): Seq[(File, URL)] = for { entry: Attributed[File] <- entries module: ModuleID <- entry.get(moduleID.key) if module.organization == organization if names.exists(module.name.startsWith) } yield entry.data -> url(location.format(module.revision)) - } - val mappings: Seq[(File, URL)] = { + val mappings: Seq[(File, URL)] = mappingsFor("org.slf4j", List("slf4j-api"), "https://www.javadoc.io/doc/org.slf4j/slf4j-api/%s/") ++ mappingsFor("com.typesafe", List("config"), "https://www.javadoc.io/doc/com.typesafe/config/%s/") ++ mappingsFor("io.aeron", List("aeron-client", "aeron-driver"), "https://www.javadoc.io/doc/io.aeron/aeron-all/%s/") ++ mappingsFor("org.reactivestreams", List("reactive-streams"), "https://www.javadoc.io/doc/org.reactivestreams/reactive-streams/%s/") - } mappings.toMap }, diff --git a/project/Jdk9.scala b/project/Jdk9.scala index 422b6d65e6a..958b82ff348 100644 --- a/project/Jdk9.scala +++ b/project/Jdk9.scala @@ -40,17 +40,15 @@ object Jdk9 extends AutoPlugin { lazy val additionalTestSourceDirectories = getAdditionalSourceDirectories(Test, ScalaTestSourceDirectories ++ JavaTestSourceDirectories) - private def getAdditionalSourceDirectoryNames(language: String, isTest: Boolean = false): Seq[String] = { + private def getAdditionalSourceDirectoryNames(language: String, isTest: Boolean = false): Seq[String] = for { version <- supportedJavaLTSVersions if version.toInt <= majorVersion - } yield { + } yield if (isTest) { s"$language-jdk$version-only" } else { s"$language-jdk-$version" } - } - } private def getAdditionalSourceDirectories(task: Configuration, sourceDirectoryNames: Seq[String]) = Def.setting { for (sourceDirectoryName <- sourceDirectoryNames) diff --git a/project/Jvm.scala b/project/Jvm.scala index 5afd85f5936..080c79ffdfd 100644 --- a/project/Jvm.scala +++ b/project/Jvm.scala @@ -23,9 +23,8 @@ object Jvm { jvmOptions: Seq[String], runOptions: Seq[String], logger: Logger, - connectInput: Boolean) = { + connectInput: Boolean) = forkJava(javaBin, jvmOptions ++ runOptions, logger, connectInput) - } def forkJava(javaBin: File, options: Seq[String], logger: Logger, connectInput: Boolean) = { val java = javaBin.toString @@ -38,9 +37,9 @@ object Jvm { * check if the current operating system is some OS */ def isOS(os: String) = - try { + try System.getProperty("os.name").toUpperCase.startsWith(os.toUpperCase) - } catch { + catch { case _: Throwable => false } @@ -119,7 +118,7 @@ class JvmBasicLogger(name: String) extends BasicLogger { def success(message: => String) = log(Level.Info, message) def control(event: ControlEvent.Value, message: => String) = log(Level.Info, message) - def logAll(events: Seq[LogEvent]) = System.out.synchronized { events.foreach(log) } + def logAll(events: Seq[LogEvent]) = System.out.synchronized(events.foreach(log)) } final class JvmLogger(name: String) extends JvmBasicLogger(name) diff --git a/project/MultiNode.scala b/project/MultiNode.scala index b6ec884d7af..38a29f70034 100644 --- a/project/MultiNode.scala +++ b/project/MultiNode.scala @@ -91,8 +91,8 @@ object MultiNode extends AutoPlugin { val logger = streams.value.log (name: String) => new Logger { - def trace(t: => Throwable): Unit = { logger.trace(t) } - def success(message: => String): Unit = { logger.success(message) } + def trace(t: => Throwable): Unit = logger.trace(t) + def success(message: => String): Unit = logger.success(message) def log(level: Level.Value, message: => String): Unit = logger.log(level, s"[${scala.Console.BLUE}$name${scala.Console.RESET}] $message") } diff --git a/project/PekkoBuild.scala b/project/PekkoBuild.scala index b68a236009a..d73a601707b 100644 --- a/project/PekkoBuild.scala +++ b/project/PekkoBuild.scala @@ -119,14 +119,13 @@ object PekkoBuild { } } - private def jvmGCLogOptions(isJdk11OrHigher: Boolean, isJdk8: Boolean): Seq[String] = { + private def jvmGCLogOptions(isJdk11OrHigher: Boolean, isJdk8: Boolean): Seq[String] = if (isJdk11OrHigher) // -Xlog:gc* is equivalent to -XX:+PrintGCDetails. See: // https://docs.oracle.com/en/java/javase/11/tools/java.html#GUID-BE93ABDC-999C-4CB5-A88B-1994AAAC74D5 Seq("-Xlog:gc*") else if (isJdk8) Seq("-XX:+PrintGCTimeStamps", "-XX:+PrintGCDetails") else Nil - } // -XDignore.symbol.file suppresses sun.misc.Unsafe warnings final val DefaultJavacOptions = Seq("-encoding", "UTF-8", "-Xlint:unchecked", "-XDignore.symbol.file") diff --git a/project/PekkoDisciplinePlugin.scala b/project/PekkoDisciplinePlugin.scala index 1e1f4a94e43..1d1b5308c16 100644 --- a/project/PekkoDisciplinePlugin.scala +++ b/project/PekkoDisciplinePlugin.scala @@ -91,9 +91,8 @@ object PekkoDisciplinePlugin extends AutoPlugin { Compile / doc / scalacOptions := Seq()) // ignore Scala compile warnings for Java 20+ - lazy val jvmIgnoreWarnings = { + lazy val jvmIgnoreWarnings = System.getProperty("java.version").startsWith("2") - } /** * We are a little less strict in docs diff --git a/project/ProjectFileIgnoreSupport.scala b/project/ProjectFileIgnoreSupport.scala index fa055c94fb0..ba31dc0c17a 100644 --- a/project/ProjectFileIgnoreSupport.scala +++ b/project/ProjectFileIgnoreSupport.scala @@ -55,7 +55,7 @@ class ProjectFileIgnoreSupport(ignoreConfigFile: File, descriptor: String) { } private def isIgnoredByPackages(file: File): Boolean = { - val ignoredByPackages = ignoredPackages.exists(pkg => { + val ignoredByPackages = ignoredPackages.exists { pkg => getPackageName(file.toURI.toString) match { case Some(packageName) => val ignored = packageName.startsWith(pkg) @@ -66,7 +66,7 @@ class ProjectFileIgnoreSupport(ignoreConfigFile: File, descriptor: String) { ignored case None => false } - }) + } ignoredByPackages } diff --git a/project/Protobuf.scala b/project/Protobuf.scala index eac49bf61d8..3b753c47da5 100644 --- a/project/Protobuf.scala +++ b/project/Protobuf.scala @@ -97,9 +97,9 @@ object Protobuf { private def checkProtocVersion(protoc: String, protocVersion: String, log: Logger): Unit = { val res = callProtoc(protoc, Seq("--version"), log, - { (p, l) => + (p, l) => p !! l - }) + ) val version = res.split(" ").last.trim if (version != protocVersion) { sys.error("Wrong protoc version! Expected %s but got %s".format(protocVersion, version)) @@ -129,9 +129,9 @@ object Protobuf { Seq("-I" + srcDir.absolutePath, "--java_out=%s".format(targetDir.absolutePath)) ++ protoPathArg ++ protoFiles.map(_.absolutePath), log, - { (p, l) => + (p, l) => p ! l - }) + ) if (exitCode != 0) sys.error("protoc returned exit code: %d".format(exitCode)) } @@ -152,9 +152,8 @@ object Protobuf { val map = Path.rebase(sourceDir, targetDir) if (in.removed.nonEmpty || in.modified.nonEmpty) { log.info("Preprocessing directory %s...".format(sourceDir)) - for (source <- in.removed; target <- map(source)) { + for (source <- in.removed; target <- map(source)) IO.delete(target) - } val updated = for (source <- in.modified; target <- map(source)) yield { if (source.isFile) { if (transformable(source)) transform(source, target) @@ -174,7 +173,7 @@ object Protobuf { /** * Transform a file, line by line. */ - def transformFile(transform: String => String)(source: File, target: File): Unit = { + def transformFile(transform: String => String)(source: File, target: File): Unit = IO.reader(source) { reader => IO.writer(target, "", IO.defaultCharset) { writer => val pw = new PrintWriter(writer) @@ -183,6 +182,5 @@ object Protobuf { } } } - } } diff --git a/project/SbtMultiJvmPlugin.scala b/project/SbtMultiJvmPlugin.scala index 7f270ae0c03..3312826141c 100644 --- a/project/SbtMultiJvmPlugin.scala +++ b/project/SbtMultiJvmPlugin.scala @@ -183,22 +183,20 @@ object MultiJvmPlugin extends AutoPlugin { val testFilters = new collection.mutable.ListBuffer[String => Boolean] val excludeTestsSet = new collection.mutable.HashSet[String] - for (option <- testOptions) { + for (option <- testOptions) option match { case Tests.Exclude(excludedTests) => excludeTestsSet ++= excludedTests case Tests.Filter(filterTestsIn) => testFilters += filterTestsIn case _ => // do nothing since the intention is only to filter tests } - } if (excludeTestsSet.nonEmpty) { log.debug(excludeTestsSet.mkString("Excluding tests: \n\t", "\n\t", "")) } - def includeTest(test: TestDefinition): Boolean = { + def includeTest(test: TestDefinition): Boolean = !excludeTestsSet.contains(test.name) && testFilters.forall(filter => filter(test.name)) && test.name.contains( marker) - } val groupedTests: Map[String, List[TestDefinition]] = discovered.filter(includeTest).toList.distinct.groupBy(test => multiName(test.name, marker)) @@ -232,9 +230,8 @@ object MultiJvmPlugin extends AutoPlugin { new File(new File(home, "bin"), name) } - def defaultScalatestOptions: Seq[String] = { + def defaultScalatestOptions: Seq[String] = if (getBoolean("sbt.log.noformat")) Seq("-oW") else Seq("-o") - } def scalaOptionsForScalatest( runner: String, @@ -250,11 +247,11 @@ object MultiJvmPlugin extends AutoPlugin { val cp = directoryBasedClasspathEntries.absString + File.pathSeparator + multiRunCopiedClassDir.getAbsolutePath + File .separator + "*" - (testClass: String) => { Seq("-cp", cp, runner, "-s", testClass) ++ options } + (testClass: String) => Seq("-cp", cp, runner, "-s", testClass) ++ options } def scalaMultiNodeOptionsForScalatest(runner: String, options: Seq[String]) = { (testClass: String) => - { Seq(runner, "-s", testClass) ++ options } + Seq(runner, "-s", testClass) ++ options } def scalaOptionsForApps(classpath: Classpath) = { @@ -279,7 +276,7 @@ object MultiJvmPlugin extends AutoPlugin { case (selection, _extraOptions) => val s = streams.value val options = multiTestOptions.value - val opts = options.copy(extra = (s: String) => { options.extra(s) ++ _extraOptions }) + val opts = options.copy(extra = (s: String) => options.extra(s) ++ _extraOptions) val filters = selection.map(GlobFilter(_)) val tests = multiJvmTests.value.filterKeys(name => filters.exists(_.accept(name))) Def.task { @@ -413,7 +410,7 @@ object MultiJvmPlugin extends AutoPlugin { val options = multiNodeTestOptions.value val (_jarName, (hostsAndUsers, javas), targetDir) = multiNodeWorkAround.value val s = streams.value - val opts = options.copy(extra = (s: String) => { options.extra(s) ++ _extraOptions }) + val opts = options.copy(extra = (s: String) => options.extra(s) ++ _extraOptions) val tests = selected.flatMap { name => multiJvmTests.value.get(name).map((name, _)) } @@ -500,7 +497,7 @@ object MultiJvmPlugin extends AutoPlugin { val syncResult = processExitCodes(name, syncProcesses, log) if (syncResult._2 == TestResult.Passed) { val processes = classesHostsJavas.zipWithIndex.map { - case ((testClass, hostAndUser, java), index) => { + case ((testClass, hostAndUser, java), index) => val jvmName = "JVM-" + (index + 1) val jvmLogger = createLogger(jvmName) val className = multiSimpleName(testClass) @@ -527,7 +524,6 @@ object MultiJvmPlugin extends AutoPlugin { jvmLogger, connectInput, log)) - } } processExitCodes(name, processes, log) } else { @@ -556,13 +552,12 @@ object MultiJvmPlugin extends AutoPlugin { tuple.zipped.map { case (className: String, hostAndUser: String, _java: String) => (className, hostAndUser, _java) } } - private def getMultiNodeCommandLineOptions(hosts: Seq[String], index: Int, maxNodes: Int): Seq[String] = { + private def getMultiNodeCommandLineOptions(hosts: Seq[String], index: Int, maxNodes: Int): Seq[String] = Seq( "-Dmultinode.max-nodes=" + maxNodes, "-Dmultinode.server-host=" + hosts.head.split("@").last, "-Dmultinode.host=" + hosts(index).split("@").last, "-Dmultinode.index=" + index) - } private def processMultiNodeHosts( hosts: Seq[String], diff --git a/project/ScalafixSupport.scala b/project/ScalafixSupport.scala index 348870ca5cd..700e1251484 100644 --- a/project/ScalafixSupport.scala +++ b/project/ScalafixSupport.scala @@ -30,7 +30,7 @@ trait ScalafixSupport { } } - def addProjectCommandsIfAbsent(alias: String, value: String): Def.Setting[Seq[Command]] = { + def addProjectCommandsIfAbsent(alias: String, value: String): Def.Setting[Seq[Command]] = commands := { val currentCommands = commands.value.flatMap(_.nameOption).toSet val isPresent = currentCommands(alias) @@ -39,13 +39,11 @@ trait ScalafixSupport { else commands.value :+ BasicCommands.newAlias(name = alias, value = value) } - } - def updateProjectCommands(alias: String, value: String): Def.Setting[Seq[Command]] = { + def updateProjectCommands(alias: String, value: String): Def.Setting[Seq[Command]] = commands := { commands.value.filterNot(_.nameOption.contains("alias")) :+ BasicCommands.newAlias(name = alias, value = value) } - } } object ScalafixSupport { diff --git a/project/SigarLoader.scala b/project/SigarLoader.scala index 933908b1ae0..90b71997521 100644 --- a/project/SigarLoader.scala +++ b/project/SigarLoader.scala @@ -34,7 +34,7 @@ object SigarLoader { val sigarFolderProperty = "kamon.sigar.folder" // TODO remove Sigar form test:test* classpath, it is provided by Sigar agent. - lazy val sigarSettings = { + lazy val sigarSettings = Seq( // // Prepare Sigar agent options. @@ -51,6 +51,5 @@ object SigarLoader { Test / fork := true) ++ ( // Invoke Sigar agent at JVM init time, to extract and load native Sigar library. if (sigarTestEnabled) Seq(Test / javaOptions += sigarOptions.value) else Seq()) - } } diff --git a/project/StreamOperatorsIndexGenerator.scala b/project/StreamOperatorsIndexGenerator.scala index 6def2eef025..5c5384761ee 100644 --- a/project/StreamOperatorsIndexGenerator.scala +++ b/project/StreamOperatorsIndexGenerator.scala @@ -113,7 +113,7 @@ object StreamOperatorsIndexGenerator extends AutoPlugin { "foldAsync", "newOnCompleteStage")) - val ignore = { + val ignore = Set("equals", "hashCode", "notify", "notifyAll", "wait", "toString", "getClass") ++ Set("productArity", "canEqual", "productPrefix", "copy", "productIterator", "productElement") ++ Set( @@ -128,7 +128,6 @@ object StreamOperatorsIndexGenerator extends AutoPlugin { "transformMaterializing") ++ Set("asScala", "asJava", "deprecatedAndThen", "deprecatedAndThenMat") ++ Set("++", "onPush", "onPull", "actorRefWithAck") - } def isPending(element: String, opName: String) = pendingTestCases.get(element).exists(_.contains(opName)) diff --git a/project/TestExtras.scala b/project/TestExtras.scala index b39270e24ca..ec6392e97e1 100644 --- a/project/TestExtras.scala +++ b/project/TestExtras.scala @@ -36,7 +36,7 @@ object TestExtras { lazy val testTagsOnly = systemPropertyAsSeq("pekko.test.tags.only").toSet } - lazy val settings = { + lazy val settings = Seq( excludeTestNames := Params.testNamesExclude, excludeTestTags := { @@ -74,11 +74,9 @@ object TestExtras { testsToCheck.foreach((shouldExist _).tupled) }) - } - def containsOrNotExcludesTag(tag: String) = { + def containsOrNotExcludesTag(tag: String) = Params.testTagsOnly.contains(tag) || !Params.testTagsExlcude(tag) - } def systemPropertyAsSeq(name: String): Seq[String] = { val prop = sys.props.get(name).getOrElse("") diff --git a/project/TestQuickUntilPassed.scala b/project/TestQuickUntilPassed.scala index ef18b938fa2..6f9ed79fe8a 100644 --- a/project/TestQuickUntilPassed.scala +++ b/project/TestQuickUntilPassed.scala @@ -39,11 +39,10 @@ object TestQuickUntilPassed extends AutoPlugin { } } - override lazy val projectSettings = { + override lazy val projectSettings = testQuickUntilPassed := { // TODO Figure out a way to pass input from testQuickUntilPassed into testQuickRecursive testQuickRecursive("").value } - } } diff --git a/remote-tests/src/multi-jvm/scala/org/apache/pekko/io/DnsSpec.scala b/remote-tests/src/multi-jvm/scala/org/apache/pekko/io/DnsSpec.scala index 2a918f22f30..1c7e2538090 100644 --- a/remote-tests/src/multi-jvm/scala/org/apache/pekko/io/DnsSpec.scala +++ b/remote-tests/src/multi-jvm/scala/org/apache/pekko/io/DnsSpec.scala @@ -47,16 +47,14 @@ class DnsSpec extends RemotingMultiNodeSpec(DnsSpec) { var temporaryValue: Option[String] = None - override def atStartup(): Unit = { + override def atStartup(): Unit = temporaryValue = sys.props.get("java.net.preferIPv6Addresses") - } - override def afterTermination(): Unit = { + override def afterTermination(): Unit = temporaryValue match { case Some(value) => sys.props.put("java.net.preferIPv6Addresses", value) case _ => sys.props.remove("java.net.preferIPv6Addresses") } - } "Dns" must { diff --git a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/RemoteFeaturesSpec.scala b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/RemoteFeaturesSpec.scala index 8b7c1b9262e..109b6406005 100644 --- a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/RemoteFeaturesSpec.scala +++ b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/RemoteFeaturesSpec.scala @@ -294,9 +294,8 @@ abstract class RemotingFeaturesSpec(val multiNodeConfig: RemotingFeaturesConfig) val actor = system.actorOf(FromConfig.props(), "service-hello3") actor.isInstanceOf[RoutedActorRef] should ===(true) - for (_ <- 0 until iterationCount; _ <- 0 until workerInstances) { + for (_ <- 0 until iterationCount; _ <- 0 until workerInstances) actor ! "hit" - } val replies: Map[Address, Int] = receiveWhile(5.seconds, messages = workerInstances * iterationCount) { case ref: ActorRef => ref.path.address @@ -326,9 +325,8 @@ abstract class RemotingFeaturesSpec(val multiNodeConfig: RemotingFeaturesConfig) val actor = system.actorOf(RoundRobinPool(nrOfInstances = 0).props(Props[SomeActor]()), "service-hello") actor.isInstanceOf[RoutedActorRef] should ===(true) - for (_ <- 0 until iterationCount; _ <- 0 until workerInstances) { + for (_ <- 0 until iterationCount; _ <- 0 until workerInstances) actor ! "hit" - } val replies = receiveWhile(5.seconds, messages = workerInstances * iterationCount) { case ref: ActorRef => ref.path.address @@ -344,7 +342,7 @@ abstract class RemotingFeaturesSpec(val multiNodeConfig: RemotingFeaturesConfig) actor ! Broadcast(PoisonPill) enterBarrier("end") - replies.values.foreach { _ should ===(iterationCount) } + replies.values.foreach(_ should ===(iterationCount)) } else { enterBarrier("broadcast-end") actor ! Broadcast(PoisonPill) diff --git a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/RemoteNodeDeathWatchSpec.scala b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/RemoteNodeDeathWatchSpec.scala index 77a4a3d3ace..f4d893e145e 100644 --- a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/RemoteNodeDeathWatchSpec.scala +++ b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/RemoteNodeDeathWatchSpec.scala @@ -128,14 +128,13 @@ abstract class RemoteNodeDeathWatchSpec(multiNodeConfig: RemoteNodeDeathWatchCon actorIdentity.ref.get } - def assertCleanup(timeout: FiniteDuration = 5.seconds): Unit = { + def assertCleanup(timeout: FiniteDuration = 5.seconds): Unit = within(timeout) { awaitAssert { remoteWatcher ! Stats expectMsg(Stats.empty) } } - } "RemoteNodeDeathWatch (" + scenario + ")" must { diff --git a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/RemoteQuarantinePiercingSpec.scala b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/RemoteQuarantinePiercingSpec.scala index a33b8f9e1aa..f03eb7268db 100644 --- a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/RemoteQuarantinePiercingSpec.scala +++ b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/RemoteQuarantinePiercingSpec.scala @@ -68,12 +68,11 @@ abstract class RemoteQuarantinePiercingSpec(multiNodeConfig: RemoteQuarantinePie def identifyWithUid( role: RoleName, actorName: String, - timeout: FiniteDuration = remainingOrDefault): (Long, ActorRef) = { + timeout: FiniteDuration = remainingOrDefault): (Long, ActorRef) = within(timeout) { system.actorSelection(node(role) / "user" / actorName) ! "identify" expectMsgType[(Long, ActorRef)] } - } "RemoteNodeShutdownAndComesBack" must { diff --git a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/TransportFailSpec.scala b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/TransportFailSpec.scala index ba383730ec6..5bc18af1174 100644 --- a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/TransportFailSpec.scala +++ b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/TransportFailSpec.scala @@ -74,14 +74,12 @@ object TransportFailSpec { class TestFailureDetector(@unused config: Config, @unused ev: EventStream) extends FailureDetector { @volatile private var active = false - override def heartbeat(): Unit = { + override def heartbeat(): Unit = active = true - } - override def isAvailable: Boolean = { + override def isAvailable: Boolean = if (active) fdAvailable.get else true - } override def isMonitoring: Boolean = active } @@ -152,10 +150,9 @@ abstract class TransportFailSpec extends RemotingMultiNodeSpec(TransportFailConf system.eventStream.subscribe(quarantineProbe.ref, classOf[QuarantinedEvent]) var subject2: ActorRef = null - awaitAssert({ - within(1.second) { - subject2 = identify(second, "subject2") - } + awaitAssert( + within(1.second) { + subject2 = identify(second, "subject2") }, max = 5.seconds) watch(subject2) quarantineProbe.expectNoMessage(1.seconds) diff --git a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/FanInThrougputSpec.scala b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/FanInThrougputSpec.scala index 77bd679993b..03196eebedf 100644 --- a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/FanInThrougputSpec.scala +++ b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/FanInThrougputSpec.scala @@ -181,8 +181,7 @@ abstract class FanInThroughputSpec extends RemotingMultiNodeSpec(FanInThroughput "Max throughput of fan-in" must { val reporter = BenchmarkFileReporter("FanInThroughputSpec", system) - for (s <- scenarios) { + for (s <- scenarios) s"be great for ${s.testName}, burstSize = ${s.burstSize}, payloadSize = ${s.payloadSize}" in test(s, reporter) - } } } diff --git a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/FanOutThrougputSpec.scala b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/FanOutThrougputSpec.scala index a272a1dedf8..01af6684bb1 100644 --- a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/FanOutThrougputSpec.scala +++ b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/FanOutThrougputSpec.scala @@ -177,8 +177,7 @@ abstract class FanOutThroughputSpec extends RemotingMultiNodeSpec(FanOutThroughp "Max throughput of fan-out" must { val reporter = BenchmarkFileReporter("FanOutThroughputSpec", system) - for (s <- scenarios) { + for (s <- scenarios) s"be great for ${s.testName}, burstSize = ${s.burstSize}, payloadSize = ${s.payloadSize}" in test(s, reporter) - } } } diff --git a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/HandshakeRestartReceiverSpec.scala b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/HandshakeRestartReceiverSpec.scala index 747e7c2ad37..8e4160b8e4f 100644 --- a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/HandshakeRestartReceiverSpec.scala +++ b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/HandshakeRestartReceiverSpec.scala @@ -68,19 +68,17 @@ abstract class HandshakeRestartReceiverSpec override def initialParticipants = roles.size - override def afterAll(): Unit = { + override def afterAll(): Unit = super.afterAll() - } def identifyWithUid( rootPath: ActorPath, actorName: String, - timeout: FiniteDuration = remainingOrDefault): (Long, ActorRef) = { + timeout: FiniteDuration = remainingOrDefault): (Long, ActorRef) = within(timeout) { system.actorSelection(rootPath / "user" / actorName) ! "identify" expectMsgType[(Long, ActorRef)] } - } private def futureUniqueRemoteAddress(association: OutboundContext): Future[UniqueAddress] = { val p = Promise[UniqueAddress]() diff --git a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/LatencySpec.scala b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/LatencySpec.scala index ba0ac9c2e01..99adbf3673f 100644 --- a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/LatencySpec.scala +++ b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/LatencySpec.scala @@ -136,9 +136,9 @@ object LatencySpec extends MultiNodeConfig { reporter.onMessage(1, size) count += 1 val d = System.nanoTime() - sendTimes.get(count - 1) - try { + try histogram.recordValue(d) - } catch { + catch { case e: ArrayIndexOutOfBoundsException => // Report it only once instead of flooding the console if (!reportedArrayOOB) { @@ -358,9 +358,8 @@ abstract class LatencySpec extends RemotingMultiNodeSpec(LatencySpec) { enterBarrier("echo-started") } - for (s <- scenarios) { + for (s <- scenarios) s"be low for ${s.testName}, at ${s.messageRate} msg/s, payloadSize = ${s.payloadSize}" in test(s, reporter) - } // TODO add more tests diff --git a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/MaxThroughputSpec.scala b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/MaxThroughputSpec.scala index 0ee81052da7..2d84d07b9ea 100644 --- a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/MaxThroughputSpec.scala +++ b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/MaxThroughputSpec.scala @@ -303,7 +303,7 @@ object MaxThroughputSpec extends MultiNodeConfig { remaining -= batchSize } - def sendFlowControl(t0: Long): Unit = { + def sendFlowControl(t0: Long): Unit = if (remaining <= 0) { context.become(waitingForEndResult) targets.foreach(_.tell(End, self)) @@ -313,7 +313,6 @@ object MaxThroughputSpec extends MultiNodeConfig { val flowControlMsg = FlowControl(flowControlId, t0) targets.foreach(_.tell(flowControlMsg, self)) } - } } final case class TestSettings( @@ -498,8 +497,7 @@ abstract class MaxThroughputSpec extends RemotingMultiNodeSpec(MaxThroughputSpec "Max throughput of Artery" must { val reporter = BenchmarkFileReporter("MaxThroughputSpec", system) - for (s <- scenarios) { + for (s <- scenarios) s"be great for ${s.testName}, burstSize = ${s.burstSize}, payloadSize = ${s.payloadSize}" in test(s, reporter) - } } } diff --git a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/RemoteRestartedQuarantinedSpec.scala b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/RemoteRestartedQuarantinedSpec.scala index e7bf806767f..db0de12235b 100644 --- a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/RemoteRestartedQuarantinedSpec.scala +++ b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/RemoteRestartedQuarantinedSpec.scala @@ -63,12 +63,11 @@ abstract class RemoteRestartedQuarantinedSpec extends RemotingMultiNodeSpec(Remo def identifyWithUid( role: RoleName, actorName: String, - timeout: FiniteDuration = remainingOrDefault): (Long, ActorRef) = { + timeout: FiniteDuration = remainingOrDefault): (Long, ActorRef) = within(timeout) { system.actorSelection(node(role) / "user" / actorName) ! "identify" expectMsgType[(Long, ActorRef)] } - } "A restarted quarantined system" must { diff --git a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/TestRateReporter.scala b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/TestRateReporter.scala index bf7962bea13..a553445a146 100644 --- a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/TestRateReporter.scala +++ b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/TestRateReporter.scala @@ -22,7 +22,7 @@ class TestRateReporter(name: String) messagesPerSec: Double, bytesPerSec: Double, totalMessages: Long, - totalBytes: Long): Unit = { + totalBytes: Long): Unit = if (totalBytes > 0) { println( name + @@ -34,5 +34,4 @@ class TestRateReporter(name: String) f": $messagesPerSec%,.0f msgs/sec " + f"total $totalMessages%,d messages") } - } }) {} diff --git a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/aeron/AeronStreamConcistencySpec.scala b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/aeron/AeronStreamConcistencySpec.scala index 768c7447f1a..71b28bed4ab 100644 --- a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/aeron/AeronStreamConcistencySpec.scala +++ b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/aeron/AeronStreamConcistencySpec.scala @@ -148,7 +148,7 @@ abstract class AeronStreamConsistencySpec pool.release(envelope) } .failed - .foreach { _.printStackTrace } + .foreach(_.printStackTrace) within(10.seconds) { Source(1 to 100) diff --git a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/aeron/AeronStreamLatencySpec.scala b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/aeron/AeronStreamLatencySpec.scala index 4ac3632387d..86acaa8f457 100644 --- a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/aeron/AeronStreamLatencySpec.scala +++ b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/aeron/AeronStreamLatencySpec.scala @@ -330,9 +330,8 @@ abstract class AeronStreamLatencySpec enterBarrier("echo-started") } - for (s <- scenarios) { + for (s <- scenarios) s"be low for ${s.testName}, at ${s.messageRate} msg/s, payloadSize = ${s.payloadSize}" in test(s) - } } } diff --git a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/aeron/AeronStreamMaxThroughputSpec.scala b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/aeron/AeronStreamMaxThroughputSpec.scala index 1af66cfa3c4..047075616c9 100644 --- a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/aeron/AeronStreamMaxThroughputSpec.scala +++ b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/artery/aeron/AeronStreamMaxThroughputSpec.scala @@ -185,7 +185,7 @@ abstract class AeronStreamMaxThroughputSpec pool.release(envelope) } .failed - .foreach { _.printStackTrace } + .foreach(_.printStackTrace) enterBarrier(receiverName + "-started") Await.ready(done, barrierTimeout) @@ -231,9 +231,8 @@ abstract class AeronStreamMaxThroughputSpec enterBarrier("udp-port-started") } - for (s <- scenarios) { + for (s <- scenarios) s"be great for ${s.testName}, payloadSize = ${s.payloadSize}" in test(s) - } } } diff --git a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/classic/Ticket15109Spec.scala b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/classic/Ticket15109Spec.scala index b38695b0f38..8dd0da00628 100644 --- a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/classic/Ticket15109Spec.scala +++ b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/classic/Ticket15109Spec.scala @@ -69,14 +69,13 @@ abstract class Ticket15109Spec extends RemotingMultiNodeSpec(Ticket15109Spec) { expectMsgType[ActorIdentity](5.seconds).getActorRef.get } - def ping(ref: ActorRef) = { + def ping(ref: ActorRef) = within(30.seconds) { awaitAssert { ref ! "ping" expectMsg(1.second, "pong") } } - } "Quarantining" must { diff --git a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/routing/RemoteRandomSpec.scala b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/routing/RemoteRandomSpec.scala index bfe1e69b972..1d7cc505683 100644 --- a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/routing/RemoteRandomSpec.scala +++ b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/routing/RemoteRandomSpec.scala @@ -92,9 +92,8 @@ class RemoteRandomSpec(multiNodeConfig: RemoteRandomConfig) val connectionCount = 3 val iterationCount = 100 - for (_ <- 0 until iterationCount; _ <- 0 until connectionCount) { + for (_ <- 0 until iterationCount; _ <- 0 until connectionCount) actor ! "hit" - } val replies: Map[Address, Int] = receiveWhile(5.seconds, messages = connectionCount * iterationCount) { case ref: ActorRef => ref.path.address diff --git a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/routing/RemoteRoundRobinSpec.scala b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/routing/RemoteRoundRobinSpec.scala index 9266aaa57be..8e3b9685408 100644 --- a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/routing/RemoteRoundRobinSpec.scala +++ b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/routing/RemoteRoundRobinSpec.scala @@ -107,9 +107,8 @@ class RemoteRoundRobinSpec(multiNodeConfig: RemoteRoundRobinConfig) val connectionCount = 3 val iterationCount = 10 - for (_ <- 0 until iterationCount; _ <- 0 until connectionCount) { + for (_ <- 0 until iterationCount; _ <- 0 until connectionCount) actor ! "hit" - } val replies: Map[Address, Int] = receiveWhile(5 seconds, messages = connectionCount * iterationCount) { case ref: ActorRef => @@ -123,7 +122,7 @@ class RemoteRoundRobinSpec(multiNodeConfig: RemoteRoundRobinConfig) actor ! Broadcast(PoisonPill) enterBarrier("end") - replies.values.foreach { _ should ===(iterationCount) } + replies.values.foreach(_ should ===(iterationCount)) replies.get(node(fourth).address) should ===(None) // shut down the actor before we let the other node(s) shut down so we don't try to send @@ -195,9 +194,8 @@ class RemoteRoundRobinSpec(multiNodeConfig: RemoteRoundRobinConfig) val connectionCount = 3 val iterationCount = 10 - for (_ <- 0 until iterationCount; _ <- 0 until connectionCount) { + for (_ <- 0 until iterationCount; _ <- 0 until connectionCount) actor ! "hit" - } val replies: Map[Address, Int] = receiveWhile(5 seconds, messages = connectionCount * iterationCount) { case ref: ActorRef => ref.path.address @@ -206,7 +204,7 @@ class RemoteRoundRobinSpec(multiNodeConfig: RemoteRoundRobinConfig) } enterBarrier("end") - replies.values.foreach { _ should ===(iterationCount) } + replies.values.foreach(_ should ===(iterationCount)) replies.get(node(fourth).address) should ===(None) } diff --git a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/routing/RemoteScatterGatherSpec.scala b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/routing/RemoteScatterGatherSpec.scala index 1b11dc204e1..2319651710e 100644 --- a/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/routing/RemoteScatterGatherSpec.scala +++ b/remote-tests/src/multi-jvm/scala/org/apache/pekko/remote/routing/RemoteScatterGatherSpec.scala @@ -103,9 +103,8 @@ class RemoteScatterGatherSpec(multiNodeConfig: RemoteScatterGatherConfig) // let them start Thread.sleep(2000) - for (_ <- 0 until iterationCount; _ <- 0 until connectionCount) { + for (_ <- 0 until iterationCount; _ <- 0 until connectionCount) actor ! "hit" - } val replies: Map[Address, Int] = receiveWhile(5.seconds, messages = connectionCount * iterationCount) { case ref: ActorRef => ref.path.address diff --git a/remote-tests/src/test/scala/org/apache/pekko/remote/artery/ArteryFailedToBindSpec.scala b/remote-tests/src/test/scala/org/apache/pekko/remote/artery/ArteryFailedToBindSpec.scala index 19fbe1bfd64..d6b17be8fdc 100644 --- a/remote-tests/src/test/scala/org/apache/pekko/remote/artery/ArteryFailedToBindSpec.scala +++ b/remote-tests/src/test/scala/org/apache/pekko/remote/artery/ArteryFailedToBindSpec.scala @@ -62,9 +62,8 @@ class ArteryFailedToBindSpec extends AnyWordSpec with Matchers { ex.getMessage should startWith("Failed to bind TCP") } - } finally { + } finally TestKit.shutdownActorSystem(as) - } } } } diff --git a/remote-tests/src/test/scala/org/apache/pekko/remote/classic/RemotingFailedToBindSpec.scala b/remote-tests/src/test/scala/org/apache/pekko/remote/classic/RemotingFailedToBindSpec.scala index b610c708e9a..bc3a2b09600 100644 --- a/remote-tests/src/test/scala/org/apache/pekko/remote/classic/RemotingFailedToBindSpec.scala +++ b/remote-tests/src/test/scala/org/apache/pekko/remote/classic/RemotingFailedToBindSpec.scala @@ -47,9 +47,8 @@ class RemotingFailedToBindSpec extends AnyWordSpec with Matchers { ActorSystem("BindTest2", config) } ex.getMessage should startWith("Address already in use") - } finally { + } finally as.terminate() - } } } } diff --git a/remote-tests/src/test/scala/org/apache/pekko/remote/testkit/LogRoleReplace.scala b/remote-tests/src/test/scala/org/apache/pekko/remote/testkit/LogRoleReplace.scala index c278466d97c..a94bfb06c56 100644 --- a/remote-tests/src/test/scala/org/apache/pekko/remote/testkit/LogRoleReplace.scala +++ b/remote-tests/src/test/scala/org/apache/pekko/remote/testkit/LogRoleReplace.scala @@ -72,18 +72,17 @@ object LogRoleReplace extends ClipboardOwner { } else if (args.length == 1) { val inputFile = new BufferedReader(new FileReader(args(0))) - try { + try replacer.process(inputFile, new PrintWriter(new OutputStreamWriter(System.out))) - } finally { + finally inputFile.close() - } } else if (args.length == 2) { val outputFile = new PrintWriter(new FileWriter(args(1))) val inputFile = new BufferedReader(new FileReader(args(0))) - try { + try replacer.process(inputFile, outputFile) - } finally { + finally { outputFile.close() inputFile.close() } @@ -144,9 +143,8 @@ class LogRoleReplace { private def replaceLine(line: String): String = { var result = line - for ((from, to) <- replacements) { + for ((from, to) <- replacements) result = result.replaceAll(from, to) - } result } diff --git a/remote/src/main/scala/org/apache/pekko/remote/AckedDelivery.scala b/remote/src/main/scala/org/apache/pekko/remote/AckedDelivery.scala index f84c2c79166..528ca1b7991 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/AckedDelivery.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/AckedDelivery.scala @@ -176,11 +176,10 @@ final case class AckedReceiveBuffer[T <: HasSequenceNumber]( * @param arrivedMsg message to be put into the buffer. * @return The updated buffer containing the message. */ - def receive(arrivedMsg: T): AckedReceiveBuffer[T] = { + def receive(arrivedMsg: T): AckedReceiveBuffer[T] = this.copy( cumulativeAck = max(arrivedMsg.seq, cumulativeAck), buf = if (arrivedMsg.seq > lastDelivered && !buf.contains(arrivedMsg)) buf + arrivedMsg else buf) - } /** * Extract all messages that could be safely delivered, an updated ack to be sent to the sender(), and an updated @@ -226,8 +225,8 @@ final case class AckedReceiveBuffer[T <: HasSequenceNumber]( this.copy( lastDelivered = mergedLastDelivered, cumulativeAck = max(this.cumulativeAck, that.cumulativeAck), - buf = this.buf.union(that.buf).filter { _.seq > mergedLastDelivered }) + buf = this.buf.union(that.buf).filter(_.seq > mergedLastDelivered)) } - override def toString = buf.map { _.seq }.mkString("[", ", ", "]") + override def toString = buf.map(_.seq).mkString("[", ", ", "]") } diff --git a/remote/src/main/scala/org/apache/pekko/remote/AddressUidExtension.scala b/remote/src/main/scala/org/apache/pekko/remote/AddressUidExtension.scala index db4656a3f14..7366097cd58 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/AddressUidExtension.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/AddressUidExtension.scala @@ -50,11 +50,10 @@ class AddressUidExtension(val system: ExtendedActorSystem) extends Extension { else system.uid.toInt.toLong // private because GenJavaDoc fails on deprecated annotated lazy val - private lazy val _addressUid: Int = { + private lazy val _addressUid: Int = if (arteryEnabled) { throw new IllegalStateException("Int UID must never be used with Artery") } else longAddressUid.toInt - } // used by old remoting and part of public api @deprecated("Use longAddressUid instead", "Akka 2.4.x") diff --git a/remote/src/main/scala/org/apache/pekko/remote/ByteStringUtils.scala b/remote/src/main/scala/org/apache/pekko/remote/ByteStringUtils.scala index 4d4440e6b48..14d23b44643 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/ByteStringUtils.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/ByteStringUtils.scala @@ -26,7 +26,7 @@ import pekko.util.ByteString.ByteString1C */ @InternalApi private[pekko] object ByteStringUtils { - def toProtoByteStringUnsafe(bytes: ByteString): ProtoByteString = { + def toProtoByteStringUnsafe(bytes: ByteString): ProtoByteString = if (bytes.isEmpty) ProtoByteString.EMPTY else if (bytes.isInstanceOf[ByteString1C] || (bytes.isInstanceOf[ByteString1] && bytes.isCompact)) { @@ -37,13 +37,11 @@ private[pekko] object ByteStringUtils { acc.concat(UnsafeByteOperations.unsafeWrap(byteBuffer)) } } - } - def toProtoByteStringUnsafe(bytes: Array[Byte]): ProtoByteString = { + def toProtoByteStringUnsafe(bytes: Array[Byte]): ProtoByteString = if (bytes.isEmpty) ProtoByteString.EMPTY else { UnsafeByteOperations.unsafeWrap(bytes) } - } } diff --git a/remote/src/main/scala/org/apache/pekko/remote/DefaultFailureDetectorRegistry.scala b/remote/src/main/scala/org/apache/pekko/remote/DefaultFailureDetectorRegistry.scala index 0ebe935fdeb..0d634c1ca00 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/DefaultFailureDetectorRegistry.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/DefaultFailureDetectorRegistry.scala @@ -39,8 +39,7 @@ class DefaultFailureDetectorRegistry[A](detectorFactory: () => FailureDetector) case _ => false } - final override def heartbeat(resource: A): Unit = { - + final override def heartbeat(resource: A): Unit = resourceToFailureDetector.get.get(resource) match { case Some(failureDetector) => failureDetector.heartbeat() case None => @@ -67,7 +66,6 @@ class DefaultFailureDetectorRegistry[A](detectorFactory: () => FailureDetector) } } finally failureDetectorCreationLock.unlock() } - } @tailrec final override def remove(resource: A): Unit = { diff --git a/remote/src/main/scala/org/apache/pekko/remote/Endpoint.scala b/remote/src/main/scala/org/apache/pekko/remote/Endpoint.scala index 81f3c06d445..184215f1425 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/Endpoint.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/Endpoint.scala @@ -86,7 +86,7 @@ private[remote] class DefaultMessageDispatcher( val sender: ActorRef = senderOption.getOrElse(system.deadLetters) val originalReceiver = recipient.path - def logMessageReceived(messageType: String): Unit = { + def logMessageReceived(messageType: String): Unit = if (LogReceive && log.isDebugEnabled) log.debug( s"received $messageType RemoteMessage: [{}] to [{}]<+[{}] from [{}]", @@ -94,7 +94,6 @@ private[remote] class DefaultMessageDispatcher( recipient, originalReceiver, sender) - } recipient match { @@ -315,7 +314,7 @@ private[remote] class ReliableDeliverySupervisor( } var writer: ActorRef = createWriter() - var uid: Option[Int] = handleOrActive.map { _.handshakeInfo.uid } + var uid: Option[Int] = handleOrActive.map(_.handshakeInfo.uid) var bailoutAt: Option[Deadline] = None var maxSilenceTimer: Option[Cancellable] = None // Processing of Acks has to be delayed until the UID after a reconnect is discovered. Depending whether the @@ -349,10 +348,9 @@ private[remote] class ReliableDeliverySupervisor( maxSilenceTimer.foreach(_.cancel()) } - override def postRestart(reason: Throwable): Unit = { + override def postRestart(reason: Throwable): Unit = throw new IllegalStateException( "BUG: ReliableDeliverySupervisor has been attempted to be restarted. This must not happen.") - } override def receive: Receive = { case FlushAndStop => @@ -470,10 +468,10 @@ private[remote] class ReliableDeliverySupervisor( private def goToIdle(): Unit = { if (maxSilenceTimer.isEmpty && settings.QuarantineSilentSystemTimeout > Duration.Zero) { - try { + try maxSilenceTimer = Some( context.system.scheduler.scheduleOnce(settings.QuarantineSilentSystemTimeout, self, TooLongIdle)) - } catch { + catch { case e: IllegalArgumentException => log.warning( "Too long quarantine-after-silence configuration value, idle timer is not scheduled. " + @@ -510,21 +508,21 @@ private[remote] class ReliableDeliverySupervisor( writer ! sequencedSend } else writer ! send - private def resendNacked(): Unit = resendBuffer.nacked.foreach { writer ! _ } + private def resendNacked(): Unit = resendBuffer.nacked.foreach(writer ! _) private def resendAll(): Unit = { resendNacked() - resendBuffer.nonAcked.take(settings.SysResendLimit).foreach { writer ! _ } + resendBuffer.nonAcked.take(settings.SysResendLimit).foreach(writer ! _) } private def tryBuffer(s: Send): Unit = - try { + try resendBuffer = resendBuffer.buffer(s) - } catch { + catch { case NonFatal(e) => throw new HopelessAssociation(localAddress, remoteAddress, uid, e) } - private def createWriter(): ActorRef = { + private def createWriter(): ActorRef = context.watch( context.actorOf( RARP(context.system) @@ -540,7 +538,6 @@ private[remote] class ReliableDeliverySupervisor( reliableDeliverySupervisor = Some(self))) .withDeploy(Deploy.local), "endpointWriter")) - } } /** @@ -691,14 +688,13 @@ private[remote] class EndpointWriter( context.system.scheduler.scheduleWithFixedDelay(interval, interval, self, AckIdleCheckTimer) } - override def preStart(): Unit = { + override def preStart(): Unit = handle match { case Some(h) => reader = startReadEndpoint(h) case None => transport.associate(remoteAddress, refuseUid).map(Handle(_)).pipeTo(self) } - } override def postRestart(reason: Throwable): Unit = throw new IllegalStateException("EndpointWriter must not be restarted") @@ -707,7 +703,7 @@ private[remote] class EndpointWriter( ackIdleTimer.cancel() while (!prioBuffer.isEmpty) extendedSystem.deadLetters ! prioBuffer.poll while (!buffer.isEmpty) extendedSystem.deadLetters ! buffer.poll - handle.foreach { _.disassociate(stopReason) } + handle.foreach(_.disassociate(stopReason)) eventPublisher.notifyListeners(DisassociatedEvent(localAddress, remoteAddress, inbound)) } @@ -848,7 +844,7 @@ private[remote] class EndpointWriter( } - def scheduleBackoffTimer(): Unit = { + def scheduleBackoffTimer(): Unit = if (fullBackoff) { fullBackoffCount += 1 fullBackoff = false @@ -870,7 +866,6 @@ private[remote] class EndpointWriter( s.tell(BackoffTimer, ActorRef.noSender) }(backoffDispatcher) } - } val writing: Receive = { case s: Send => @@ -889,7 +884,7 @@ private[remote] class EndpointWriter( } def writeSend(s: Send): Boolean = - try { + try handle match { case Some(h) => if (provider.remoteSettings.LogSend && log.isDebugEnabled) { @@ -935,7 +930,7 @@ private[remote] class EndpointWriter( throw new EndpointException( "Internal error: Endpoint is in state Writing, but no association handle is present.") } - } catch { + catch { case e: NotSerializableException => log.error( e, @@ -985,7 +980,7 @@ private[remote] class EndpointWriter( } case TakeOver(newHandle, replyTo) => // Shutdown old reader - handle.foreach { _.disassociate("the association was replaced by a new one", log) } + handle.foreach(_.disassociate("the association was replaced by a new one", log)) handle = Some(newHandle) replyTo ! TookOver(self, newHandle) context.become(handoff) @@ -1010,12 +1005,11 @@ private[remote] class EndpointWriter( } private def trySendPureAck(): Unit = - for (h <- handle; ack <- lastAck) { + for (h <- handle; ack <- lastAck) if (h.write(codec.constructPureAck(ack))) { ackDeadline = newAckDeadline lastAck = None } - } private def startReadEndpoint(handle: PekkoProtocolHandle): Some[ActorRef] = { val newReader = @@ -1105,7 +1099,7 @@ private[remote] class EndpointReader( val provider = RARP(context.system).provider var ackedReceiveBuffer = new AckedReceiveBuffer[Message] - override def preStart(): Unit = { + override def preStart(): Unit = receiveBuffers.get(Link(localAddress, remoteAddress)) match { case null => case ResendState(`uid`, buffer) => @@ -1113,7 +1107,6 @@ private[remote] class EndpointReader( deliverAndAck() case _ => } - } override def postStop(): Unit = saveState() @@ -1123,7 +1116,7 @@ private[remote] class EndpointReader( else currentState @tailrec - def updateSavedState(key: Link, expectedState: ResendState): Unit = { + def updateSavedState(key: Link, expectedState: ResendState): Unit = if (expectedState eq null) { if (receiveBuffers.putIfAbsent(key, ResendState(uid, ackedReceiveBuffer)) ne null) updateSavedState(key, receiveBuffers.get(key)) @@ -1132,7 +1125,6 @@ private[remote] class EndpointReader( expectedState, merge(ResendState(uid, ackedReceiveBuffer), expectedState))) updateSavedState(key, receiveBuffers.get(key)) - } val key = Link(localAddress, remoteAddress) updateSavedState(key, receiveBuffers.get(key)) @@ -1243,9 +1235,9 @@ private[remote] class EndpointReader( } private def tryDecodeMessageAndAck(pdu: ByteString): (Option[Ack], Option[Message]) = - try { + try codec.decodeMessage(pdu, provider, localAddress) - } catch { + catch { case NonFatal(e) => throw new EndpointException("Error while decoding incoming Pekko PDU", e) } } diff --git a/remote/src/main/scala/org/apache/pekko/remote/FailureDetectorRegistry.scala b/remote/src/main/scala/org/apache/pekko/remote/FailureDetectorRegistry.scala index b006f7844aa..9f751f1a170 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/FailureDetectorRegistry.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/FailureDetectorRegistry.scala @@ -75,7 +75,7 @@ private[pekko] object FailureDetectorLoader { * @param system ActorSystem to be used for loading the implementation * @return A configured instance of the given [[FailureDetector]] implementation */ - def load(fqcn: String, config: Config, system: ActorSystem): FailureDetector = { + def load(fqcn: String, config: Config, system: ActorSystem): FailureDetector = system .asInstanceOf[ExtendedActorSystem] .dynamicAccess @@ -87,7 +87,6 @@ private[pekko] object FailureDetectorLoader { throw new ConfigurationException(s"Could not create custom failure detector [$fqcn] due to: ${e.toString}", e) } .get - } /** * Loads and instantiates a given [[FailureDetector]] implementation. The class to be loaded must have a constructor diff --git a/remote/src/main/scala/org/apache/pekko/remote/MessageSerializer.scala b/remote/src/main/scala/org/apache/pekko/remote/MessageSerializer.scala index c6373019484..15e5527f42b 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/MessageSerializer.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/MessageSerializer.scala @@ -36,14 +36,13 @@ private[pekko] object MessageSerializer { /** * Uses Pekko Serialization for the specified ActorSystem to transform the given MessageProtocol to a message */ - def deserialize(system: ExtendedActorSystem, messageProtocol: SerializedMessage): AnyRef = { + def deserialize(system: ExtendedActorSystem, messageProtocol: SerializedMessage): AnyRef = SerializationExtension(system) .deserialize( messageProtocol.getMessage.toByteArray, messageProtocol.getSerializerId, if (messageProtocol.hasMessageManifest) messageProtocol.getMessageManifest.toStringUtf8 else "") .get - } /** * Uses Pekko Serialization for the specified ActorSystem to transform the given message to a MessageProtocol @@ -107,7 +106,6 @@ private[pekko] object MessageSerializer { serialization: Serialization, serializer: Int, classManifest: String, - envelope: EnvelopeBuffer): AnyRef = { + envelope: EnvelopeBuffer): AnyRef = serialization.deserializeByteBuffer(envelope.byteBuffer, serializer, classManifest) - } } diff --git a/remote/src/main/scala/org/apache/pekko/remote/PhiAccrualFailureDetector.scala b/remote/src/main/scala/org/apache/pekko/remote/PhiAccrualFailureDetector.scala index 6493c606faa..e4b8d1745a1 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/PhiAccrualFailureDetector.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/PhiAccrualFailureDetector.scala @@ -270,7 +270,7 @@ private[pekko] final case class HeartbeatHistory private ( def stdDeviation: Double = math.sqrt(variance) @tailrec - final def :+(interval: Long): HeartbeatHistory = { + final def :+(interval: Long): HeartbeatHistory = if (intervals.size < maxSampleSize) HeartbeatHistory( maxSampleSize, @@ -279,7 +279,6 @@ private[pekko] final case class HeartbeatHistory private ( squaredIntervalSum = squaredIntervalSum + pow2(interval)) else dropOldest :+ interval // recur - } private def dropOldest: HeartbeatHistory = HeartbeatHistory( diff --git a/remote/src/main/scala/org/apache/pekko/remote/RemoteActorRefProvider.scala b/remote/src/main/scala/org/apache/pekko/remote/RemoteActorRefProvider.scala index ea877ecd9fe..1f31f4ea430 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/RemoteActorRefProvider.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/RemoteActorRefProvider.scala @@ -278,14 +278,13 @@ private[pekko] class RemoteActorRefProvider( remoteDeploymentWatcher = createOrNone[ActorRef](createRemoteDeploymentWatcher(system)) } - private def checkNettyOnClassPath(system: ActorSystemImpl): Unit = { + private def checkNettyOnClassPath(system: ActorSystemImpl): Unit = checkClassOrThrow( system, "io.netty.channel.Channel", "Classic", "Netty", "https://pekko.apache.org/docs/pekko/current/remoting.html") - } private def checkAeronOnClassPath(system: ActorSystemImpl): Unit = { val arteryLink = "https://pekko.apache.org/docs/pekko/current/remoting-artery.html" @@ -299,14 +298,13 @@ private[pekko] class RemoteActorRefProvider( className: String, remoting: String, libraryMissing: String, - link: String): Unit = { + link: String): Unit = system.dynamicAccess.getClassFor[Any](className) match { case Failure(_: ClassNotFoundException | _: NoClassDefFoundError) => throw new IllegalStateException( s"$remoting remoting is enabled but $libraryMissing is not on the classpath, it must be added explicitly. See $link") case _ => } - } /** Will call the provided `func` if using Cluster or explicitly enabled unsafe remote features. */ private def createOrNone[T](func: => T): Option[T] = if (hasClusterOrUseUnsafe) Some(func) else None @@ -334,13 +332,12 @@ private[pekko] class RemoteActorRefProvider( "remote-deployment-watcher") /** Can be overridden when using RemoteActorRefProvider as a superclass rather than directly */ - protected def warnIfDirectUse(): Unit = { + protected def warnIfDirectUse(): Unit = if (remoteSettings.WarnAboutDirectUse) { log.warning( "Using the 'remote' ActorRefProvider directly, which is a low-level layer. " + "For most use cases, the 'cluster' abstraction on top of remoting is more suitable instead.") } - } // Log on `init` similar to `warnIfDirectUse`. private[pekko] def warnIfUseUnsafeWithoutCluster(): Unit = @@ -414,14 +411,13 @@ private[pekko] class RemoteActorRefProvider( */ @scala.annotation.tailrec - def lookupRemotes(p: Iterable[String]): Option[Deploy] = { + def lookupRemotes(p: Iterable[String]): Option[Deploy] = p.headOption match { case None => None case Some("remote") => lookupRemotes(p.drop(3)) case Some("user") => deployer.lookup(p.drop(1)) case Some(_) => None } - } val elems = path.elements val lookup = @@ -433,12 +429,11 @@ private[pekko] class RemoteActorRefProvider( } else None - val deployment = { + val deployment = deploy.toList ::: lookup.toList match { case Nil => Nil case l => List(l.reduce((a, b) => b.withFallback(a))) } - } (Iterator(props.deploy) ++ deployment.iterator).reduce((a, b) => b.withFallback(a)) match { case d @ Deploy(_, _, _, RemoteScope(address), _, _) => @@ -448,7 +443,7 @@ private[pekko] class RemoteActorRefProvider( throw new ConfigurationException( s"${ErrorMessages.RemoteDeploymentConfigErrorPrefix} for local-only Props at [$path]") } else - try { + try if (hasClusterOrUseUnsafe && shouldCreateRemoteActorRef(system, address)) { try { // for consistency we check configuration of dispatcher and mailbox locally @@ -471,7 +466,7 @@ private[pekko] class RemoteActorRefProvider( local.actorOf(system, props, supervisor, path, systemService, deployment.headOption, false, async) } - } catch { + catch { case NonFatal(e) => throw new IllegalArgumentException(s"remote deployment failed for [$path]", e) } case _ => @@ -479,10 +474,10 @@ private[pekko] class RemoteActorRefProvider( } } - def rootGuardianAt(address: Address): ActorRef = { + def rootGuardianAt(address: Address): ActorRef = if (hasAddress(address)) rootGuardian else - try { + try new RemoteActorRef( transport, transport.localAddressForRemote(address), @@ -491,24 +486,23 @@ private[pekko] class RemoteActorRefProvider( props = None, deploy = None, acceptProtocolNames = remoteSettings.AcceptProtocolNames) - } catch { + catch { case NonFatal(e) => log.error(e, "No root guardian at [{}]", address) new EmptyLocalActorRef(this, RootActorPath(address), eventStream) } - } /** * INTERNAL API * Called in deserialization of incoming remote messages where the correct local address is known. */ - private[pekko] def resolveActorRefWithLocalAddress(path: String, localAddress: Address): InternalActorRef = { + private[pekko] def resolveActorRefWithLocalAddress(path: String, localAddress: Address): InternalActorRef = path match { case ActorPathExtractor(address, elems) => if (hasAddress(address)) local.resolveActorRef(rootGuardian, elems) else - try { + try new RemoteActorRef( transport, localAddress, @@ -517,7 +511,7 @@ private[pekko] class RemoteActorRefProvider( props = None, deploy = None, acceptProtocolNames = remoteSettings.AcceptProtocolNames) - } catch { + catch { case NonFatal(e) => log.warning("Error while resolving ActorRef [{}] due to [{}]", path, e.getMessage) new EmptyLocalActorRef(this, RootActorPath(address) / elems, eventStream) @@ -526,9 +520,8 @@ private[pekko] class RemoteActorRefProvider( log.debug("Resolve (deserialization) of unknown (invalid) path [{}], using deadLetters.", path) deadLetters } - } - def resolveActorRef(path: String): ActorRef = { + def resolveActorRef(path: String): ActorRef = // using thread local LRU cache, which will call internalResolveActorRef // if the value is not cached actorRefResolveThreadLocalCache match { @@ -537,7 +530,6 @@ private[pekko] class RemoteActorRefProvider( case c => c.threadLocalCache(this).resolve(path) } - } /** * INTERNAL API: This is used by the `ActorRefResolveCache` via the @@ -551,7 +543,7 @@ private[pekko] class RemoteActorRefProvider( if (hasAddress(address)) local.resolveActorRef(rootGuardian, elems) else { val rootPath = RootActorPath(address) / elems - try { + try new RemoteActorRef( transport, transport.localAddressForRemote(address), @@ -560,7 +552,7 @@ private[pekko] class RemoteActorRefProvider( props = None, deploy = None, acceptProtocolNames = remoteSettings.AcceptProtocolNames) - } catch { + catch { case NonFatal(e) => log.warning("Error while resolving ActorRef [{}] due to [{}]", path, e.getMessage) new EmptyLocalActorRef(this, rootPath, eventStream) @@ -572,10 +564,10 @@ private[pekko] class RemoteActorRefProvider( deadLetters } - def resolveActorRef(path: ActorPath): ActorRef = { + def resolveActorRef(path: ActorPath): ActorRef = if (hasAddress(path.address)) local.resolveActorRef(rootGuardian, path.elements) else - try { + try new RemoteActorRef( transport, transport.localAddressForRemote(path.address), @@ -584,12 +576,11 @@ private[pekko] class RemoteActorRefProvider( props = None, deploy = None, acceptProtocolNames = remoteSettings.AcceptProtocolNames) - } catch { + catch { case NonFatal(e) => log.warning("Error while resolving ActorRef [{}] due to [{}]", path, e.getMessage) new EmptyLocalActorRef(this, path, eventStream) } - } /** * Using (checking out) actor on a specific node. @@ -609,7 +600,7 @@ private[pekko] class RemoteActorRefProvider( case None => warnIfUseUnsafeWithoutCluster() } - def getExternalAddressFor(addr: Address): Option[Address] = { + def getExternalAddressFor(addr: Address): Option[Address] = addr match { case _ if hasAddress(addr) => Some(local.rootPath.address) case Address(_, _, Some(_), Some(_)) => @@ -617,7 +608,6 @@ private[pekko] class RemoteActorRefProvider( catch { case NonFatal(_) => None } case _ => None } - } def getDefaultAddress: Address = transport.defaultAddress @@ -652,14 +642,13 @@ private[pekko] class RemoteActorRefProvider( // lazily initialized with fallback since it can depend on transport which is not initialized up front // worth caching since if it is used once in a system it will very likely be used many times @volatile private var _addressString: OptionVal[String] = OptionVal.None - override private[pekko] def addressString: String = { + override private[pekko] def addressString: String = _addressString match { case OptionVal.Some(addr) => addr case _ => // not initialized yet, fallback local.addressString } - } } private[pekko] trait RemoteRef extends ActorRefScope { @@ -731,14 +720,13 @@ private[pekko] class RemoteActorRef private[pekko] ( /** * Determine if a watch/unwatch message must be handled by the remoteWatcher actor, or sent to this remote ref */ - def isWatchIntercepted(watchee: ActorRef, watcher: ActorRef): Boolean = { + def isWatchIntercepted(watchee: ActorRef, watcher: ActorRef): Boolean = // If watchee != this then watcher should == this. This is a reverse watch, and it is not intercepted // If watchee == this, only the watches from remoteWatcher are sent on the wire, on behalf of other watchers provider.remoteWatcher.exists(remoteWatcher => watcher != remoteWatcher) && watchee == this - } def sendSystemMessage(message: SystemMessage): Unit = - try { + try // send to remote, unless watch message is intercepted by the remoteWatcher message match { case Watch(watchee, watcher) => @@ -759,7 +747,7 @@ private[pekko] class RemoteActorRef private[pekko] ( case _ => remote.send(message, OptionVal.None, this) } - } catch handleException(message, Actor.noSender) + catch handleException(message, Actor.noSender) override def !(message: Any)(implicit sender: ActorRef = Actor.noSender): Unit = { if (message == null) throw InvalidMessageException("Message is null") diff --git a/remote/src/main/scala/org/apache/pekko/remote/RemoteDaemon.scala b/remote/src/main/scala/org/apache/pekko/remote/RemoteDaemon.scala index 524c6878928..6bec1f17097 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/RemoteDaemon.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/RemoteDaemon.scala @@ -101,7 +101,7 @@ private[pekko] class RemoteSystemDaemon( else addChildParentNeedsWatch(parent, child) } - @tailrec private def removeChildParentNeedsUnwatch(parent: ActorRef, child: ActorRef): Boolean = { + @tailrec private def removeChildParentNeedsUnwatch(parent: ActorRef, child: ActorRef): Boolean = parent2children.get(parent) match { case null => false // no-op case children => @@ -114,7 +114,6 @@ private[pekko] class RemoteSystemDaemon( else false } } - } /** * Find the longest matching path which we know about and return that ref @@ -226,7 +225,7 @@ private[pekko] class RemoteSystemDaemon( case TerminationHook => terminating.switchOn { terminationHookDoneWhenNoChildren() - foreachChild { system.stop } + foreachChild(system.stop) } case AddressTerminated(address) => @@ -242,7 +241,7 @@ private[pekko] class RemoteSystemDaemon( case NonFatal(e) => log.error(e, "exception while processing remote command [{}] from [{}]", msg, sender) } - private def doCreateActor(message: DaemonMsg, props: Props, deploy: Deploy, path: String, supervisor: ActorRef) = { + private def doCreateActor(message: DaemonMsg, props: Props, deploy: Deploy, path: String, supervisor: ActorRef) = path match { case ActorPathExtractor(_, elems) if elems.nonEmpty && elems.head == "remote" => // TODO RK currently the extracted “address” is just ignored, is that okay? @@ -276,7 +275,6 @@ private[pekko] class RemoteSystemDaemon( case _ => log.debug("remote path does not match path from message [{}]", message) } - } def terminationHookDoneWhenNoChildren(): Unit = terminating.whileOn { if (!hasChildren) terminator.tell(TerminationHookDone, this) diff --git a/remote/src/main/scala/org/apache/pekko/remote/RemoteDeployer.scala b/remote/src/main/scala/org/apache/pekko/remote/RemoteDeployer.scala index d23c44eeda4..eaef8ebf372 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/RemoteDeployer.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/RemoteDeployer.scala @@ -33,8 +33,7 @@ final case class RemoteScope(node: Address) extends Scope { */ private[pekko] class RemoteDeployer(_settings: ActorSystem.Settings, _pm: DynamicAccess) extends Deployer(_settings, _pm) { - override def parseConfig(path: String, config: Config): Option[Deploy] = { - + override def parseConfig(path: String, config: Config): Option[Deploy] = super.parseConfig(path, config) match { case d @ Some(deploy) => deploy.config.getString("remote") match { @@ -51,5 +50,4 @@ private[pekko] class RemoteDeployer(_settings: ActorSystem.Settings, _pm: Dynami } case None => None } - } } diff --git a/remote/src/main/scala/org/apache/pekko/remote/RemoteSettings.scala b/remote/src/main/scala/org/apache/pekko/remote/RemoteSettings.scala index f106284ca56..7b6fd79e2e1 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/RemoteSettings.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/RemoteSettings.scala @@ -46,10 +46,9 @@ final class RemoteSettings(val config: Config) { val LogSend: Boolean = getBoolean("pekko.remote.classic.log-sent-messages") @deprecated("Classic remoting is deprecated, use Artery", "Akka 2.6.0") - val LogFrameSizeExceeding: Option[Int] = { + val LogFrameSizeExceeding: Option[Int] = if (config.getString("pekko.remote.classic.log-frame-size-exceeding").toLowerCase == "off") None else Some(getBytes("pekko.remote.classic.log-frame-size-exceeding").toInt) - } @deprecated("Classic remoting is deprecated, use Artery", "Akka 2.6.0") val UntrustedMode: Boolean = getBoolean("pekko.remote.classic.untrusted-mode") @@ -88,32 +87,32 @@ final class RemoteSettings(val config: Config) { } @deprecated("Classic remoting is deprecated, use Artery", "Akka 2.6.0") - val ShutdownTimeout: Timeout = { + val ShutdownTimeout: Timeout = Timeout(config.getMillisDuration("pekko.remote.classic.shutdown-timeout")) - }.requiring(_.duration > Duration.Zero, "shutdown-timeout must be > 0") + .requiring(_.duration > Duration.Zero, "shutdown-timeout must be > 0") @deprecated("Classic remoting is deprecated, use Artery", "Akka 2.6.0") - val FlushWait: FiniteDuration = { + val FlushWait: FiniteDuration = config.getMillisDuration("pekko.remote.classic.flush-wait-on-shutdown") - }.requiring(_ > Duration.Zero, "flush-wait-on-shutdown must be > 0") + .requiring(_ > Duration.Zero, "flush-wait-on-shutdown must be > 0") @deprecated("Classic remoting is deprecated, use Artery", "Akka 2.6.0") - val StartupTimeout: Timeout = { + val StartupTimeout: Timeout = Timeout(config.getMillisDuration("pekko.remote.classic.startup-timeout")) - }.requiring(_.duration > Duration.Zero, "startup-timeout must be > 0") + .requiring(_.duration > Duration.Zero, "startup-timeout must be > 0") @deprecated("Classic remoting is deprecated, use Artery", "Akka 2.6.0") - val RetryGateClosedFor: FiniteDuration = { + val RetryGateClosedFor: FiniteDuration = config.getMillisDuration("pekko.remote.classic.retry-gate-closed-for") - }.requiring(_ >= Duration.Zero, "retry-gate-closed-for must be >= 0") + .requiring(_ >= Duration.Zero, "retry-gate-closed-for must be >= 0") @deprecated("Classic remoting is deprecated, use Artery", "Akka 2.6.0") val UsePassiveConnections: Boolean = getBoolean("pekko.remote.classic.use-passive-connections") @deprecated("Classic remoting is deprecated, use Artery", "Akka 2.6.0") - val BackoffPeriod: FiniteDuration = { + val BackoffPeriod: FiniteDuration = config.getMillisDuration("pekko.remote.classic.backoff-interval") - }.requiring(_ > Duration.Zero, "backoff-interval must be > 0") + .requiring(_ > Duration.Zero, "backoff-interval must be > 0") @deprecated("Classic remoting is deprecated, use Artery", "Akka 2.6.0") val LogBufferSizeExceeding: Int = { @@ -125,29 +124,29 @@ final class RemoteSettings(val config: Config) { } @deprecated("Classic remoting is deprecated, use Artery", "Akka 2.6.0") - val SysMsgAckTimeout: FiniteDuration = { + val SysMsgAckTimeout: FiniteDuration = config.getMillisDuration("pekko.remote.classic.system-message-ack-piggyback-timeout") - }.requiring(_ > Duration.Zero, "system-message-ack-piggyback-timeout must be > 0") + .requiring(_ > Duration.Zero, "system-message-ack-piggyback-timeout must be > 0") @deprecated("Classic remoting is deprecated, use Artery", "Akka 2.6.0") - val SysResendTimeout: FiniteDuration = { + val SysResendTimeout: FiniteDuration = config.getMillisDuration("pekko.remote.classic.resend-interval") - }.requiring(_ > Duration.Zero, "resend-interval must be > 0") + .requiring(_ > Duration.Zero, "resend-interval must be > 0") @deprecated("Classic remoting is deprecated, use Artery", "Akka 2.6.0") - val SysResendLimit: Int = { + val SysResendLimit: Int = config.getInt("pekko.remote.classic.resend-limit") - }.requiring(_ > 0, "resend-limit must be > 0") + .requiring(_ > 0, "resend-limit must be > 0") @deprecated("Classic remoting is deprecated, use Artery", "Akka 2.6.0") - val SysMsgBufferSize: Int = { + val SysMsgBufferSize: Int = getInt("pekko.remote.classic.system-message-buffer-size") - }.requiring(_ > 0, "system-message-buffer-size must be > 0") + .requiring(_ > 0, "system-message-buffer-size must be > 0") @deprecated("Classic remoting is deprecated, use Artery", "Akka 2.6.0") - val InitialSysMsgDeliveryTimeout: FiniteDuration = { + val InitialSysMsgDeliveryTimeout: FiniteDuration = config.getMillisDuration("pekko.remote.classic.initial-system-message-delivery-timeout") - }.requiring(_ > Duration.Zero, "initial-system-message-delivery-timeout must be > 0") + .requiring(_ > Duration.Zero, "initial-system-message-delivery-timeout must be > 0") @deprecated("Classic remoting is deprecated, use Artery", "Akka 2.6.0") val QuarantineSilentSystemTimeout: FiniteDuration = { @@ -160,16 +159,15 @@ final class RemoteSettings(val config: Config) { } @deprecated("Classic remoting is deprecated, use Artery", "Akka 2.6.0") - val QuarantineDuration: FiniteDuration = { + val QuarantineDuration: FiniteDuration = config .getMillisDuration("pekko.remote.classic.prune-quarantine-marker-after") .requiring(_ > Duration.Zero, "prune-quarantine-marker-after must be > 0 ms") - } @deprecated("Classic remoting is deprecated, use Artery", "Akka 2.6.0") - val CommandAckTimeout: Timeout = { + val CommandAckTimeout: Timeout = Timeout(config.getMillisDuration("pekko.remote.classic.command-ack-timeout")) - }.requiring(_.duration > Duration.Zero, "command-ack-timeout must be > 0") + .requiring(_.duration > Duration.Zero, "command-ack-timeout must be > 0") val UseUnsafeRemoteFeaturesWithoutCluster: Boolean = getBoolean( "pekko.remote.use-unsafe-remote-features-outside-cluster") @@ -178,15 +176,15 @@ final class RemoteSettings(val config: Config) { val WatchFailureDetectorConfig: Config = getConfig("pekko.remote.watch-failure-detector") val WatchFailureDetectorImplementationClass: String = WatchFailureDetectorConfig.getString("implementation-class") - val WatchHeartBeatInterval: FiniteDuration = { + val WatchHeartBeatInterval: FiniteDuration = WatchFailureDetectorConfig.getMillisDuration("heartbeat-interval") - }.requiring(_ > Duration.Zero, "watch-failure-detector.heartbeat-interval must be > 0") - val WatchUnreachableReaperInterval: FiniteDuration = { + .requiring(_ > Duration.Zero, "watch-failure-detector.heartbeat-interval must be > 0") + val WatchUnreachableReaperInterval: FiniteDuration = WatchFailureDetectorConfig.getMillisDuration("unreachable-nodes-reaper-interval") - }.requiring(_ > Duration.Zero, "watch-failure-detector.unreachable-nodes-reaper-interval must be > 0") - val WatchHeartbeatExpectedResponseAfter: FiniteDuration = { + .requiring(_ > Duration.Zero, "watch-failure-detector.unreachable-nodes-reaper-interval must be > 0") + val WatchHeartbeatExpectedResponseAfter: FiniteDuration = WatchFailureDetectorConfig.getMillisDuration("expected-response-after") - }.requiring(_ > Duration.Zero, "watch-failure-detector.expected-response-after > 0") + .requiring(_ > Duration.Zero, "watch-failure-detector.expected-response-after > 0") val Transports: immutable.Seq[(String, immutable.Seq[String], Config)] = transportNames.map { name => val transportConfig = transportConfigFor(name) diff --git a/remote/src/main/scala/org/apache/pekko/remote/RemoteTransport.scala b/remote/src/main/scala/org/apache/pekko/remote/RemoteTransport.scala index 6c0b39eb08d..42b42591ca6 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/RemoteTransport.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/RemoteTransport.scala @@ -93,7 +93,7 @@ private[pekko] abstract class RemoteTransport(val system: ExtendedActorSystem, v * @param cmd Command message to send to the transports. * @return A Future that indicates when the message was successfully handled or dropped. */ - def managementCommand(@unused cmd: Any): Future[Boolean] = { Future.successful(false) } + def managementCommand(@unused cmd: Any): Future[Boolean] = Future.successful(false) /** * A Logger that can be used to log issues that may occur diff --git a/remote/src/main/scala/org/apache/pekko/remote/RemoteWatcher.scala b/remote/src/main/scala/org/apache/pekko/remote/RemoteWatcher.scala index f283c1c6c7a..ef1f93d308c 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/RemoteWatcher.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/RemoteWatcher.scala @@ -209,22 +209,20 @@ private[pekko] class RemoteWatcher( AddressTerminatedTopic(context.system).publish(AddressTerminated(address)) } - def quarantine(address: Address, uid: Option[Long], reason: String, harmless: Boolean): Unit = { + def quarantine(address: Address, uid: Option[Long], reason: String, harmless: Boolean): Unit = remoteProvider.transport match { case t: ArteryTransport if harmless => t.quarantine(address, uid, reason, harmless) case _ => remoteProvider.quarantine(address, uid, reason) } - } /** * Returns true if either has cluster or `pekko.remote.use-unsafe-remote-features-outside-cluster` * is enabled. Can be overridden when using RemoteWatcher as a superclass. */ - protected def shouldWatch(@unused watchee: InternalActorRef): Boolean = { + protected def shouldWatch(@unused watchee: InternalActorRef): Boolean = // In this it is unnecessary if only created by RARP, but cluster needs it. // Cleaner than overriding Cluster watcher addWatch/removeWatch just for one boolean test remoteProvider.remoteSettings.UseUnsafeRemoteFeaturesWithoutCluster - } def addWatch(watchee: InternalActorRef, watcher: InternalActorRef): Unit = { assert(watcher != self) diff --git a/remote/src/main/scala/org/apache/pekko/remote/Remoting.scala b/remote/src/main/scala/org/apache/pekko/remote/Remoting.scala index 85812471143..1c0901c868f 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/Remoting.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/Remoting.scala @@ -95,8 +95,7 @@ private[remote] object Remoting { def localAddressForRemote( transportMapping: Map[String, Set[(PekkoProtocolTransport, Address)]], - remote: Address): Address = { - + remote: Address): Address = transportMapping.get(remote.protocol) match { case Some(transports) => val responsibleTransports = transports.filter { case (t, _) => t.isResponsibleFor(remote) } @@ -124,7 +123,6 @@ private[remote] object Remoting { .mkString(", ")}]", null) } - } final case class RegisterTransportActor(props: Props, name: String) extends NoSerializationVerificationNeeded @@ -173,7 +171,7 @@ private[remote] class Remoting(_system: ExtendedActorSystem, _provider: RemoteAc private def notifyError(msg: String, cause: Throwable): Unit = eventPublisher.notifyListeners(RemotingErrorEvent(new RemoteTransportException(msg, cause))) - override def shutdown(): Future[Done] = { + override def shutdown(): Future[Done] = endpointManager match { case Some(manager) => implicit val timeout = ShutdownTimeout @@ -204,10 +202,9 @@ private[remote] class Remoting(_system: ExtendedActorSystem, _provider: RemoteAc log.warning("Remoting is not running. Ignoring shutdown attempt.") Future.successful(Done) } - } // Start assumes that it cannot be followed by another start() without having a shutdown() first - override def start(): Unit = { + override def start(): Unit = endpointManager match { case None => log.info("Starting remoting") @@ -232,7 +229,7 @@ private[remote] class Remoting(_system: ExtendedActorSystem, _provider: RemoteAc .map { case (k, v) => k -> v.toSet } defaultAddress = transports.head._2 - addresses = transports.map { _._2 }.toSet + addresses = transports.map(_._2).toSet log.info("Remoting started; listening on addresses :" + addresses.mkString("[", ", ", "]")) @@ -253,7 +250,6 @@ private[remote] class Remoting(_system: ExtendedActorSystem, _provider: RemoteAc case Some(_) => log.warning("Remoting was already started. Ignoring start attempt.") } - } override def send(message: Any, senderOption: OptionVal[ActorRef], recipient: RemoteActorRef): Unit = endpointManager match { @@ -287,7 +283,7 @@ private[remote] class Remoting(_system: ExtendedActorSystem, _provider: RemoteAc null) } - private[pekko] def boundAddresses: Map[String, Set[Address]] = { + private[pekko] def boundAddresses: Map[String, Set[Address]] = transportMapping.map { case (scheme, transports) => scheme -> transports.flatMap { @@ -295,7 +291,6 @@ private[remote] class Remoting(_system: ExtendedActorSystem, _provider: RemoteAc case (t, _) => Option(t.boundAddress) } } - } } /** @@ -378,16 +373,14 @@ private[remote] object EndpointManager { endpoint } - def registerWritableEndpointUid(remoteAddress: Address, uid: Int): Unit = { + def registerWritableEndpointUid(remoteAddress: Address, uid: Int): Unit = addressToWritable.get(remoteAddress) match { case Some(Pass(ep, _)) => addressToWritable += remoteAddress -> Pass(ep, Some(uid)) case _ => } - } - def registerWritableEndpointRefuseUid(remoteAddress: Address, refuseUid: Int, timeOfRelease: Deadline): Unit = { + def registerWritableEndpointRefuseUid(remoteAddress: Address, refuseUid: Int, timeOfRelease: Deadline): Unit = addressToRefuseUid = addressToRefuseUid.updated(remoteAddress, (refuseUid, timeOfRelease)) - } def registerReadOnlyEndpoint(address: Address, endpoint: ActorRef, uid: Int): ActorRef = { addressToReadonly += address -> ((endpoint, uid)) @@ -620,7 +613,7 @@ private[remote] class EndpointManager(conf: Config, log: LoggingAdapter) def receive = { case Listen(addressesPromise) => listens - .map { ListensResult(addressesPromise, _) } + .map(ListensResult(addressesPromise, _)) .recover { case NonFatal(e) => ListensFailure(addressesPromise, e) } @@ -705,10 +698,9 @@ private[remote] class EndpointManager(conf: Config, log: LoggingAdapter) case _ => // nothing to stop } - def matchesQuarantine(handle: PekkoProtocolHandle): Boolean = { + def matchesQuarantine(handle: PekkoProtocolHandle): Boolean = handle.remoteAddress == address && uidToQuarantineOption.forall(_ == handle.handshakeInfo.uid) - } // Stop all matching pending read handoffs pendingReadHandoffs = pendingReadHandoffs.filter { @@ -736,7 +728,7 @@ private[remote] class EndpointManager(conf: Config, log: LoggingAdapter) case s @ Send(_, _, recipientRef, _) => val recipientAddress = recipientRef.path.address - def createAndRegisterWritingEndpoint(): ActorRef = { + def createAndRegisterWritingEndpoint(): ActorRef = endpoints.registerWritableEndpoint( recipientAddress, uid = None, @@ -747,7 +739,6 @@ private[remote] class EndpointManager(conf: Config, log: LoggingAdapter) settings, handleOption = None, writing = true)) - } endpoints.writableEndpointWithPolicyFor(recipientAddress) match { case Some(Pass(endpoint, _)) => @@ -794,11 +785,10 @@ private[remote] class EndpointManager(conf: Config, log: LoggingAdapter) // Shutdown all endpoints and signal to sender() when ready (and whether all endpoints were shut down gracefully) @nowarn("msg=deprecated") - def shutdownAll[T](resources: IterableOnce[T])(shutdown: T => Future[Boolean]): Future[Boolean] = { + def shutdownAll[T](resources: IterableOnce[T])(shutdown: T => Future[Boolean]): Future[Boolean] = Future.sequence(resources.toList.map(shutdown)).map(_.forall(identity)).recover { case NonFatal(_) => false } - } (for { // The construction of the future for shutdownStatus has to happen after the flushStatus future has been finished @@ -924,7 +914,7 @@ private[remote] class EndpointManager(conf: Config, log: LoggingAdapter) // The chain at this point: // Adapter <- ... <- Adapter <- Driver val wrappedTransport = - adapters.map { TransportAdaptersExtension.get(context.system).getAdapterProvider }.foldLeft(driver) { + adapters.map(TransportAdaptersExtension.get(context.system).getAdapterProvider).foldLeft(driver) { (t: Transport, provider: TransportAdapterProvider) => // The TransportAdapterProvider will wrap the given Transport and returns with a wrapped one provider.create(t, context.system.asInstanceOf[ExtendedActorSystem]) @@ -943,7 +933,7 @@ private[remote] class EndpointManager(conf: Config, log: LoggingAdapter) }) } - private def acceptPendingReader(takingOverFrom: ActorRef): Unit = { + private def acceptPendingReader(takingOverFrom: ActorRef): Unit = if (pendingReadHandoffs.contains(takingOverFrom)) { val handle = pendingReadHandoffs(takingOverFrom) pendingReadHandoffs -= takingOverFrom @@ -958,12 +948,10 @@ private[remote] class EndpointManager(conf: Config, log: LoggingAdapter) writing = false) endpoints.registerReadOnlyEndpoint(handle.remoteAddress, endpoint, handle.handshakeInfo.uid) } - } - private def removePendingReader(takingOverFrom: ActorRef, withHandle: PekkoProtocolHandle): Unit = { + private def removePendingReader(takingOverFrom: ActorRef, withHandle: PekkoProtocolHandle): Unit = if (pendingReadHandoffs.get(takingOverFrom).exists(handle => handle == withHandle)) pendingReadHandoffs -= takingOverFrom - } private def createEndpoint( remoteAddress: Address, diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/ArterySettings.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/ArterySettings.scala index d96b8ffff0a..a8ebc6b4a85 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/ArterySettings.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/ArterySettings.scala @@ -84,10 +84,9 @@ private[pekko] final class ArterySettings private (config: Config) { val LogReceive: Boolean = getBoolean("log-received-messages") val LogSend: Boolean = getBoolean("log-sent-messages") - val LogFrameSizeExceeding: Option[Int] = { + val LogFrameSizeExceeding: Option[Int] = if (toRootLowerCase(getString("log-frame-size-exceeding")) == "off") None else Some(getBytes("log-frame-size-exceeding").toInt) - } val Transport: Transport = toRootLowerCase(getString("transport")) match { case AeronUpd.configName => AeronUpd @@ -169,7 +168,7 @@ private[pekko] final class ArterySettings private (config: Config) { config .getMillisDuration("shutdown-flush-timeout") .requiring(timeout => timeout > Duration.Zero, "shutdown-flush-timeout must be more than zero") - val DeathWatchNotificationFlushTimeout: FiniteDuration = { + val DeathWatchNotificationFlushTimeout: FiniteDuration = toRootLowerCase(config.getString("death-watch-notification-flush-timeout")) match { case "off" => Duration.Zero case _ => @@ -179,7 +178,6 @@ private[pekko] final class ArterySettings private (config: Config) { interval => interval > Duration.Zero, "death-watch-notification-flush-timeout must be more than zero, or off") } - } val InboundRestartTimeout: FiniteDuration = config .getMillisDuration("inbound-restart-timeout") @@ -251,12 +249,11 @@ private[pekko] final class ArterySettings private (config: Config) { val ConnectionTimeout: FiniteDuration = config .getMillisDuration("connection-timeout") .requiring(interval => interval > Duration.Zero, "connection-timeout must be more than zero") - val OutboundClientHostname: Option[String] = { + val OutboundClientHostname: Option[String] = config.getString("outbound-client-hostname") match { case "" => None case hostname => Some(hostname) } - } } } diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/ArteryTransport.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/ArteryTransport.scala index 44103d42eda..57bec2677b6 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/ArteryTransport.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/ArteryTransport.scala @@ -142,20 +142,18 @@ private[remote] final class AssociationState private ( */ def uniqueRemoteAddress(): Option[UniqueAddress] = _uniqueRemoteAddress.get().uniqueRemoteAddress - def uniqueRemoteAddressState(): UniqueRemoteAddressState = { + def uniqueRemoteAddressState(): UniqueRemoteAddressState = uniqueRemoteAddress() match { case Some(a) if isQuarantined(a.uid) => UidQuarantined case Some(_) => UidKnown case None => UidUnknown // handshake not completed yet } - } - def isQuarantined(): Boolean = { + def isQuarantined(): Boolean = uniqueRemoteAddress() match { case Some(a) => isQuarantined(a.uid) case None => false // handshake not completed yet } - } def isQuarantined(uid: Long): Boolean = quarantined.contains(uid) @@ -298,11 +296,10 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr * * Use `inboundCompressionAccess` (provided by the materialized `Decoder`) to call into the compression infrastructure. */ - protected val _inboundCompressions = { + protected val _inboundCompressions = if (settings.Advanced.Compression.Enabled) { new InboundCompressionsImpl(system, this, settings.Advanced.Compression, flightRecorder) } else NoInboundCompressions - } @volatile private[this] var _inboundCompressionAccess: OptionVal[InboundCompressionAccess] = OptionVal.None @@ -455,7 +452,7 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr // Select inbound lane based on destination to preserve message order, // Also include the uid of the sending system in the hash to spread // "hot" destinations, e.g. ActorSelection anchor. - protected val inboundLanePartitioner: InboundEnvelope => Int = env => { + protected val inboundLanePartitioner: InboundEnvelope => Int = env => env.recipient match { case OptionVal.Some(r) => val a = r.path.uid @@ -467,10 +464,9 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr // the lane is set by the DuplicateHandshakeReq stage, otherwise 0 env.lane } - } private lazy val shutdownHook = new Thread { - override def run(): Unit = { + override def run(): Unit = if (!hasBeenShutdown.get) { val coord = CoordinatedShutdown(system) // totalTimeout will be 0 when no tasks registered, so at least 3.seconds @@ -486,14 +482,13 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr Await.result(internalShutdown(), settings.Advanced.Aeron.DriverTimeout + 3.seconds) } } - } } protected def attachControlMessageObserver(ctrl: ControlMessageSubject): Unit = { controlSubject = ctrl controlSubject.attach(new ControlMessageObserver { - override def notify(inboundEnvelope: InboundEnvelope): Unit = { - try { + override def notify(inboundEnvelope: InboundEnvelope): Unit = + try inboundEnvelope.message match { case m: CompressionMessage => import CompressionProtocol._ @@ -573,10 +568,9 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr case _ => // not interesting } - } catch { + catch { case ShuttingDown => // silence it } - } override def controlSubjectCompleted(signal: Try[Done]): Unit = () }) @@ -613,7 +607,7 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr } } - override def shutdown(): Future[Done] = { + override def shutdown(): Future[Done] = if (hasBeenShutdown.compareAndSet(false, true)) { log.debug("Shutting down [{}]", localAddress) if (system.settings.JvmShutdownHooks) @@ -637,7 +631,6 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr } else { Future.successful(Done) } - } private def internalShutdown(): Future[Done] = { implicit val ec = system.dispatchers.internalDispatcher @@ -695,9 +688,9 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr // InboundContext override def sendControl(to: Address, message: ControlMessage) = - try { + try association(to).sendControl(message) - } catch { + catch { case ShuttingDown => // silence it } @@ -728,26 +721,23 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr override def association(uid: Long): OptionVal[Association] = associationRegistry.association(uid) - override def completeHandshake(peer: UniqueAddress): Future[Done] = { - try { + override def completeHandshake(peer: UniqueAddress): Future[Done] = + try associationRegistry.setUID(peer).completeHandshake(peer) - } catch { + catch { case ShuttingDown => Future.successful(Done) // silence it } - } @InternalStableApi - override def quarantine(remoteAddress: Address, uid: Option[Long], reason: String): Unit = { + override def quarantine(remoteAddress: Address, uid: Option[Long], reason: String): Unit = quarantine(remoteAddress, uid, reason, harmless = false) - } - def quarantine(remoteAddress: Address, uid: Option[Long], reason: String, harmless: Boolean): Unit = { - try { + def quarantine(remoteAddress: Address, uid: Option[Long], reason: String, harmless: Boolean): Unit = + try association(remoteAddress).quarantine(reason, uid, harmless) - } catch { + catch { case ShuttingDown => // silence it } - } def outboundLarge(outboundContext: OutboundContext): Sink[OutboundEnvelope, Future[Done]] = createOutboundSink(LargeStreamId, outboundContext, largeEnvelopeBufferPool).mapMaterializedValue { @@ -760,11 +750,9 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr private def createOutboundSink( streamId: Int, outboundContext: OutboundContext, - bufferPool: EnvelopeBufferPool): Sink[OutboundEnvelope, (OutboundCompressionAccess, Future[Done])] = { - + bufferPool: EnvelopeBufferPool): Sink[OutboundEnvelope, (OutboundCompressionAccess, Future[Done])] = outboundLane(outboundContext, bufferPool, streamId).toMat( outboundTransportSink(outboundContext, streamId, bufferPool))(Keep.both) - } def outboundTransportSink(outboundContext: OutboundContext): Sink[EnvelopeBuffer, Future[Done]] = outboundTransportSink(outboundContext, OrdinaryStreamId, envelopeBufferPool) @@ -781,8 +769,7 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr private def outboundLane( outboundContext: OutboundContext, bufferPool: EnvelopeBufferPool, - streamId: Int): Flow[OutboundEnvelope, EnvelopeBuffer, OutboundCompressionAccess] = { - + streamId: Int): Flow[OutboundEnvelope, EnvelopeBuffer, OutboundCompressionAccess] = Flow .fromGraph(killSwitch.flow[OutboundEnvelope]) .via( @@ -795,7 +782,6 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr settings.Advanced.InjectHandshakeInterval, Duration.Undefined)) .viaMat(createEncoder(bufferPool, streamId))(Keep.right) - } def outboundControl( outboundContext: OutboundContext): Sink[OutboundEnvelope, (OutboundControlIngress, Future[Done])] = { @@ -852,7 +838,7 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr // Checks for termination hint messages and sends an ACK for those (not processing them further) // Purpose of this stage is flushing, the sender can wait for the ACKs up to try flushing // pending messages. - def terminationHintReplier(inControlStream: Boolean): Flow[InboundEnvelope, InboundEnvelope, NotUsed] = { + def terminationHintReplier(inControlStream: Boolean): Flow[InboundEnvelope, InboundEnvelope, NotUsed] = Flow[InboundEnvelope].filter { envelope => envelope.message match { case ActorSystemTerminating(from) => @@ -871,7 +857,6 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr case _ => true } } - } // Checks for Flush messages and sends an FlushAck for those (not processing them further) // Purpose of this stage is flushing, the sender can wait for the ACKs up to try flushing @@ -879,7 +864,7 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr // The Flush messages are duplicated into all lanes by the DuplicateFlush stage and // the `expectedAcks` corresponds to the number of lanes. The sender receives the `expectedAcks` and // thereby knows how many to wait for. - def flushReplier(expectedAcks: Int): Flow[InboundEnvelope, InboundEnvelope, NotUsed] = { + def flushReplier(expectedAcks: Int): Flow[InboundEnvelope, InboundEnvelope, NotUsed] = Flow[InboundEnvelope].filter { envelope => envelope.message match { case Flush => @@ -893,7 +878,6 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr case _ => true } } - } def inboundSink(bufferPool: EnvelopeBufferPool): Sink[InboundEnvelope, Future[Done]] = Flow[InboundEnvelope] @@ -907,15 +891,14 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr def inboundFlow( settings: ArterySettings, - compressions: InboundCompressions): Flow[EnvelopeBuffer, InboundEnvelope, InboundCompressionAccess] = { + compressions: InboundCompressions): Flow[EnvelopeBuffer, InboundEnvelope, InboundCompressionAccess] = Flow[EnvelopeBuffer].via(killSwitch.flow).viaMat(createDecoder(settings, compressions))(Keep.right) - } // large messages flow does not use compressions, since the message size dominates the size anyway def inboundLargeFlow(settings: ArterySettings): Flow[EnvelopeBuffer, InboundEnvelope, Any] = inboundFlow(settings, NoInboundCompressions) - def inboundControlSink: Sink[InboundEnvelope, (ControlMessageSubject, Future[Done])] = { + def inboundControlSink: Sink[InboundEnvelope, (ControlMessageSubject, Future[Done])] = Flow[InboundEnvelope] .via(createDeserializer(envelopeBufferPool)) .via(if (settings.Advanced.TestMode) new InboundTestStage(this, testState) else Flow[InboundEnvelope]) @@ -926,14 +909,13 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr .viaMat(new InboundControlJunction)(Keep.right) .via(new SystemMessageAcker(this)) .toMat(messageDispatcherSink)(Keep.both) - } def outboundTestFlow(outboundContext: OutboundContext): Flow[OutboundEnvelope, OutboundEnvelope, NotUsed] = if (settings.Advanced.TestMode) Flow.fromGraph(new OutboundTestStage(outboundContext, testState)) else Flow[OutboundEnvelope] /** INTERNAL API: for testing only. */ - private[remote] def triggerCompressionAdvertisements(actorRef: Boolean, manifest: Boolean) = { + private[remote] def triggerCompressionAdvertisements(actorRef: Boolean, manifest: Boolean) = inboundCompressionAccess match { case OptionVal.Some(c) if actorRef || manifest => log.info("Triggering compression table advertisement for {}", c) @@ -941,11 +923,9 @@ private[remote] abstract class ArteryTransport(_system: ExtendedActorSystem, _pr if (manifest) c.runNextClassManifestAdvertisement() case _ => } - } - override def publishDropped(env: InboundEnvelope, reason: String): Unit = { + override def publishDropped(env: InboundEnvelope, reason: String): Unit = system.eventStream.publish(Dropped(env.message, reason, env.recipient.getOrElse(system.deadLetters))) - } } diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/Association.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/Association.scala index 6bf999338ff..53cb9be79cc 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/Association.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/Association.scala @@ -107,10 +107,9 @@ private[remote] object Association { final case class LazyQueueWrapper(queue: Queue[OutboundEnvelope], materialize: () => Unit) extends QueueWrapper { private val onlyOnce = new AtomicBoolean - def runMaterialize(): Unit = { + def runMaterialize(): Unit = if (onlyOnce.compareAndSet(false, true)) materialize() - } override def offer(message: OutboundEnvelope): Boolean = { runMaterialize() @@ -234,7 +233,7 @@ private[remote] class Association( private def deadletters = transport.system.deadLetters - def outboundControlIngress: OutboundControlIngress = { + def outboundControlIngress: OutboundControlIngress = _outboundControlIngress match { case OptionVal.Some(o) => o case _ => @@ -252,7 +251,6 @@ private[remote] class Association( else throw new IllegalStateException(s"outboundControlIngress for [$remoteAddress] not initialized yet") } } - } override def localAddress: UniqueAddress = transport.localAddress @@ -328,8 +326,8 @@ private[remote] class Association( } // OutboundContext - override def sendControl(message: ControlMessage): Unit = { - try { + override def sendControl(message: ControlMessage): Unit = + try if (!transport.isShutdown && !isRemovedAfterQuarantined()) { if (associationState.isQuarantined()) { log.debug("Send control message [{}] to quarantined [{}]", Logging.messageClassName(message), remoteAddress) @@ -337,10 +335,9 @@ private[remote] class Association( } outboundControlIngress.sendControlMessage(message) } - } catch { + catch { case ShuttingDown => // silence it } - } def send(message: Any, sender: OptionVal[ActorRef], recipient: OptionVal[RemoteActorRef]): Unit = { @@ -373,7 +370,7 @@ private[remote] class Association( def shouldSendDeathWatchNotification(d: DeathWatchNotification): Boolean = d.addressTerminated || !transport.provider.settings.HasCluster || !transport.system.isTerminating() - def sendSystemMessage(outboundEnvelope: OutboundEnvelope): Unit = { + def sendSystemMessage(outboundEnvelope: OutboundEnvelope): Unit = outboundEnvelope.message match { case u: Unwatch if shouldSendUnwatch() => log.debug( @@ -393,7 +390,6 @@ private[remote] class Association( dropped(ControlQueueIndex, controlQueueSize, outboundEnvelope) } } - } val state = associationState val quarantined = state.isQuarantined() @@ -456,7 +452,7 @@ private[remote] class Association( remoteAddress) } - private def selectQueue(recipient: OptionVal[RemoteActorRef]): Int = { + private def selectQueue(recipient: OptionVal[RemoteActorRef]): Int = recipient match { case OptionVal.Some(r) => r.cachedSendQueueIndex match { @@ -485,19 +481,17 @@ private[remote] class Association( case _ => OrdinaryQueueIndex } - } override def isOrdinaryMessageStreamActive(): Boolean = isStreamActive(OrdinaryQueueIndex) - def isStreamActive(queueIndex: Int): Boolean = { + def isStreamActive(queueIndex: Int): Boolean = queues(queueIndex) match { case _: LazyQueueWrapper => false case DisabledQueueWrapper => false case RemovedQueueWrapper => false case _ => true } - } def sendTerminationHint(replyTo: ActorRef): Int = { log.debug("Sending ActorSystemTerminating to all queues") @@ -507,7 +501,7 @@ private[remote] class Association( def sendFlush(replyTo: ActorRef, excludeControlQueue: Boolean): Int = sendToAllQueues(Flush, replyTo, excludeControlQueue) - def sendToAllQueues(msg: ControlMessage, replyTo: ActorRef, excludeControlQueue: Boolean): Int = { + def sendToAllQueues(msg: ControlMessage, replyTo: ActorRef, excludeControlQueue: Boolean): Int = if (!associationState.isQuarantined()) { var sent = 0 val queuesIter = if (excludeControlQueue) queues.iterator.drop(1) else queues.iterator @@ -523,7 +517,6 @@ private[remote] class Association( } sent } else 0 - } // OutboundContext override def quarantine(reason: String): Unit = { @@ -531,7 +524,7 @@ private[remote] class Association( quarantine(reason, uid, harmless = false) } - @tailrec final def quarantine(reason: String, uid: Option[Long], harmless: Boolean): Unit = { + @tailrec final def quarantine(reason: String, uid: Option[Long], harmless: Boolean): Unit = uid match { case Some(u) => val current = associationState @@ -598,12 +591,10 @@ private[remote] class Association( reason) } - } - /** * After calling this no messages can be sent with this Association instance */ - def removedAfterQuarantined(): Unit = { + def removedAfterQuarantined(): Unit = if (!isRemovedAfterQuarantined()) { flightRecorder.transportRemoveQuarantined(remoteAddress) queues(ControlQueueIndex) = RemovedQueueWrapper @@ -624,7 +615,6 @@ private[remote] class Association( log.info("Unused association to [{}] removed after quarantine", remoteAddress) } - } def isRemovedAfterQuarantined(): Boolean = queues(ControlQueueIndex) == RemovedQueueWrapper @@ -663,7 +653,7 @@ private[remote] class Association( idleTimer.compareAndSet(current, None) } - private def setupIdleTimer(): Unit = { + private def setupIdleTimer(): Unit = if (idleTimer.get.isEmpty) { val StopIdleOutboundAfter = settings.Advanced.StopIdleOutboundAfter val QuarantineIdleOutboundAfter = settings.Advanced.QuarantineIdleOutboundAfter @@ -723,16 +713,14 @@ private[remote] class Association( task.cancel() } } - } private def cancelAllTimers(): Unit = { cancelIdleTimer() cancelStopQuarantinedTimer() } - private def sendToDeadLetters[T](pending: Vector[OutboundEnvelope]): Unit = { + private def sendToDeadLetters[T](pending: Vector[OutboundEnvelope]): Unit = pending.foreach(transport.system.deadLetters ! _) - } /** * Called once after construction when the `Association` instance @@ -956,9 +944,8 @@ private[remote] class Association( _outboundControlIngress = OptionVal.None } // LazyQueueWrapper will invoke the `restart` function when first message is offered - val wrappedRestartFun: () => Unit = () => { + val wrappedRestartFun: () => Unit = () => restart() - } if (!isRemovedAfterQuarantined()) queues(queueIndex) = LazyQueueWrapper(createQueue(queueCapacity, queueIndex), wrappedRestartFun) @@ -1089,12 +1076,11 @@ private[remote] class Association( } } - private def getStopReason(streamId: Int): OptionVal[StopSignal] = { + private def getStopReason(streamId: Int): OptionVal[StopSignal] = streamMatValues.get().get(streamId) match { case Some(OutboundStreamMatValues(_, _, stopping)) => stopping case None => OptionVal.None } - } // after it has been used we remove the kill switch to cleanup some memory, // not a "leak" but a KillSwitch is rather heavy diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/Codecs.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/Codecs.scala index 86ea9e56759..49005b662c5 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/Codecs.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/Codecs.scala @@ -119,9 +119,8 @@ private[remote] class Encoder( private var debugLogSendEnabled = false - override def preStart(): Unit = { + override def preStart(): Unit = debugLogSendEnabled = debugLogSend && log.isDebugEnabled - } override def onPush(): Unit = { val outboundEnvelope = grab(in) @@ -563,7 +562,7 @@ private[remote] class Decoder( pull(in) } - private def resolveRecipient(path: String): OptionVal[InternalActorRef] = { + private def resolveRecipient(path: String): OptionVal[InternalActorRef] = actorRefResolver.getOrCompute(path) match { case empty: EmptyLocalActorRef => val pathElements = empty.path.elements @@ -571,11 +570,10 @@ private[remote] class Decoder( else OptionVal(empty) case ref => OptionVal(ref) } - } override def onPull(): Unit = pull(in) - override protected def onTimer(timerKey: Any): Unit = { + override protected def onTimer(timerKey: Any): Unit = timerKey match { case Tick => val now = System.nanoTime() @@ -629,7 +627,6 @@ private[remote] class Decoder( case unknown => throw new IllegalArgumentException(s"Unknown timer key: $unknown") } - } setHandlers(in, out, this) } @@ -747,7 +744,7 @@ private[remote] class DuplicateHandshakeReq( lazyInitOfSerializer() _manifest } - def lazyInitOfSerializer(): Unit = { + def lazyInitOfSerializer(): Unit = if (_serializerId == -1) { val serialization = SerializationExtension(system) val ser = serialization.serializerFor(classOf[HandshakeReq]) @@ -755,7 +752,6 @@ private[remote] class DuplicateHandshakeReq( Serializers.manifestFor(ser, HandshakeReq(inboundContext.localAddress, inboundContext.localAddress.address)) _serializerId = ser.identifier } - } var currentIterator: Iterator[InboundEnvelope] = Iterator.empty @@ -777,14 +773,13 @@ private[remote] class DuplicateHandshakeReq( push(out, envelope) } - override def onPull(): Unit = { + override def onPull(): Unit = if (currentIterator.isEmpty) pull(in) else { push(out, currentIterator.next()) if (currentIterator.isEmpty) currentIterator = Iterator.empty // GC friendly } - } setHandlers(in, out, this) } @@ -815,14 +810,13 @@ private[remote] class DuplicateFlush(numberOfLanes: Int, system: ExtendedActorSy lazyInitOfSerializer() _manifest } - def lazyInitOfSerializer(): Unit = { + def lazyInitOfSerializer(): Unit = if (_serializerId == -1) { val serialization = SerializationExtension(system) val ser = serialization.serializerFor(Flush.getClass) _manifest = Serializers.manifestFor(ser, Flush) _serializerId = ser.identifier } - } var currentIterator: Iterator[InboundEnvelope] = Iterator.empty @@ -843,14 +837,13 @@ private[remote] class DuplicateFlush(numberOfLanes: Int, system: ExtendedActorSy push(out, envelope) } - override def onPull(): Unit = { + override def onPull(): Unit = if (currentIterator.isEmpty) pull(in) else { push(out, currentIterator.next()) if (currentIterator.isEmpty) currentIterator = Iterator.empty // GC friendly } - } setHandlers(in, out, this) } diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/Control.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/Control.scala index f842e62b3fe..1f56248e8bd 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/Control.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/Control.scala @@ -147,7 +147,7 @@ private[remote] class InboundControlJunction } // InHandler - override def onPush(): Unit = { + override def onPush(): Unit = grab(in) match { case env: InboundEnvelope if env.message.isInstanceOf[ControlMessage] => observers.foreach(_.notify(env)) @@ -155,7 +155,6 @@ private[remote] class InboundControlJunction case env => push(out, env) } - } // OutHandler override def onPull(): Unit = pull(in) @@ -216,22 +215,20 @@ private[remote] class OutboundControlJunction( private val buffer = new ArrayDeque[OutboundEnvelope] // InHandler - override def onPush(): Unit = { + override def onPush(): Unit = if (buffer.isEmpty && isAvailable(out)) push(out, grab(in)) else buffer.offer(grab(in)) - } // OutHandler - override def onPull(): Unit = { + override def onPull(): Unit = if (buffer.isEmpty && !hasBeenPulled(in)) pull(in) else if (!buffer.isEmpty) push(out, buffer.poll()) - } - private def internalSendControlMessage(message: ControlMessage): Unit = { + private def internalSendControlMessage(message: ControlMessage): Unit = if (buffer.isEmpty && isAvailable(out)) push(out, wrap(message)) else if (buffer.size < maxControlMessageBufferSize) @@ -240,7 +237,6 @@ private[remote] class OutboundControlJunction( // it's alright to drop control messages log.debug("Dropping control message [{}] due to full buffer.", Logging.messageClassName(message)) } - } private def wrap(message: ControlMessage): OutboundEnvelope = outboundEnvelopePool.acquire().init(recipient = OptionVal.None, message = message, sender = OptionVal.None) diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/EnvelopeBufferPool.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/EnvelopeBufferPool.scala index 3ad099e3d8f..dce2a426aa8 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/EnvelopeBufferPool.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/EnvelopeBufferPool.scala @@ -46,10 +46,9 @@ private[remote] class EnvelopeBufferPool(maximumPayload: Int, maximumBuffers: In } } - def release(buffer: EnvelopeBuffer) = { + def release(buffer: EnvelopeBuffer) = // only reuse direct buffers, e.g. not those wrapping ByteString if (buffer.byteBuffer.isDirect && !availableBuffers.offer(buffer)) buffer.tryCleanDirectByteBuffer() - } } @@ -297,39 +296,35 @@ private[remote] final class HeaderBuilderImpl( def useOutboundCompression(on: Boolean): Unit = _useOutboundCompression = on - def setOutboundActorRefCompression(table: CompressionTable[ActorRef]): Unit = { + def setOutboundActorRefCompression(table: CompressionTable[ActorRef]): Unit = _outboundActorRefCompression = table - } override def outboundActorRefCompression: CompressionTable[ActorRef] = _outboundActorRefCompression - def setOutboundClassManifestCompression(table: CompressionTable[String]): Unit = { + def setOutboundClassManifestCompression(table: CompressionTable[String]): Unit = _outboundClassManifestCompression = table - } def outboundClassManifestCompression: CompressionTable[String] = _outboundClassManifestCompression /** * Note that Serialization.currentTransportInformation must be set when calling this method, * because it's using `Serialization.serializedActorPath` */ - override def setSenderActorRef(ref: ActorRef): Unit = { + override def setSenderActorRef(ref: ActorRef): Unit = if (_useOutboundCompression) { _senderActorRefIdx = outboundActorRefCompression.compress(ref) if (_senderActorRefIdx == -1) _senderActorRef = Serialization.serializedActorPath(ref) } else _senderActorRef = Serialization.serializedActorPath(ref) - } override def setNoSender(): Unit = { _senderActorRef = null _senderActorRefIdx = DeadLettersCode } override def isNoSender: Boolean = (_senderActorRef eq null) && _senderActorRefIdx == DeadLettersCode - override def senderActorRef(originUid: Long): OptionVal[ActorRef] = { + override def senderActorRef(originUid: Long): OptionVal[ActorRef] = // we treat deadLetters as always present, but not included in table if ((_senderActorRef eq null) && !isNoSender) inboundCompression.decompressActorRef(originUid, inboundActorRefCompressionTableVersion, _senderActorRefIdx) else OptionVal.None - } def senderActorRefPath: OptionVal[String] = OptionVal(_senderActorRef) @@ -345,45 +340,39 @@ private[remote] final class HeaderBuilderImpl( * Note that Serialization.currentTransportInformation must be set when calling this method, * because it's using `Serialization.serializedActorPath` */ - def setRecipientActorRef(ref: ActorRef): Unit = { + def setRecipientActorRef(ref: ActorRef): Unit = if (_useOutboundCompression) { _recipientActorRefIdx = outboundActorRefCompression.compress(ref) if (_recipientActorRefIdx == -1) _recipientActorRef = toSerializationFormat.getOrCompute(ref) } else _recipientActorRef = toSerializationFormat.getOrCompute(ref) - } - def recipientActorRef(originUid: Long): OptionVal[ActorRef] = { + def recipientActorRef(originUid: Long): OptionVal[ActorRef] = // we treat deadLetters as always present, but not included in table if ((_recipientActorRef eq null) && !isNoRecipient) inboundCompression.decompressActorRef(originUid, inboundActorRefCompressionTableVersion, _recipientActorRefIdx) else OptionVal.None - } def recipientActorRefPath: OptionVal[String] = OptionVal(_recipientActorRef) - override def setSerializer(serializer: Int): Unit = { + override def setSerializer(serializer: Int): Unit = _serializer = serializer - } override def serializer: Int = _serializer - override def setManifest(manifest: String): Unit = { + override def setManifest(manifest: String): Unit = if (_useOutboundCompression) { _manifestIdx = outboundClassManifestCompression.compress(manifest) if (_manifestIdx == -1) _manifest = manifest } else _manifest = manifest - } - override def manifest(originUid: Long): OptionVal[String] = { + override def manifest(originUid: Long): OptionVal[String] = if (_manifest ne null) OptionVal.Some(_manifest) else { inboundCompression.decompressClassManifest(originUid, inboundClassManifestCompressionTableVersion, _manifestIdx) } - } - override def setRemoteInstruments(instruments: RemoteInstruments): Unit = { + override def setRemoteInstruments(instruments: RemoteInstruments): Unit = _remoteInstruments = OptionVal(instruments) - } override def toString = "HeaderBuilderImpl(" + @@ -559,12 +548,11 @@ private[remote] final class EnvelopeBuffer(val byteBuffer: ByteBuffer) { } } - private def ensureLiteralCharsLength(length: Int): Unit = { + private def ensureLiteralCharsLength(length: Int): Unit = if (length > literalChars.length) { literalChars = new Array[Char](length) literalBytes = new Array[Byte](length) } - } def tryCleanDirectByteBuffer(): Unit = DirectByteBufferPool.tryCleanDirectByteBuffer(byteBuffer) diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/FixedSizePartitionHub.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/FixedSizePartitionHub.scala index d39cdd318ff..bec7a5ec517 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/FixedSizePartitionHub.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/FixedSizePartitionHub.scala @@ -73,10 +73,9 @@ import pekko.stream.scaladsl.PartitionHub override def nonEmpty(id: Long): Boolean = !isEmpty(id) - override def offer(id: Long, elem: Any): Unit = { + override def offer(id: Long, elem: Any): Unit = if (!queues(id.toInt).offer(elem.asInstanceOf[AnyRef])) throw new IllegalStateException(s"queue is full, id [$id]") - } override def poll(id: Long): AnyRef = queues(id.toInt).poll() diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/FlushBeforeDeathWatchNotification.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/FlushBeforeDeathWatchNotification.scala index 211e0dd6620..46f6c04ef94 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/FlushBeforeDeathWatchNotification.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/FlushBeforeDeathWatchNotification.scala @@ -33,9 +33,8 @@ import pekko.annotation.InternalApi private[remote] object FlushBeforeDeathWatchNotification { private val nameCounter = new AtomicLong(0L) - def props(done: Promise[Done], timeout: FiniteDuration, association: Association): Props = { + def props(done: Promise[Done], timeout: FiniteDuration, association: Association): Props = Props(new FlushBeforeDeathWatchNotification(done, timeout, association)) - } def nextName(): String = s"flush-${nameCounter.incrementAndGet()}" @@ -60,7 +59,7 @@ private[remote] class FlushBeforeDeathWatchNotification( private val timeoutTask = context.system.scheduler.scheduleOnce(timeout, self, Timeout)(context.dispatcher) - override def preStart(): Unit = { + override def preStart(): Unit = try { sent = association.sendFlush(self, excludeControlQueue = true) if (sent == 0) { @@ -74,7 +73,6 @@ private[remote] class FlushBeforeDeathWatchNotification( // will log and stop throw e } - } override def postStop(): Unit = { timeoutTask.cancel() diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/FlushOnShutdown.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/FlushOnShutdown.scala index 67610f6b224..8e12256b69c 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/FlushOnShutdown.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/FlushOnShutdown.scala @@ -48,7 +48,7 @@ private[remote] class FlushOnShutdown(done: Promise[Done], timeout: FiniteDurati private val timeoutTask = context.system.scheduler.scheduleOnce(timeout, self, FlushOnShutdown.Timeout)(context.dispatcher) - override def preStart(): Unit = { + override def preStart(): Unit = try { associations.foreach { a => val acksExpected = a.sendTerminationHint(self) @@ -67,7 +67,6 @@ private[remote] class FlushOnShutdown(done: Promise[Done], timeout: FiniteDurati done.tryFailure(e) throw e } - } override def postStop(): Unit = { timeoutTask.cancel() diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/Handshake.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/Handshake.scala index 9efb6196f8f..40ac8336cd9 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/Handshake.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/Handshake.scala @@ -131,7 +131,7 @@ private[remote] class OutboundHandshake( } // OutHandler - override def onPull(): Unit = { + override def onPull(): Unit = handshakeState match { case Completed => pendingMessage match { @@ -162,7 +162,6 @@ private[remote] class OutboundHandshake( case ReqInProgress => // will pull when handshake reply is received } - } private def pushHandshakeReq(): Unit = { injectHandshakeTickScheduled = true @@ -172,7 +171,7 @@ private[remote] class OutboundHandshake( push(out, createHandshakeReqEnvelope()) } - private def pushLivenessProbeReq(): Unit = { + private def pushLivenessProbeReq(): Unit = // The associationState.lastUsedTimestamp will be updated when the HandshakeRsp is received // and that is the confirmation that the other system is alive, and will not be quarantined // by the quarantine-idle-outbound-after even though no real messages have been sent. @@ -186,16 +185,14 @@ private[remote] class OutboundHandshake( push(out, createHandshakeReqEnvelope()) } } - } - private def createHandshakeReqEnvelope(): OutboundEnvelope = { + private def createHandshakeReqEnvelope(): OutboundEnvelope = outboundEnvelopePool .acquire() .init( recipient = OptionVal.None, message = HandshakeReq(outboundContext.localAddress, outboundContext.remoteAddress), sender = OptionVal.None) - } private def handshakeCompleted(): Unit = { handshakeState = Completed @@ -279,7 +276,7 @@ private[remote] class InboundHandshake(inboundContext: InboundContext, inControl } }) - private def onHandshakeReq(from: UniqueAddress, to: Address): Unit = { + private def onHandshakeReq(from: UniqueAddress, to: Address): Unit = if (to == inboundContext.localAddress.address) { after(inboundContext.completeHandshake(from)) { () => inboundContext.sendControl(from.address, HandshakeRsp(inboundContext.localAddress)) @@ -298,9 +295,8 @@ private[remote] class InboundHandshake(inboundContext: InboundContext, inControl pull(in) } - } - private def after(first: Future[Done])(thenInside: () => Unit): Unit = { + private def after(first: Future[Done])(thenInside: () => Unit): Unit = first.value match { case Some(_) => // This in the normal case (all but the first). The future will be completed @@ -311,9 +307,7 @@ private[remote] class InboundHandshake(inboundContext: InboundContext, inControl first.onComplete(_ => runInStage.invoke(thenInside))(ExecutionContexts.parasitic) } - } - - private def onMessage(env: InboundEnvelope): Unit = { + private def onMessage(env: InboundEnvelope): Unit = if (isKnownOrigin(env)) push(out, env) else { @@ -323,14 +317,12 @@ private[remote] class InboundHandshake(inboundContext: InboundContext, inControl inboundContext.publishDropped(env, dropReason) pull(in) } - } - private def isKnownOrigin(env: InboundEnvelope): Boolean = { + private def isKnownOrigin(env: InboundEnvelope): Boolean = // the association is passed in the envelope from the Decoder stage to avoid // additional lookup. The second OR case is because if we didn't use fusing it // would be possible that it was not found by Decoder (handshake not completed yet) env.association.isDefined || inboundContext.association(env.originUid).isDefined - } // OutHandler override def onPull(): Unit = pull(in) diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/ImmutableLongMap.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/ImmutableLongMap.scala index ddc703fd178..cdc9345182c 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/ImmutableLongMap.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/ImmutableLongMap.scala @@ -53,16 +53,15 @@ private[pekko] class ImmutableLongMap[A >: Null] private (private val keys: Arra /** * Worst case `O(log n)`, allocation free. */ - def contains(key: Long): Boolean = { + def contains(key: Long): Boolean = Arrays.binarySearch(keys, key) >= 0 - } /** * Worst case `O(log n)`, creates new `ImmutableLongMap` * with copies of the internal arrays for the keys and * values. */ - def updated(key: Long, value: A): ImmutableLongMap[A] = { + def updated(key: Long, value: A): ImmutableLongMap[A] = if (size == 0) new ImmutableLongMap(Array(key), Array(value)) else { @@ -89,7 +88,6 @@ private[pekko] class ImmutableLongMap[A >: Null] private (private val keys: Arra new ImmutableLongMap(newKeys, newValues) } } - } def remove(key: Long): ImmutableLongMap[A] = { val i = Arrays.binarySearch(keys, key) @@ -133,12 +131,11 @@ private[pekko] class ImmutableLongMap[A >: Null] private (private val keys: Arra else if (size != other.size) false else if (size == 0 && other.size == 0) true else { - @tailrec def check(i: Int): Boolean = { + @tailrec def check(i: Int): Boolean = if (i == size) true else if (keys(i) == other.keys(i) && values(i) == other.values(i)) check(i + 1) // recur, next elem else false - } check(0) } case _ => false diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/LruBoundedCache.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/LruBoundedCache.scala index fc4bc8b713d..6da2e506494 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/LruBoundedCache.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/LruBoundedCache.scala @@ -92,7 +92,7 @@ private[pekko] abstract class LruBoundedCache[K <: AnyRef: ClassTag, V <: AnyRef val h = hash(k) epoch += 1 - @tailrec def findOrCalculate(position: Int, probeDistance: Int): V = { + @tailrec def findOrCalculate(position: Int, probeDistance: Int): V = if (values(position) eq null) { val value = compute(k) if (isCacheable(value)) { @@ -119,7 +119,6 @@ private[pekko] abstract class LruBoundedCache[K <: AnyRef: ClassTag, V <: AnyRef findOrCalculate((position + 1) & Mask, probeDistance + 1) } } - } findOrCalculate(position = h & Mask, probeDistance = 0) } @@ -147,7 +146,7 @@ private[pekko] abstract class LruBoundedCache[K <: AnyRef: ClassTag, V <: AnyRef // Protected for exposing it to unit tests protected def probeDistanceOf(idealSlot: Int, actualSlot: Int) = ((actualSlot - idealSlot) + capacity) & Mask - @tailrec private def move(position: Int, k: K, h: Int, value: V, elemEpoch: Int, probeDistance: Int): Unit = { + @tailrec private def move(position: Int, k: K, h: Int, value: V, elemEpoch: Int, probeDistance: Int): Unit = if (values(position) eq null) { // Found an empty place, done. keys(position) = k @@ -188,8 +187,6 @@ private[pekko] abstract class LruBoundedCache[K <: AnyRef: ClassTag, V <: AnyRef } } - } - protected def compute(k: K): V protected def hash(k: K): Int diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/RemoteInstrument.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/RemoteInstrument.scala index 7123483fd65..ecf990e8b7c 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/RemoteInstrument.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/RemoteInstrument.scala @@ -123,7 +123,7 @@ abstract class RemoteInstrument { message: Object, sender: ActorRef, size: Int, - time: Long): Unit = { + time: Long): Unit = if (size >= logFrameSizeExceeding) { val clazz = message match { case x: WrappedMessage => x.message.getClass @@ -147,7 +147,6 @@ abstract class RemoteInstrument { } check() } - } override def remoteReadMetadata(recipient: ActorRef, message: Object, sender: ActorRef, buffer: ByteBuffer): Unit = () @@ -192,7 +191,7 @@ private[remote] final class RemoteInstruments( // does any of the instruments want serialization timing? private val serializationTimingEnabled = instruments.exists(_.serializationTimingEnabled) - def serialize(outboundEnvelope: OptionVal[OutboundEnvelope], buffer: ByteBuffer): Unit = { + def serialize(outboundEnvelope: OptionVal[OutboundEnvelope], buffer: ByteBuffer): Unit = if (instruments.nonEmpty && outboundEnvelope.isDefined) { val startPos = buffer.position() val oe = outboundEnvelope.get @@ -203,9 +202,9 @@ private[remote] final class RemoteInstruments( while (i < instruments.length) { val rewindPos = buffer.position() val instrument = instruments(i) - try { + try serializeInstrument(instrument, oe, buffer) - } catch { + catch { case NonFatal(t) => log.debug( "Skipping serialization of RemoteInstrument {} since it failed with {}", @@ -229,7 +228,6 @@ private[remote] final class RemoteInstruments( buffer.position(startPos) } } - } private def serializeInstrument( instrument: RemoteInstrument, @@ -253,18 +251,17 @@ private[remote] final class RemoteInstruments( } } - def deserialize(inboundEnvelope: InboundEnvelope): Unit = { + def deserialize(inboundEnvelope: InboundEnvelope): Unit = if (inboundEnvelope.flag(EnvelopeBuffer.MetadataPresentFlag)) { inboundEnvelope.envelopeBuffer.byteBuffer.position(EnvelopeBuffer.MetadataContainerAndLiteralSectionOffset) deserializeRaw(inboundEnvelope) } - } def deserializeRaw(inboundEnvelope: InboundEnvelope): Unit = { val buffer = inboundEnvelope.envelopeBuffer.byteBuffer val length = buffer.getInt val endPos = buffer.position() + length - try { + try if (instruments.nonEmpty) { var i = 0 while (i < instruments.length && buffer.position() < endPos) { @@ -277,9 +274,9 @@ private[remote] final class RemoteInstruments( var nextPos = dataPos + length val identifier = instrument.identifier if (key == identifier) { - try { + try deserializeInstrument(instrument, inboundEnvelope, buffer) - } catch { + catch { case NonFatal(t) => log.debug( "Skipping deserialization of RemoteInstrument {} since it failed with {}", @@ -304,38 +301,35 @@ private[remote] final class RemoteInstruments( "Skipping serialized data in message for RemoteInstrument(s) {} that has no local match", remoteInstrumentIdIteratorRaw(buffer, endPos).mkString("[", ", ", "]")) } - } catch { + catch { case NonFatal(t) => log.debug("Skipping further deserialization of remaining RemoteInstruments due to unhandled failure {}", t) - } finally { + } finally buffer.position(endPos) - } } private def deserializeInstrument( instrument: RemoteInstrument, inboundEnvelope: InboundEnvelope, - buffer: ByteBuffer): Unit = { + buffer: ByteBuffer): Unit = instrument.remoteReadMetadata( inboundEnvelope.recipient.orNull, inboundEnvelope.message, inboundEnvelope.sender.orNull, buffer) - } def messageSent(outboundEnvelope: OutboundEnvelope, size: Int, time: Long): Unit = { - @tailrec def messageSent(pos: Int): Unit = { + @tailrec def messageSent(pos: Int): Unit = if (pos < instruments.length) { val instrument = instruments(pos) - try { + try messageSentInstrument(instrument, outboundEnvelope, size, time) - } catch { + catch { case NonFatal(t) => log.debug("Message sent in RemoteInstrument {} failed with {}", instrument.identifier, t.getMessage) } messageSent(pos + 1) } - } messageSent(0) } @@ -343,28 +337,26 @@ private[remote] final class RemoteInstruments( instrument: RemoteInstrument, outboundEnvelope: OutboundEnvelope, size: Int, - time: Long): Unit = { + time: Long): Unit = instrument.remoteMessageSent( outboundEnvelope.recipient.orNull, outboundEnvelope.message, outboundEnvelope.sender.orNull, size, time) - } def messageReceived(inboundEnvelope: InboundEnvelope, size: Int, time: Long): Unit = { - @tailrec def messageRecieved(pos: Int): Unit = { + @tailrec def messageRecieved(pos: Int): Unit = if (pos < instruments.length) { val instrument = instruments(pos) - try { + try messageReceivedInstrument(instrument, inboundEnvelope, size, time) - } catch { + catch { case NonFatal(t) => log.debug("Message received in RemoteInstrument {} failed with {}", instrument.identifier, t.getMessage) } messageRecieved(pos + 1) } - } messageRecieved(0) } @@ -372,16 +364,15 @@ private[remote] final class RemoteInstruments( instrument: RemoteInstrument, inboundEnvelope: InboundEnvelope, size: Int, - time: Long): Unit = { + time: Long): Unit = instrument.remoteMessageReceived( inboundEnvelope.recipient.orNull, inboundEnvelope.message, inboundEnvelope.sender.orNull, size, time) - } - private def remoteInstrumentIdIteratorRaw(buffer: ByteBuffer, endPos: Int): Iterator[Int] = { + private def remoteInstrumentIdIteratorRaw(buffer: ByteBuffer, endPos: Int): Iterator[Int] = new Iterator[Int] { override def hasNext: Boolean = buffer.position() < endPos override def next(): Int = { @@ -390,7 +381,6 @@ private[remote] final class RemoteInstruments( getKey(keyAndLength) } } - } def isEmpty: Boolean = instruments.isEmpty def nonEmpty: Boolean = instruments.nonEmpty diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/SendQueue.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/SendQueue.scala index 9321e7bc604..60ad4132ee5 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/SendQueue.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/SendQueue.scala @@ -85,12 +85,11 @@ private[remote] final class SendQueue[T](postStopAction: Vector[T] => Unit) }.invoke) } - override def onPull(): Unit = { + override def onPull(): Unit = if (consumerQueue ne null) tryPush() - } - @tailrec private def tryPush(firstAttempt: Boolean = true): Unit = { + @tailrec private def tryPush(firstAttempt: Boolean = true): Unit = consumerQueue.poll() match { case null => needWakeup = true @@ -102,12 +101,10 @@ private[remote] final class SendQueue[T](postStopAction: Vector[T] => Unit) needWakeup = false // there will be another onPull push(out, elem) } - } // external call - override def wakeup(): Unit = { + override def wakeup(): Unit = wakeupCallback.invoke(()) - } override def postStop(): Unit = { val pending = Vector.newBuilder[T] diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/SystemMessageDelivery.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/SystemMessageDelivery.scala index 2bcbc21afac..2bc5ac88cd8 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/SystemMessageDelivery.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/SystemMessageDelivery.scala @@ -131,12 +131,11 @@ import pekko.util.PrettyDuration.PrettyPrintableDuration outboundContext.controlSubject.detach(this) } - override def onUpstreamFinish(): Unit = { + override def onUpstreamFinish(): Unit = if (unacknowledged.isEmpty) super.onUpstreamFinish() else stopping = true - } override protected def onTimer(timerKey: Any): Unit = timerKey match { @@ -154,21 +153,19 @@ import pekko.util.PrettyDuration.PrettyPrintableDuration } // ControlMessageObserver, external call - override def notify(inboundEnvelope: InboundEnvelope): Unit = { + override def notify(inboundEnvelope: InboundEnvelope): Unit = inboundEnvelope.message match { case ack: Ack => if (ack.from.address == remoteAddress) ackCallback.invoke(ack) case nack: Nack => if (nack.from.address == remoteAddress) nackCallback.invoke(nack) case _ => // not interested } - } // ControlMessageObserver, external call but on graph logic machinery thread (getAsyncCallback safe) - override def controlSubjectCompleted(signal: Try[Done]): Unit = { + override def controlSubjectCompleted(signal: Try[Done]): Unit = getAsyncCallback[Try[Done]] { case Success(_) => completeStage() case Failure(cause) => failStage(cause) }.invoke(signal) - } private val ackCallback = getAsyncCallback[Ack] { reply => ack(reply.seqNo) @@ -192,7 +189,7 @@ import pekko.util.PrettyDuration.PrettyPrintableDuration clearUnacknowledged(n) } - @tailrec private def clearUnacknowledged(ackedSeqNo: Long): Unit = { + @tailrec private def clearUnacknowledged(ackedSeqNo: Long): Unit = if (!unacknowledged.isEmpty && unacknowledged.peek().message.asInstanceOf[SystemMessageEnvelope].seqNo <= ackedSeqNo) { unacknowledged.removeFirst() @@ -204,9 +201,8 @@ import pekko.util.PrettyDuration.PrettyPrintableDuration else clearUnacknowledged(ackedSeqNo) } - } - private def tryResend(): Unit = { + private def tryResend(): Unit = if (isAvailable(out) && !resending.isEmpty) { val env = resending.poll() @@ -226,12 +222,10 @@ import pekko.util.PrettyDuration.PrettyPrintableDuration pushCopy(env) } - } // important to not send the buffered instance, since it's mutable - private def pushCopy(outboundEnvelope: OutboundEnvelope): Unit = { + private def pushCopy(outboundEnvelope: OutboundEnvelope): Unit = push(out, outboundEnvelope.copy()) - } // InHandler override def onPush(): Unit = { @@ -286,12 +280,11 @@ import pekko.util.PrettyDuration.PrettyPrintableDuration } } - private def checkGiveUp(): Unit = { + private def checkGiveUp(): Unit = if (!unacknowledged.isEmpty && (System.nanoTime() - ackTimestamp > giveUpAfterNanos)) throw new GaveUpSystemMessageException( s"Gave up sending system message to [${outboundContext.remoteAddress}] after " + s"${outboundContext.settings.Advanced.GiveUpSystemMessageAfter.pretty}.") - } private def clear(): Unit = { sendUnacknowledgedToDeadLetters() @@ -304,20 +297,18 @@ import pekko.util.PrettyDuration.PrettyPrintableDuration private def sendUnacknowledgedToDeadLetters(): Unit = { val iter = unacknowledged.iterator - while (iter.hasNext()) { + while (iter.hasNext()) deadLetters ! iter.next() - } } // OutHandler - override def onPull(): Unit = { + override def onPull(): Unit = if (replyObserverAttached) { // otherwise it will be pulled after attached if (resending.isEmpty && !hasBeenPulled(in) && !stopping) pull(in) else tryResend() } - } setHandlers(in, out, this) } diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/TestStage.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/TestStage.scala index bef0deddef6..443235fb37c 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/TestStage.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/TestStage.scala @@ -162,7 +162,7 @@ private[remote] class InboundTestStage(inboundContext: InboundContext, state: Sh new TimerGraphStageLogic(shape) with InHandler with OutHandler with StageLogging { // InHandler - override def onPush(): Unit = { + override def onPush(): Unit = state.getInboundFailureOnce match { case Some(shouldFailEx) => log.info("Fail inbound stream from [{}]: {}", classOf[InboundTestStage].getName, shouldFailEx.getMessage) @@ -202,7 +202,6 @@ private[remote] class InboundTestStage(inboundContext: InboundContext, state: Sh } } } - } // OutHandler override def onPull(): Unit = pull(in) diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/aeron/AeronSink.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/aeron/AeronSink.scala index 2ce40b1ee86..df0af070040 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/aeron/AeronSink.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/aeron/AeronSink.scala @@ -147,7 +147,7 @@ private[remote] class AeronSink( flightRecorder.aeronSinkStarted(channel, streamId) } - override def postStop(): Unit = { + override def postStop(): Unit = try { taskRunner.command(Remove(addOfferTask.task)) flightRecorder.aeronSinkTaskRunnerRemoved(channel, streamId) @@ -157,7 +157,6 @@ private[remote] class AeronSink( flightRecorder.aeronSinkStopped(channel, streamId) completed.complete(completedValue) } - } // InHandler override def onPush(): Unit = { @@ -237,11 +236,10 @@ private[remote] class AeronSink( failStage(cause) } - override def onUpstreamFinish(): Unit = { + override def onUpstreamFinish(): Unit = // flush outstanding offer before completing stage if (!offerTaskInProgress) super.onUpstreamFinish() - } override def onUpstreamFailure(cause: Throwable): Unit = { completedValue = Failure(cause) diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/aeron/AeronSource.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/aeron/AeronSource.scala index 137b9a298ed..6c53dc8cb64 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/aeron/AeronSource.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/aeron/AeronSource.scala @@ -44,17 +44,15 @@ private[remote] object AeronSource { sub: Subscription, handler: MessageHandler, onMessage: AsyncCallback[EnvelopeBuffer]): () => Boolean = { () => - { - handler.reset() - sub.poll(handler.fragmentsHandler, 1) - val msg = handler.messageReceived - handler.reset() // for GC - if (msg ne null) { - onMessage.invoke(msg) - true - } else - false - } + handler.reset() + sub.poll(handler.fragmentsHandler, 1) + val msg = handler.messageReceived + handler.reset() // for GC + if (msg ne null) { + onMessage.invoke(msg) + true + } else + false } class MessageHandler(pool: EnvelopeBufferPool) { @@ -129,9 +127,8 @@ private[remote] class AeronSource( override protected def logSource = classOf[AeronSource] - override def preStart(): Unit = { + override def preStart(): Unit = flightRecorder.aeronSourceStarted(channel, streamId) - } override def postStop(): Unit = { taskRunner.command(Remove(addPollTask.task)) @@ -197,14 +194,13 @@ private[remote] class AeronSource( private def freeSessionBuffers(): Unit = if (!delegatingToTaskRunner) { - def loop(remaining: List[Int]): Unit = { + def loop(remaining: List[Int]): Unit = remaining match { case Nil => case sessionId :: tail => messageHandler.fragmentsHandler.freeSessionBuffer(sessionId) loop(tail) } - } loop(pendingUnavailableImages) pendingUnavailableImages = Nil @@ -212,9 +208,9 @@ private[remote] class AeronSource( // External callback from ResourceLifecycle def onUnavailableImage(sessionId: Int): Unit = - try { + try onUnavailableImageCb.invoke(sessionId) - } catch { + catch { case NonFatal(_) => // just in case it's called before stage is initialized, ignore } diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/aeron/ArteryAeronUdpTransport.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/aeron/ArteryAeronUdpTransport.scala index b209e50ce55..af73d877952 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/aeron/ArteryAeronUdpTransport.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/aeron/ArteryAeronUdpTransport.scala @@ -93,7 +93,7 @@ private[remote] class ArteryAeronUdpTransport(_system: ExtendedActorSystem, _pro flightRecorder.transportTaskRunnerStarted() } - private def startMediaDriver(): Unit = { + private def startMediaDriver(): Unit = if (settings.Advanced.Aeron.EmbeddedMediaDriver) { val driverContext = new MediaDriver.Context if (settings.Advanced.Aeron.AeronDirectoryName.nonEmpty) { @@ -147,7 +147,6 @@ private[remote] class ArteryAeronUdpTransport(_system: ExtendedActorSystem, _pro throw new IllegalStateException("media driver started more than once") } } - } private def aeronDir: String = mediaDriver.get match { case Some(driver) => driver.aeronDirectoryName @@ -167,12 +166,12 @@ private[remote] class ArteryAeronUdpTransport(_system: ExtendedActorSystem, _pro log.warning("Couldn't close Aeron embedded media driver due to [{}]", e) } - try { + try if (settings.Advanced.Aeron.DeleteAeronDirectory) { IoUtil.delete(new File(driver.aeronDirectoryName), false) flightRecorder.transportMediaFileDeleted() } - } catch { + catch { case NonFatal(e) => log.warning( "Couldn't delete Aeron embedded media driver files in [{}] due to [{}]", @@ -190,10 +189,9 @@ private[remote] class ArteryAeronUdpTransport(_system: ExtendedActorSystem, _pro ctx.threadFactory(system.threadFactory) ctx.availableImageHandler(new AvailableImageHandler { - override def onAvailableImage(img: Image): Unit = { + override def onAvailableImage(img: Image): Unit = if (log.isDebugEnabled) log.debug(s"onAvailableImage from ${img.sourceIdentity} session ${img.sessionId}") - } }) ctx.unavailableImageHandler(new UnavailableImageHandler { override def onUnavailableImage(img: Image): Unit = { @@ -211,7 +209,7 @@ private[remote] class ArteryAeronUdpTransport(_system: ExtendedActorSystem, _pro ctx.errorHandler(new ErrorHandler { private val fatalErrorOccured = new AtomicBoolean - override def onError(cause: Throwable): Unit = { + override def onError(cause: Throwable): Unit = cause match { case e: ConductorServiceTimeoutException => handleFatalError(e) case e: DriverTimeoutException => handleFatalError(e) @@ -219,9 +217,8 @@ private[remote] class ArteryAeronUdpTransport(_system: ExtendedActorSystem, _pro case _ => log.error(cause, s"Aeron error, $cause") } - } - private def handleFatalError(cause: Throwable): Unit = { + private def handleFatalError(cause: Throwable): Unit = if (fatalErrorOccured.compareAndSet(false, true)) { if (!isShutdown) { log.error( @@ -240,7 +237,6 @@ private[remote] class ArteryAeronUdpTransport(_system: ExtendedActorSystem, _pro } } else throw new AeronTerminated(cause) - } }) ctx.aeronDirectoryName(aeronDir) @@ -334,7 +330,7 @@ private[remote] class ArteryAeronUdpTransport(_system: ExtendedActorSystem, _pro settings.Advanced.Aeron.IdleCpuLevel < 5) 0 // also don't spin for small IdleCpuLevels else 50 * settings.Advanced.Aeron.IdleCpuLevel - 240 - override protected def bindInboundStreams(): (Int, Int) = { + override protected def bindInboundStreams(): (Int, Int) = (settings.Canonical.Port, settings.Bind.Port) match { case (0, 0) => val p = autoSelectPort(settings.Bind.Hostname) @@ -346,7 +342,6 @@ private[remote] class ArteryAeronUdpTransport(_system: ExtendedActorSystem, _pro case _ => (settings.Canonical.Port, settings.Bind.Port) } - } override protected def runInboundStreams(port: Int, bindPort: Int): Unit = { val inboundChannel = s"aeron:udp?endpoint=${settings.Bind.Hostname}:$bindPort" @@ -462,7 +457,7 @@ private[remote] class ArteryAeronUdpTransport(_system: ExtendedActorSystem, _pro })) } - override protected def shutdownTransport(): Future[Done] = { + override protected def shutdownTransport(): Future[Done] = taskRunner .stop() .map { _ => @@ -477,7 +472,6 @@ private[remote] class ArteryAeronUdpTransport(_system: ExtendedActorSystem, _pro Done }(system.dispatchers.internalDispatcher) - } def autoSelectPort(hostname: String): Int = { import java.net.InetSocketAddress diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/aeron/TaskRunner.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/aeron/TaskRunner.scala index 902b0e7debd..edbc5389e63 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/aeron/TaskRunner.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/aeron/TaskRunner.scala @@ -51,7 +51,7 @@ private[pekko] object TaskRunner { def add(e: T): Unit = { val size = elements.length - @tailrec def tryAdd(i: Int): Unit = { + @tailrec def tryAdd(i: Int): Unit = if (i == size) { doubleCapacity() elements(i) = e @@ -59,20 +59,18 @@ private[pekko] object TaskRunner { elements(i) = e else tryAdd(i + 1) // recursive - } tryAdd(0) } def remove(e: T): Unit = { val size = elements.length - @tailrec def tryRemove(i: Int): Unit = { + @tailrec def tryRemove(i: Int): Unit = if (i == size) () // not found else if (elements(i) == e) elements(i) = null.asInstanceOf[T] else tryRemove(i + 1) // recursive - } tryRemove(0) } @@ -103,7 +101,7 @@ private[pekko] object TaskRunner { elements.filterNot(_ eq null).mkString("[", ",", "]") } - def createIdleStrategy(idleCpuLevel: Int): IdleStrategy = { + def createIdleStrategy(idleCpuLevel: Int): IdleStrategy = if (idleCpuLevel == 1) new SleepingIdleStrategy(MILLISECONDS.toNanos(1)) else if (idleCpuLevel == 10) @@ -117,7 +115,6 @@ private[pekko] object TaskRunner { val maxParkNanos = MICROSECONDS.toNanos(280 - 30 * idleCpuLevel) new BackoffIdleStrategy(spinning, yielding, minParkNanos, maxParkNanos) } - } } /** @@ -150,11 +147,10 @@ private[pekko] class TaskRunner(system: ExtendedActorSystem, val idleCpuLevel: I shutdown.future } - def command(cmd: Command): Unit = { + def command(cmd: Command): Unit = cmdQueue.add(cmd) - } - override def run(): Unit = { + override def run(): Unit = try { running = true while (running) { @@ -172,7 +168,6 @@ private[pekko] class TaskRunner(system: ExtendedActorSystem, val idleCpuLevel: I case NonFatal(e) => log.error(e, e.getMessage) } - } private def executeTasks(): Unit = { val elements = tasks.all @@ -181,12 +176,12 @@ private[pekko] class TaskRunner(system: ExtendedActorSystem, val idleCpuLevel: I while (i < size) { val task = elements(i) if (task ne null) - try { + try if (task()) { tasks.remove(task) reset = true } - } catch { + catch { case NonFatal(e) => log.error(e, "Task failed") tasks.remove(task) @@ -195,7 +190,7 @@ private[pekko] class TaskRunner(system: ExtendedActorSystem, val idleCpuLevel: I } } - private def processCommand(cmd: Command): Unit = { + private def processCommand(cmd: Command): Unit = cmd match { case null => // no command case Add(task) => tasks.add(task) @@ -206,6 +201,5 @@ private[pekko] class TaskRunner(system: ExtendedActorSystem, val idleCpuLevel: I while (cmdQueue.poll() != null) () // gc friendly shutdown.trySuccess(Done) } - } } diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/compress/CompressionTable.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/compress/CompressionTable.scala index d91975ed9d6..16e3acda7f7 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/compress/CompressionTable.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/compress/CompressionTable.scala @@ -106,10 +106,9 @@ private[remote] object CompressionTable { } def compareBy2ndValue[T]: Comparator[Tuple2[T, Int]] = CompareBy2ndValue.asInstanceOf[Comparator[(T, Int)]] - private def newObject2IntHashMap[T](initialCapacity: Int): Object2IntHashMap[T] = { + private def newObject2IntHashMap[T](initialCapacity: Int): Object2IntHashMap[T] = // import to use shouldAvoidAllocation = false because of concurrent access of dictionary new Object2IntHashMap[T](initialCapacity, Hashing.DEFAULT_LOAD_FACTOR, NotCompressedId, false) - } def empty[T] = new CompressionTable[T](0, 0, newObject2IntHashMap(2)) diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/compress/InboundCompressions.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/compress/InboundCompressions.scala index 350047a79e8..b6986d9b4da 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/compress/InboundCompressions.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/compress/InboundCompressions.scala @@ -106,12 +106,11 @@ private[remote] final class InboundCompressionsImpl( actorRefsIn(originUid).increment(address, ref, n) } - override def confirmActorRefCompressionAdvertisement(originUid: Long, tableVersion: Byte): Unit = { + override def confirmActorRefCompressionAdvertisement(originUid: Long, tableVersion: Byte): Unit = _actorRefsIns.get(originUid) match { case null => // ignore case a => a.confirmAdvertisement(tableVersion, gaveUp = false) } - } /** Send compression table advertisement over control stream. Should be called from Decoder. */ override def runNextActorRefAdvertisement(): Unit = { @@ -138,12 +137,11 @@ private[remote] final class InboundCompressionsImpl( if (ArterySettings.Compression.Debug) println(s"[compress] hitClassManifest($originUid, $address, $manifest, $n)") classManifestsIn(originUid).increment(address, manifest, n) } - override def confirmClassManifestCompressionAdvertisement(originUid: Long, tableVersion: Byte): Unit = { + override def confirmClassManifestCompressionAdvertisement(originUid: Long, tableVersion: Byte): Unit = _classManifestsIns.get(originUid) match { case null => // ignore case a => a.confirmAdvertisement(tableVersion, gaveUp = false) } - } /** Send compression table advertisement over control stream. Should be called from Decoder. */ override def runNextClassManifestAdvertisement(): Unit = { @@ -192,10 +190,9 @@ private[remote] final class InboundActorRefCompression( heavyHitters: TopHeavyHitters[ActorRef]) extends InboundCompression[ActorRef](log, settings, originUid, inboundContext, heavyHitters) { - override def increment(remoteAddress: Address, value: ActorRef, n: Long): Unit = { + override def increment(remoteAddress: Address, value: ActorRef, n: Long): Unit = // don't count PromiseActorRefs as they are used only once and becomes a sort of memory leak if (!InternalActorRef.isTemporaryRef(value)) super.increment(remoteAddress, value, n) - } override def decompress(tableVersion: Byte, idx: Int): OptionVal[ActorRef] = super.decompressInternal(tableVersion, idx, 0) @@ -286,20 +283,19 @@ private[remote] object InboundCompression { advertisementInProgress: Option[CompressionTable[T]], keepOldTables: Int) { - def selectTable(version: Int): OptionVal[DecompressionTable[T]] = { + def selectTable(version: Int): OptionVal[DecompressionTable[T]] = if (activeTable.version == version) { if (ArterySettings.Compression.Debug) println(s"[compress] Found table [version: $version], was [ACTIVE]$activeTable") OptionVal.Some(activeTable) } else { - @tailrec def find(tables: List[DecompressionTable[T]]): OptionVal[DecompressionTable[T]] = { + @tailrec def find(tables: List[DecompressionTable[T]]): OptionVal[DecompressionTable[T]] = tables match { case Nil => OptionVal.None case t :: tail => if (t.version == version) OptionVal.Some(t) else find(tail) } - } val found = find(oldTables) if (ArterySettings.Compression.Debug) { @@ -314,7 +310,6 @@ private[remote] object InboundCompression { } found } - } def startUsingNextTable(): Tables[T] = { def incrementTableVersion(version: Byte): Byte = @@ -415,7 +410,7 @@ private[remote] abstract class InboundCompression[T >: Null]( } } - final def confirmAdvertisement(tableVersion: Byte, gaveUp: Boolean): Unit = { + final def confirmAdvertisement(tableVersion: Byte, gaveUp: Boolean): Unit = tables.advertisementInProgress match { case Some(inProgress) if tableVersion == inProgress.version => tables = tables.startUsingNextTable() @@ -435,8 +430,6 @@ private[remote] abstract class InboundCompression[T >: Null]( // already confirmed } - } - /** * Add `n` occurrence for the given key and call `heavyHittedDetected` if element has become a heavy hitter. * Empty keys are omitted. @@ -448,9 +441,8 @@ private[remote] abstract class InboundCompression[T >: Null]( } /** Mutates heavy hitters */ - private def addAndCheckIfheavyHitterDetected(value: T, count: Long): Boolean = { + private def addAndCheckIfheavyHitterDetected(value: T, count: Long): Boolean = heavyHitters.update(value, count) - } /* ==== TABLE ADVERTISEMENT ==== */ diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/compress/TopHeavyHitters.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/compress/TopHeavyHitters.scala index be6e27f5327..3ac7acf4d7d 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/compress/TopHeavyHitters.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/compress/TopHeavyHitters.scala @@ -116,10 +116,9 @@ private[remote] final class TopHeavyHitters[T >: Null](val max: Int)(implicit cl new Iterator[T] { var i = 0 - @tailrec override final def hasNext: Boolean = { + @tailrec override final def hasNext: Boolean = // note that this is using max and not adjustedMax so will be empty if disabled (max=0) (i < self.max) && ((value != null) || { next(); hasNext }) - } override final def next(): T = { val v = value @@ -205,7 +204,7 @@ private[remote] final class TopHeavyHitters[T >: Null](val max: Int)(implicit cl * equality). */ private def findItemIdx(searchFromIndex: Int, hashCode: HashCodeVal, o: T): Int = { - @tailrec def loop(index: Int, start: Int, hashCodeVal: HashCodeVal, o: T): Int = { + @tailrec def loop(index: Int, start: Int, hashCodeVal: HashCodeVal, o: T): Int = // Scanned the whole table, returned to the start => element not in table if (index == start) -1 else if (hashCodeVal.get == hashes(index)) { // First check on hashcode to avoid costly equality @@ -223,7 +222,6 @@ private[remote] final class TopHeavyHitters[T >: Null](val max: Int)(implicit cl // hashcode did not match the one in slot, move to next index (linear probing) loop((index + 1) & mask, start, hashCodeVal, o) } - } if (searchFromIndex == -1) -1 else if (Objects.equals(items(searchFromIndex), o)) searchFromIndex @@ -348,14 +346,13 @@ private[remote] final class TopHeavyHitters[T >: Null](val max: Int)(implicit cl /** * Remove value from hash-table based on position. */ - private def removeHash(index: Int): Unit = { + private def removeHash(index: Int): Unit = if (index >= 0) { items(index) = null heapIndex(index) = -1 hashes(index) = 0 weights(index) = 0 } - } /** * Insert value in hash-table. @@ -370,9 +367,8 @@ private[remote] final class TopHeavyHitters[T >: Null](val max: Int)(implicit cl */ private def insert(hashCode: HashCodeVal, item: T, count: Long): Int = { var index: Int = hashCode.get & mask - while (items(index) != null) { + while (items(index) != null) index = (index + 1) & mask - } hashes(index) = hashCode.get items(index) = item weights(index) = count @@ -400,9 +396,8 @@ private[remote] final class TopHeavyHitters[T >: Null](val max: Int)(implicit cl * is empty, this returns a negative index. * Implemented by looking at the top of the heap and extracting the index which is O(1). */ - private def lowestHitterIndex: Int = { + private def lowestHitterIndex: Int = heap(0) - } override def toString = s"${getClass.getSimpleName}(max:$max)" diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/tcp/ArteryTcpTransport.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/tcp/ArteryTcpTransport.scala index 21a99e1ba16..98802e30ab8 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/tcp/ArteryTcpTransport.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/tcp/ArteryTcpTransport.scala @@ -159,7 +159,7 @@ private[remote] class ArteryTcpTransport( def connectionFlowWithRestart: Flow[ByteString, ByteString, NotUsed] = { val restartCount = new AtomicInteger(0) - def logConnect(): Unit = { + def logConnect(): Unit = if (log.isDebugEnabled) log.debug( RemoteLogMarker.connect( @@ -167,9 +167,8 @@ private[remote] class ArteryTcpTransport( outboundContext.associationState.uniqueRemoteAddress().map(_.uid)), "Outbound connection opened to [{}]", outboundContext.remoteAddress) - } - def logDisconnected(): Unit = { + def logDisconnected(): Unit = if (log.isDebugEnabled) log.debug( RemoteLogMarker.disconnected( @@ -177,14 +176,13 @@ private[remote] class ArteryTcpTransport( outboundContext.associationState.uniqueRemoteAddress().map(_.uid)), "Outbound connection closed to [{}]", outboundContext.remoteAddress) - } val flowFactory = () => { val onFailureLogLevel = if (restartCount.incrementAndGet() == 1) Logging.WarningLevel else Logging.DebugLevel def flow(controlIdleKillSwitch: OptionVal[SharedKillSwitch]) = Flow[ByteString] - .via(Flow.lazyFlow(() => { + .via(Flow.lazyFlow { () => // only open the actual connection if any new messages are sent logConnect() flightRecorder.tcpOutboundConnected(outboundContext.remoteAddress, streamName(streamId)) @@ -192,7 +190,7 @@ private[remote] class ArteryTcpTransport( outboundContext.asInstanceOf[Association].setControlIdleKillSwitch(controlIdleKillSwitch) Flow[ByteString].prepend(Source.single(TcpFraming.encodeConnectionHeader(streamId))).via(connectionFlow) - })) + }) .mapError { case ArteryTransport.ShutdownSignal => ArteryTransport.ShutdownSignal case e => @@ -317,7 +315,7 @@ private[remote] class ArteryTcpTransport( // are attached to these via a MergeHub. val (controlStream, controlStreamCompleted) = runInboundControlStream() val (ordinaryMessagesStream, ordinaryMessagesStreamCompleted) = runInboundOrdinaryMessagesStream() - val (largeMessagesStream, largeMessagesStreamCompleted) = { + val (largeMessagesStream, largeMessagesStreamCompleted) = if (largeMessageChannelEnabled) runInboundLargeMessagesStream() else @@ -326,7 +324,6 @@ private[remote] class ArteryTcpTransport( .map(_ => log.warning("Dropping large message, missing large-message-destinations configuration.")) .to(Sink.ignore), Promise[Done]().future) // never completed, not enabled - } // An inbound connection will only use one of the control, ordinary or large streams, but we have to // attach it to all and select via Partition and the streamId in the frame header. Conceptually it @@ -337,14 +334,14 @@ private[remote] class ArteryTcpTransport( val inboundStream = Sink.fromGraph(GraphDSL.create() { implicit b => import GraphDSL.Implicits._ val partition = b.add(Partition[EnvelopeBuffer](3, - env => { + env => env.streamId match { case OrdinaryStreamId => 1 case ControlStreamId => 0 case LargeStreamId => 2 case other => throw new IllegalArgumentException(s"Unexpected streamId [$other]") } - })) + )) partition.out(0) ~> controlStream partition.out(1) ~> ordinaryMessagesStream partition.out(2) ~> largeMessagesStream @@ -353,7 +350,7 @@ private[remote] class ArteryTcpTransport( // If something in the inboundConnectionFlow fails, e.g. framing, the connection will be teared down, // but other parts of the inbound streams don't have to restarted. - val newInboundConnectionFlow = { + val newInboundConnectionFlow = Flow[ByteString] .via(inboundKillSwitch.flow) // must create new FlightRecorder event sink for each connection because they can't be shared @@ -361,7 +358,6 @@ private[remote] class ArteryTcpTransport( .alsoTo(inboundStream) .filter(_ => false) // don't send back anything in this TCP socket .map(_ => ByteString.empty) // make it a Flow[ByteString] again - } firstConnectionFlow.trySuccess(newInboundConnectionFlow) inboundConnectionFlow = Future.successful(newInboundConnectionFlow) @@ -503,7 +499,7 @@ private[remote] class ArteryTcpTransport( } } - private def unbind(): Future[Done] = { + private def unbind(): Future[Done] = serverBinding match { case Some(binding) => implicit val ec = system.dispatchers.internalDispatcher @@ -516,6 +512,5 @@ private[remote] class ArteryTcpTransport( case None => Future.successful(Done) } - } } diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/tcp/ConfigSSLEngineProvider.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/tcp/ConfigSSLEngineProvider.scala index eca77f416ea..167fce582db 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/tcp/ConfigSSLEngineProvider.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/tcp/ConfigSSLEngineProvider.scala @@ -77,7 +77,7 @@ class ConfigSSLEngineProvider(protected val config: Config, protected val log: M constructContext() } - private def constructContext(): SSLContext = { + private def constructContext(): SSLContext = try { val rng = createSecureRandom() val ctx = SSLContext.getInstance(SSLProtocol) @@ -95,7 +95,6 @@ class ConfigSSLEngineProvider(protected val config: Config, protected val log: M "Server SSL connection could not be established because SSL context could not be constructed", e) } - } /** * Subclass may override to customize loading of `KeyStore` @@ -135,9 +134,8 @@ class ConfigSSLEngineProvider(protected val config: Config, protected val log: M override def createClientSSLEngine(hostname: String, port: Int): SSLEngine = createSSLEngine(pekko.stream.Client, hostname, port) - private def createSSLEngine(role: TLSRole, hostname: String, port: Int): SSLEngine = { + private def createSSLEngine(role: TLSRole, hostname: String, port: Int): SSLEngine = createSSLEngine(sslContext, role, hostname, port) - } private def createSSLEngine(sslContext: SSLContext, role: TLSRole, hostname: String, port: Int): SSLEngine = { diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/tcp/SecureRandomFactory.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/tcp/SecureRandomFactory.scala index 8a87688f025..e6504d1957d 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/tcp/SecureRandomFactory.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/tcp/SecureRandomFactory.scala @@ -32,13 +32,11 @@ import com.typesafe.config.Config */ @InternalApi // extracted as a method for testing - private[tcp] def rngConfig(config: Config) = { + private[tcp] def rngConfig(config: Config) = config.getString("random-number-generator") - } - def createSecureRandom(config: Config, log: MarkerLoggingAdapter): SecureRandom = { + def createSecureRandom(config: Config, log: MarkerLoggingAdapter): SecureRandom = createSecureRandom(rngConfig(config), log) - } def createSecureRandom(randomNumberGenerator: String, log: MarkerLoggingAdapter): SecureRandom = { val rng = randomNumberGenerator match { diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/tcp/ssl/RotatingKeysSSLEngineProvider.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/tcp/ssl/RotatingKeysSSLEngineProvider.scala index 4b400ebba10..f926c4db5fa 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/tcp/ssl/RotatingKeysSSLEngineProvider.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/tcp/ssl/RotatingKeysSSLEngineProvider.scala @@ -81,7 +81,7 @@ final class RotatingKeysSSLEngineProvider(val config: Config, protected val log: /** INTERNAL API */ @InternalApi private[ssl] def getSSLContext() = getContext().context - private def getContext(): ConfiguredContext = { + private def getContext(): ConfiguredContext = cachedContext match { case Some(CachedContext(_, expired)) if expired.isOverdue() => // Multiple connection requests arriving when the cache is overdue will @@ -98,7 +98,6 @@ final class RotatingKeysSSLEngineProvider(val config: Config, protected val log: cachedContext = Some(CachedContext(context, SSLContextCacheTime.fromNow)) context } - } // Construct the cached instance private def constructContext(): ConfiguredContext = { @@ -122,7 +121,7 @@ final class RotatingKeysSSLEngineProvider(val config: Config, protected val log: } } - private def readFiles(): (PrivateKey, X509Certificate, Certificate) = { + private def readFiles(): (PrivateKey, X509Certificate, Certificate) = try { val cacert: Certificate = PemManagersProvider.loadCertificate(SSLCACertFile) val cert: X509Certificate = PemManagersProvider.loadCertificate(SSLCertFile).asInstanceOf[X509Certificate] @@ -136,7 +135,6 @@ final class RotatingKeysSSLEngineProvider(val config: Config, protected val log: case e: IOException => throw new SslTransportException("Server SSL connection could not be established because: " + e.getMessage, e) } - } // Implement the SSLEngine create methods from the trait override def createServerSSLEngine(hostname: String, port: Int): SSLEngine = diff --git a/remote/src/main/scala/org/apache/pekko/remote/artery/tcp/ssl/SSLEngineConfig.scala b/remote/src/main/scala/org/apache/pekko/remote/artery/tcp/ssl/SSLEngineConfig.scala index 545e0ed1be1..8ed4c56cecd 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/artery/tcp/ssl/SSLEngineConfig.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/artery/tcp/ssl/SSLEngineConfig.scala @@ -31,18 +31,16 @@ private[tcp] class SSLEngineConfig(config: Config) { private[tcp] val SSLProtocol: String = config.getString("protocol") private[tcp] val SSLEnabledAlgorithms: Set[String] = immutableSeq(config.getStringList("enabled-algorithms")).toSet - private[tcp] val SSLRequireMutualAuthentication: Boolean = { + private[tcp] val SSLRequireMutualAuthentication: Boolean = if (config.hasPath("require-mutual-authentication")) config.getBoolean("require-mutual-authentication") else false - } - private[tcp] val HostnameVerification: Boolean = { + private[tcp] val HostnameVerification: Boolean = if (config.hasPath("hostname-verification")) config.getBoolean("hostname-verification") else false - } private[tcp] val SSLContextCacheTime: FiniteDuration = if (config.hasPath("ssl-context-cache-ttl")) config.getDuration("ssl-context-cache-ttl").toMillis.millis diff --git a/remote/src/main/scala/org/apache/pekko/remote/serialization/ArteryMessageSerializer.scala b/remote/src/main/scala/org/apache/pekko/remote/serialization/ArteryMessageSerializer.scala index fc19989d0d0..91a474222c3 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/serialization/ArteryMessageSerializer.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/serialization/ArteryMessageSerializer.scala @@ -298,7 +298,7 @@ private[pekko] final class ArteryMessageSerializer(val system: ExtendedActorSyst def serializeFlushAck(expectedAcks: Int): ArteryControlFormats.FlushAck = ArteryControlFormats.FlushAck.newBuilder().setExpectedAcks(expectedAcks).build() - def deserializeFlushAck(bytes: Array[Byte]): FlushAck = { + def deserializeFlushAck(bytes: Array[Byte]): FlushAck = if (bytes.isEmpty) FlushAck(1) // for wire compatibility with Akka 2.6.16 or earlier, which didn't include the expectedAcks else { @@ -306,5 +306,4 @@ private[pekko] final class ArteryMessageSerializer(val system: ExtendedActorSyst val expectedAcks = if (msg.hasExpectedAcks) msg.getExpectedAcks else 1 FlushAck(expectedAcks) } - } } diff --git a/remote/src/main/scala/org/apache/pekko/remote/serialization/MiscMessageSerializer.scala b/remote/src/main/scala/org/apache/pekko/remote/serialization/MiscMessageSerializer.scala index 897f6e05ba9..ff93efecd22 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/serialization/MiscMessageSerializer.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/serialization/MiscMessageSerializer.scala @@ -103,19 +103,17 @@ class MiscMessageSerializer(val system: ExtendedActorSystem) extends SerializerW private def serializeSome(someValue: Any): Array[Byte] = ContainerFormats.Option.newBuilder().setValue(payloadSupport.payloadBuilder(someValue)).build().toByteArray - private def serializeOptional(opt: Optional[_]): Array[Byte] = { + private def serializeOptional(opt: Optional[_]): Array[Byte] = if (opt.isPresent) ContainerFormats.Option.newBuilder().setValue(payloadSupport.payloadBuilder(opt.get)).build().toByteArray else ParameterlessSerializedMessage - } private def serializeActorRef(ref: ActorRef): Array[Byte] = actorRefBuilder(ref).build().toByteArray - private def serializeHeartbeatRsp(hbrsp: RemoteWatcher.HeartbeatRsp): Array[Byte] = { + private def serializeHeartbeatRsp(hbrsp: RemoteWatcher.HeartbeatRsp): Array[Byte] = ContainerFormats.WatcherHeartbeatResponse.newBuilder().setUid(hbrsp.addressUid).build().toByteArray - } private def serializeRemoteScope(rs: RemoteScope): Array[Byte] = { val builder = WireFormats.RemoteScope.newBuilder() @@ -136,7 +134,7 @@ class MiscMessageSerializer(val system: ExtendedActorSystem) extends SerializerW // no specific message, serialized id and manifest together with payload is enough (no wrapping overhead) payloadSupport.payloadBuilder(r.getValue).build().toByteArray - def serializeStatusReplyError(r: StatusReply[_]): Array[Byte] = { + def serializeStatusReplyError(r: StatusReply[_]): Array[Byte] = r.getError match { case em: StatusReply.ErrorMessage => // somewhat optimized for the recommended usage, avoiding the additional payload metadata @@ -146,7 +144,6 @@ class MiscMessageSerializer(val system: ExtendedActorSystem) extends SerializerW // no specific message, serialized id and manifest together with payload is enough (less wrapping overhead) payloadSupport.payloadBuilder(ex).build().toByteArray } - } private def serializeActorInitializationException(ex: ActorInitializationException): Array[Byte] = { val builder = ContainerFormats.ActorInitializationException.newBuilder() @@ -166,9 +163,8 @@ class MiscMessageSerializer(val system: ExtendedActorSystem) extends SerializerW builder.build().toByteArray } - private def serializeConfig(c: Config): Array[Byte] = { + private def serializeConfig(c: Config): Array[Byte] = c.root.render(ConfigRenderOptions.concise()).getBytes(StandardCharsets.UTF_8) - } private def protoForAddressData(address: Address): AddressData.Builder = address match { @@ -226,21 +222,17 @@ class MiscMessageSerializer(val system: ExtendedActorSystem) extends SerializerW builder.build().toByteArray } - private def serializeBalancingPool(bp: BalancingPool): Array[Byte] = { + private def serializeBalancingPool(bp: BalancingPool): Array[Byte] = buildGenericRoutingPool(bp.nrOfInstances, bp.routerDispatcher, bp.usePoolDispatcher, bp.resizer).toByteArray - } - private def serializeBroadcastPool(bp: BroadcastPool): Array[Byte] = { + private def serializeBroadcastPool(bp: BroadcastPool): Array[Byte] = buildGenericRoutingPool(bp.nrOfInstances, bp.routerDispatcher, bp.usePoolDispatcher, bp.resizer).toByteArray - } - private def serializeRandomPool(rp: RandomPool): Array[Byte] = { + private def serializeRandomPool(rp: RandomPool): Array[Byte] = buildGenericRoutingPool(rp.nrOfInstances, rp.routerDispatcher, rp.usePoolDispatcher, rp.resizer).toByteArray - } - private def serializeRoundRobinPool(rp: RoundRobinPool): Array[Byte] = { + private def serializeRoundRobinPool(rp: RoundRobinPool): Array[Byte] = buildGenericRoutingPool(rp.nrOfInstances, rp.routerDispatcher, rp.usePoolDispatcher, rp.resizer).toByteArray - } private def serializeScatterGatherFirstCompletedPool(sgp: ScatterGatherFirstCompletedPool): Array[Byte] = { val builder = WireFormats.ScatterGatherPool.newBuilder() @@ -292,9 +284,8 @@ class MiscMessageSerializer(val system: ExtendedActorSystem) extends SerializerW case TimeUnit.DAYS => WireFormats.TimeUnit.DAYS } - private def buildFiniteDuration(duration: FiniteDuration): WireFormats.FiniteDuration = { + private def buildFiniteDuration(duration: FiniteDuration): WireFormats.FiniteDuration = WireFormats.FiniteDuration.newBuilder().setValue(duration.length).setUnit(timeUnitToWire(duration.unit)).build() - } private def buildAddressData(address: Address): WireFormats.AddressData = { val builder = WireFormats.AddressData.newBuilder() @@ -453,23 +444,21 @@ class MiscMessageSerializer(val system: ExtendedActorSystem) extends SerializerW private def deserializeActorRef(actorRef: ContainerFormats.ActorRef): ActorRef = serialization.system.provider.resolveActorRef(actorRef.getPath) - private def deserializeOption(bytes: Array[Byte]): Option[Any] = { + private def deserializeOption(bytes: Array[Byte]): Option[Any] = if (bytes.length == 0) None else { val optionProto = ContainerFormats.Option.parseFrom(bytes) Some(payloadSupport.deserializePayload(optionProto.getValue)) } - } - private def deserializeOptional(bytes: Array[Byte]): Optional[Any] = { + private def deserializeOptional(bytes: Array[Byte]): Optional[Any] = if (bytes.length == 0) Optional.empty() else { val optionProto = ContainerFormats.Option.parseFrom(bytes) Optional.of(payloadSupport.deserializePayload(optionProto.getValue)) } - } private def deserializeStatusSuccess(bytes: Array[Byte]): Status.Success = Status.Success(payloadSupport.deserializePayload(ContainerFormats.Payload.parseFrom(bytes))) @@ -490,31 +479,28 @@ class MiscMessageSerializer(val system: ExtendedActorSystem) extends SerializerW private def deserializeAddressData(bytes: Array[Byte]): Address = addressFromDataProto(WireFormats.AddressData.parseFrom(bytes)) - private def addressFromDataProto(a: WireFormats.AddressData): Address = { + private def addressFromDataProto(a: WireFormats.AddressData): Address = Address( a.getProtocol, a.getSystem, // technically the presence of hostname and port are guaranteed, see our serializeAddressData if (a.hasHostname) Some(a.getHostname) else None, if (a.hasPort) Some(a.getPort) else None) - } - private def addressFromProto(a: ArteryControlFormats.Address): Address = { + private def addressFromProto(a: ArteryControlFormats.Address): Address = Address( a.getProtocol, a.getSystem, // technically the presence of hostname and port are guaranteed, see our serializeAddressData if (a.hasHostname) Some(a.getHostname) else None, if (a.hasPort) Some(a.getPort) else None) - } private def deserializeUniqueAddress(bytes: Array[Byte]): UniqueAddress = { val u = ArteryControlFormats.UniqueAddress.parseFrom(bytes) UniqueAddress(addressFromProto(u.getAddress), u.getUid) } - private def deserializeHeartbeatRsp(bytes: Array[Byte]): RemoteWatcher.HeartbeatRsp = { + private def deserializeHeartbeatRsp(bytes: Array[Byte]): RemoteWatcher.HeartbeatRsp = RemoteWatcher.HeartbeatRsp(ContainerFormats.WatcherHeartbeatResponse.parseFrom(bytes).getUid.toInt) - } private def deserializeActorInitializationException(bytes: Array[Byte]): ActorInitializationException = { val serializedEx = ContainerFormats.ActorInitializationException.parseFrom(bytes) @@ -542,10 +528,9 @@ class MiscMessageSerializer(val system: ExtendedActorSystem) extends SerializerW RemoteScope(deserializeAddressData(rs.getNode)) } - private def deserializeConfig(bytes: Array[Byte]): Config = { + private def deserializeConfig(bytes: Array[Byte]): Config = if (bytes.isEmpty) EmptyConfig else ConfigFactory.parseString(new String(bytes, StandardCharsets.UTF_8)) - } private def deserializeFromConfig(bytes: Array[Byte]): FromConfig = if (bytes.isEmpty) FromConfig @@ -659,7 +644,6 @@ class MiscMessageSerializer(val system: ExtendedActorSystem) extends SerializerW private def deserializeFiniteDuration(duration: WireFormats.FiniteDuration): FiniteDuration = FiniteDuration(duration.getValue, deserializeTimeUnit(duration.getUnit)) - private def deserializeAddressData(address: WireFormats.AddressData): Address = { + private def deserializeAddressData(address: WireFormats.AddressData): Address = Address(address.getProtocol, address.getSystem, address.getHostname, address.getPort) - } } diff --git a/remote/src/main/scala/org/apache/pekko/remote/serialization/ProtobufSerializer.scala b/remote/src/main/scala/org/apache/pekko/remote/serialization/ProtobufSerializer.scala index d52f00d331f..56c4f6f2adc 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/serialization/ProtobufSerializer.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/serialization/ProtobufSerializer.scala @@ -34,9 +34,8 @@ object ProtobufSerializer { * Helper to serialize an [[pekko.actor.ActorRef]] to Pekko's * protobuf representation. */ - def serializeActorRef(ref: ActorRef): ActorRefData = { + def serializeActorRef(ref: ActorRef): ActorRefData = ActorRefData.newBuilder.setPath(Serialization.serializedActorPath(ref)).build - } /** * Helper to materialize (lookup) an [[pekko.actor.ActorRef]] @@ -71,7 +70,7 @@ class ProtobufSerializer(val system: ExtendedActorSystem) extends BaseSerializer override def includeManifest: Boolean = true - override def fromBinary(bytes: Array[Byte], manifest: Option[Class[_]]): AnyRef = { + override def fromBinary(bytes: Array[Byte], manifest: Option[Class[_]]): AnyRef = manifest match { case Some(clazz) => @tailrec @@ -97,7 +96,6 @@ class ProtobufSerializer(val system: ExtendedActorSystem) extends BaseSerializer case None => throw new IllegalArgumentException("Need a protobuf message class to be able to serialize bytes using protobuf") } - } override def toBinary(obj: AnyRef): Array[Byte] = { val clazz = obj.getClass @@ -121,7 +119,7 @@ class ProtobufSerializer(val system: ExtendedActorSystem) extends BaseSerializer toByteArrayMethod().invoke(obj).asInstanceOf[Array[Byte]] } - private def checkAllowedClass(clazz: Class[_]): Unit = { + private def checkAllowedClass(clazz: Class[_]): Unit = if (!isInAllowList(clazz)) { val warnMsg = s"Can't deserialize object of type [${clazz.getName}] in [${getClass.getName}]. " + "Only classes that are on the allow list are allowed for security reasons. " + @@ -130,7 +128,6 @@ class ProtobufSerializer(val system: ExtendedActorSystem) extends BaseSerializer log.warning(LogMarker.Security, warnMsg) throw new IllegalArgumentException(warnMsg) } - } /** * Using the `serialization-bindings` as source for the allowed classes. @@ -147,22 +144,19 @@ class ProtobufSerializer(val system: ExtendedActorSystem) extends BaseSerializer * That is also possible when changing a binding from a ProtobufSerializer to another serializer (e.g. Jackson) * and still bind with the same class (interface). */ - private def isInAllowList(clazz: Class[_]): Boolean = { + private def isInAllowList(clazz: Class[_]): Boolean = isBoundToProtobufSerializer(clazz) || isInAllowListClassName(clazz) - } - private def isBoundToProtobufSerializer(clazz: Class[_]): Boolean = { + private def isBoundToProtobufSerializer(clazz: Class[_]): Boolean = try { val boundSerializer = serialization.serializerFor(clazz) boundSerializer.isInstanceOf[ProtobufSerializer] } catch { case NonFatal(_) => false // not bound } - } - private def isInAllowListClassName(clazz: Class[_]): Boolean = { + private def isInAllowListClassName(clazz: Class[_]): Boolean = allowedClassNames(clazz.getName) || allowedClassNames(clazz.getSuperclass.getName) || clazz.getInterfaces.exists(c => allowedClassNames(c.getName)) - } } diff --git a/remote/src/main/scala/org/apache/pekko/remote/serialization/SystemMessageSerializer.scala b/remote/src/main/scala/org/apache/pekko/remote/serialization/SystemMessageSerializer.scala index 58bd95d3924..f5e6aa4faa2 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/serialization/SystemMessageSerializer.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/serialization/SystemMessageSerializer.scala @@ -97,9 +97,8 @@ class SystemMessageSerializer(val system: ExtendedActorSystem) extends BaseSeria builder.build().toByteArray } - override def fromBinary(bytes: Array[Byte], manifest: Option[Class[_]]): AnyRef = { + override def fromBinary(bytes: Array[Byte], manifest: Option[Class[_]]): AnyRef = deserializeSystemMessage(SystemMessageFormats.SystemMessage.parseFrom(bytes)) - } private def deserializeSystemMessage(sysmsg: SystemMessageFormats.SystemMessage): SystemMessage = sysmsg.getType match { @@ -152,20 +151,16 @@ class SystemMessageSerializer(val system: ExtendedActorSystem) extends BaseSeria sysmsg.getDwNotificationData.getAddressTerminated) } - private def serializeThrowable(throwable: Throwable): ContainerFormats.Payload.Builder = { + private def serializeThrowable(throwable: Throwable): ContainerFormats.Payload.Builder = payloadSupport.payloadBuilder(throwable) - } - private def getCauseThrowable(msg: SystemMessageFormats.SystemMessage): Throwable = { + private def getCauseThrowable(msg: SystemMessageFormats.SystemMessage): Throwable = payloadSupport.deserializePayload(msg.getCauseData).asInstanceOf[Throwable] - } - private def serializeActorRef(actorRef: ActorRef): ContainerFormats.ActorRef.Builder = { + private def serializeActorRef(actorRef: ActorRef): ContainerFormats.ActorRef.Builder = ContainerFormats.ActorRef.newBuilder().setPath(Serialization.serializedActorPath(actorRef)) - } - private def deserializeActorRef(serializedRef: ContainerFormats.ActorRef): ActorRef = { + private def deserializeActorRef(serializedRef: ContainerFormats.ActorRef): ActorRef = serialization.system.provider.resolveActorRef(serializedRef.getPath) - } } diff --git a/remote/src/main/scala/org/apache/pekko/remote/serialization/ThrowableSupport.scala b/remote/src/main/scala/org/apache/pekko/remote/serialization/ThrowableSupport.scala index 1adee9c9ce8..07bfe8bc685 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/serialization/ThrowableSupport.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/serialization/ThrowableSupport.scala @@ -33,9 +33,8 @@ private[pekko] class ThrowableSupport(system: ExtendedActorSystem) { private val payloadSupport = new WrappedPayloadSupport(system) private val log = Logging(system, classOf[ThrowableSupport]) - def serializeThrowable(t: Throwable): Array[Byte] = { + def serializeThrowable(t: Throwable): Array[Byte] = toProtobufThrowable(t).build().toByteArray - } def toProtobufThrowable(t: Throwable): ContainerFormats.Throwable.Builder = { val b = ContainerFormats.Throwable.newBuilder().setClassName(t.getClass.getName) @@ -65,9 +64,8 @@ private[pekko] class ThrowableSupport(system: ExtendedActorSystem) { if (fileName ne null) builder.setFileName(fileName) else builder.setFileName("") } - def deserializeThrowable(bytes: Array[Byte]): Throwable = { + def deserializeThrowable(bytes: Array[Byte]): Throwable = fromProtobufThrowable(ContainerFormats.Throwable.parseFrom(bytes)) - } def fromProtobufThrowable(protoT: ContainerFormats.Throwable): Throwable = { val className = protoT.getClassName diff --git a/remote/src/main/scala/org/apache/pekko/remote/transport/AbstractTransportAdapter.scala b/remote/src/main/scala/org/apache/pekko/remote/transport/AbstractTransportAdapter.scala index 75e4c2c74a4..e36aaace105 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/transport/AbstractTransportAdapter.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/transport/AbstractTransportAdapter.scala @@ -41,14 +41,13 @@ trait TransportAdapterProvider { class TransportAdapters(system: ExtendedActorSystem) extends Extension { val settings = RARP(system).provider.remoteSettings - private val adaptersTable: Map[String, TransportAdapterProvider] = for ((name, fqn) <- settings.Adapters) yield { - name -> system.dynamicAccess + private val adaptersTable: Map[String, TransportAdapterProvider] = + for ((name, fqn) <- settings.Adapters) yield name -> system.dynamicAccess .createInstanceFor[TransportAdapterProvider](fqn, immutable.Seq.empty) .recover { case e => throw new IllegalArgumentException(s"Cannot instantiate transport adapter [$fqn]", e) } .get - } def getAdapterProvider(name: String): TransportAdapterProvider = adaptersTable.get(name) match { case Some(provider) => provider @@ -190,7 +189,7 @@ abstract class ActorTransportAdapter(wrappedTransport: Transport, system: ActorS override def interceptListen( listenAddress: Address, - listenerPromise: Future[AssociationEventListener]): Future[AssociationEventListener] = { + listenerPromise: Future[AssociationEventListener]): Future[AssociationEventListener] = registerManager().map { mgr => // Side effecting: storing the manager instance in volatile var // This is done only once: during the initialization of the protocol stack. The variable manager is not read @@ -199,7 +198,6 @@ abstract class ActorTransportAdapter(wrappedTransport: Transport, system: ActorS manager ! ListenUnderlying(listenAddress, listenerPromise) ActorAssociationEventListener(manager) } - } override def interceptAssociate(remoteAddress: Address, statusPromise: Promise[AssociationHandle]): Unit = manager ! AssociateUnderlying(remoteAddress, statusPromise) @@ -231,11 +229,11 @@ abstract class ActorTransportAdapterManager extends Actor with RequiresMessageQu def receive: Receive = { case ListenUnderlying(listenAddress, upstreamListenerFuture) => localAddress = listenAddress - upstreamListenerFuture.future.map { ListenerRegistered(_) }.pipeTo(self) + upstreamListenerFuture.future.map(ListenerRegistered(_)).pipeTo(self) case ListenerRegistered(listener) => associationListener = listener - delayedEvents.foreach { self.tell(_, Actor.noSender) } + delayedEvents.foreach(self.tell(_, Actor.noSender)) delayedEvents = immutable.Queue.empty[Any] context.become(ready) diff --git a/remote/src/main/scala/org/apache/pekko/remote/transport/FailureInjectorTransportAdapter.scala b/remote/src/main/scala/org/apache/pekko/remote/transport/FailureInjectorTransportAdapter.scala index cd3f730b7b3..49c5a68d5c0 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/transport/FailureInjectorTransportAdapter.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/transport/FailureInjectorTransportAdapter.scala @@ -113,7 +113,7 @@ private[remote] class FailureInjectorTransportAdapter( Future.successful(this) } - protected def interceptAssociate(remoteAddress: Address, statusPromise: Promise[AssociationHandle]): Unit = { + protected def interceptAssociate(remoteAddress: Address, statusPromise: Promise[AssociationHandle]): Unit = // Association is simulated to be failed if there was either an inbound or outbound message drop if (shouldDropInbound(remoteAddress, (), "interceptAssociate") || shouldDropOutbound( remoteAddress, (), @@ -124,7 +124,6 @@ private[remote] class FailureInjectorTransportAdapter( addressChaosTable.putIfAbsent(handle.remoteAddress.copy(protocol = "", system = ""), PassThru) new FailureInjectorHandle(handle, this) }) - } def notify(ev: AssociationEvent): Unit = ev match { case InboundAssociation(handle) if shouldDropInbound(handle.remoteAddress, ev, "notify") => // Ignore diff --git a/remote/src/main/scala/org/apache/pekko/remote/transport/PekkoPduCodec.scala b/remote/src/main/scala/org/apache/pekko/remote/transport/PekkoPduCodec.scala index d203c6bbb09..37333f2ff15 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/transport/PekkoPduCodec.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/transport/PekkoPduCodec.scala @@ -197,7 +197,7 @@ private[remote] object PekkoPduProtobufCodec extends PekkoPduCodec { override val constructHeartbeat: ByteString = constructControlMessagePdu(WireFormats.CommandType.HEARTBEAT, None) - override def decodePdu(raw: ByteString): PekkoPdu = { + override def decodePdu(raw: ByteString): PekkoPdu = try { val pdu = PekkoProtocolMessage.parseFrom(raw.toArrayUnsafe()) if (pdu.hasPayload) Payload(ByteString.fromByteBuffer(pdu.getPayload.asReadOnlyByteBuffer())) @@ -208,7 +208,6 @@ private[remote] object PekkoPduProtobufCodec extends PekkoPduCodec { } catch { case e: InvalidProtocolBufferException => throw new PduCodecException("Decoding PDU failed.", e) } - } override def decodeMessage( raw: ByteString, @@ -241,8 +240,7 @@ private[remote] object PekkoPduProtobufCodec extends PekkoPduCodec { (ackOption, messageOption) } - private def decodeControlPdu(controlPdu: PekkoControlMessage): PekkoPdu = { - + private def decodeControlPdu(controlPdu: PekkoControlMessage): PekkoPdu = controlPdu.getCommandType match { case CommandType.ASSOCIATE if controlPdu.hasHandshakeInfo => val handshakeInfo = controlPdu.getHandshakeInfo @@ -258,7 +256,6 @@ private[remote] object PekkoPduProtobufCodec extends PekkoPduCodec { case x => throw new PduCodecException(s"Decoding of control PDU failed, invalid format, unexpected: [$x]", null) } - } private def decodeAddress(encodedAddress: AddressData): Address = Address(encodedAddress.getProtocol, encodedAddress.getSystem, encodedAddress.getHostname, encodedAddress.getPort) @@ -279,13 +276,12 @@ private[remote] object PekkoPduProtobufCodec extends PekkoPduCodec { .toByteArray) // Reuse Byte Array (naughty!) } - private def serializeActorRef(defaultAddress: Address, ref: ActorRef): ActorRefData = { + private def serializeActorRef(defaultAddress: Address, ref: ActorRef): ActorRefData = ActorRefData.newBuilder .setPath( if (ref.path.address.host.isDefined) ref.path.toSerializationFormat else ref.path.toSerializationFormatWithAddress(defaultAddress)) .build() - } private def serializeAddress(address: Address): AddressData = address match { case Address(protocol, system, Some(host), Some(port)) => diff --git a/remote/src/main/scala/org/apache/pekko/remote/transport/PekkoProtocolTransport.scala b/remote/src/main/scala/org/apache/pekko/remote/transport/PekkoProtocolTransport.scala index 7568d0b2869..2681cd3a132 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/transport/PekkoProtocolTransport.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/transport/PekkoProtocolTransport.scala @@ -54,9 +54,9 @@ private[remote] class PekkoProtocolSettings(config: Config) { val TransportFailureDetectorConfig: Config = getConfig("pekko.remote.classic.transport-failure-detector") val TransportFailureDetectorImplementationClass: String = TransportFailureDetectorConfig.getString("implementation-class") - val TransportHeartBeatInterval: FiniteDuration = { + val TransportHeartBeatInterval: FiniteDuration = TransportFailureDetectorConfig.getMillisDuration("heartbeat-interval") - }.requiring(_ > Duration.Zero, "transport-failure-detector.heartbeat-interval must be > 0") + .requiring(_ > Duration.Zero, "transport-failure-detector.heartbeat-interval must be > 0") val HandshakeTimeout: FiniteDuration = { val enabledTransports = config.getStringList("pekko.remote.classic.enabled-transports") @@ -370,7 +370,7 @@ private[remote] class ProtocolStateActor( settings: PekkoProtocolSettings, codec: PekkoPduCodec, failureDetector: FailureDetector, - refuseUid: Option[Int]) = { + refuseUid: Option[Int]) = this( OutboundUnassociated(remoteAddress, statusPromise, transport), handshakeInfo, @@ -378,7 +378,6 @@ private[remote] class ProtocolStateActor( settings, codec, failureDetector) - } // Inbound case def this( @@ -387,7 +386,7 @@ private[remote] class ProtocolStateActor( associationListener: AssociationEventListener, settings: PekkoProtocolSettings, codec: PekkoPduCodec, - failureDetector: FailureDetector) = { + failureDetector: FailureDetector) = this( InboundUnassociated(associationListener, wrappedHandle), handshakeInfo, @@ -395,7 +394,6 @@ private[remote] class ProtocolStateActor( settings, codec, failureDetector) - } val localAddress = localHandshakeInfo.origin val handshakeTimerKey = "handshake-timer" @@ -600,15 +598,13 @@ private[remote] class ProtocolStateActor( stay().using(ListenerReady(listener, wrappedHandle)) } - private def initHeartbeatTimer(): Unit = { + private def initHeartbeatTimer(): Unit = startTimerWithFixedDelay("heartbeat-timer", HeartbeatTimer, settings.TransportHeartBeatInterval) - } - private def initHandshakeTimer(): Unit = { + private def initHandshakeTimer(): Unit = startSingleTimer(handshakeTimerKey, HandshakeTimer, settings.HandshakeTimeout) - } - private def handleTimers(wrappedHandle: AssociationHandle): State = { + private def handleTimers(wrappedHandle: AssociationHandle): State = if (failureDetector.isAvailable) { sendHeartbeat(wrappedHandle) stay() @@ -625,7 +621,6 @@ private[remote] class ProtocolStateActor( FSM.Failure(TimeoutReason(s"No response from remote. " + s"Transport failure detector triggered. (internal state was $stateName)"))) } - } private def safeClassName(obj: AnyRef): String = obj match { case null => "null" @@ -664,7 +659,7 @@ private[remote] class ProtocolStateActor( case FSM.Failure(info: DisassociateInfo) => Disassociated(info) case _ => Disassociated(Unknown) } - handlerFuture.foreach { _.notify(disassociateNotification) } + handlerFuture.foreach(_.notify(disassociateNotification)) wrappedHandle.disassociate(disassociationReason(reason), log) case StopEvent(reason, _, ListenerReady(handler, wrappedHandle)) => @@ -700,7 +695,7 @@ private[remote] class ProtocolStateActor( } private def listenForListenerRegistration(readHandlerPromise: Promise[HandleEventListener]): Unit = - readHandlerPromise.future.map { HandleListenerRegistered(_) }.pipeTo(self) + readHandlerPromise.future.map(HandleListenerRegistered(_)).pipeTo(self) private def notifyOutboundHandler( wrappedHandle: AssociationHandle, @@ -766,9 +761,9 @@ private[remote] class ProtocolStateActor( } private def sendAssociate(wrappedHandle: AssociationHandle, info: HandshakeInfo): Boolean = - try { + try wrappedHandle.write(codec.constructAssociate(info)) - } catch { + catch { case NonFatal(e) => throw new PekkoProtocolException("Error writing ASSOCIATE to transport", e) } diff --git a/remote/src/main/scala/org/apache/pekko/remote/transport/TestTransport.scala b/remote/src/main/scala/org/apache/pekko/remote/transport/TestTransport.scala index e6576413f9e..cc12449f1f5 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/transport/TestTransport.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/transport/TestTransport.scala @@ -45,13 +45,12 @@ class TestTransport( import TestTransport._ - def this(system: ExtendedActorSystem, conf: Config) = { + def this(system: ExtendedActorSystem, conf: Config) = this( AddressFromURIString(conf.getString("local-address")), AssociationRegistry.get(conf.getString("registry-key")), conf.getBytes("maximum-payload-bytes").toInt, conf.getString("scheme-identifier")) - } override def isResponsibleFor(address: Address): Boolean = true @@ -62,7 +61,7 @@ class TestTransport( Future.successful((localAddress, associationListenerPromise)) } - private def defaultAssociate(remoteAddress: Address): Future[AssociationHandle] = { + private def defaultAssociate(remoteAddress: Address): Future[AssociationHandle] = registry.transportFor(remoteAddress) match { case Some((remoteTransport, remoteListenerFuture)) => @@ -94,7 +93,6 @@ class TestTransport( case None => Future.failed(new InvalidAssociationException(s"No registered transport: $remoteAddress", null)) } - } private def createHandlePair( remoteTransport: TestTransport, @@ -134,7 +132,7 @@ class TestTransport( override def associate(remoteAddress: Address): Future[AssociationHandle] = associateBehavior(remoteAddress) override def shutdown(): Future[Boolean] = shutdownBehavior(()) - private def defaultWrite(params: (TestAssociationHandle, ByteString)): Future[Boolean] = { + private def defaultWrite(params: (TestAssociationHandle, ByteString)): Future[Boolean] = registry.getRemoteReadHandlerFor(params._1) match { case Some(listener) => listener.notify(InboundPayload(params._2)) @@ -142,7 +140,6 @@ class TestTransport( case None => Future.failed(new IllegalStateException("No association present")) } - } private def defaultDisassociate(handle: TestAssociationHandle): Future[Unit] = { registry.deregisterAssociation(handle.key).foreach { @@ -158,9 +155,8 @@ class TestTransport( * is not recommended. */ val writeBehavior = new SwitchableLoggedBehavior[(TestAssociationHandle, ByteString), Boolean]( - defaultBehavior = { - defaultWrite _ - }, + defaultBehavior = + defaultWrite _, logCallback = { case (handle, payload) => registry.logActivity(WriteAttempt(handle.localAddress, handle.remoteAddress, payload)) @@ -170,9 +166,8 @@ class TestTransport( * The [[pekko.remote.transport.TestTransport.SwitchableLoggedBehavior]] for the disassociate() method on handles. All * handle calls pass through this call. */ - val disassociateBehavior = new SwitchableLoggedBehavior[TestAssociationHandle, Unit](defaultBehavior = { - defaultDisassociate _ - }, + val disassociateBehavior = new SwitchableLoggedBehavior[TestAssociationHandle, Unit](defaultBehavior = + defaultDisassociate _, logCallback = { handle => registry.logActivity(DisassociateAttempt(handle.localAddress, handle.remoteAddress)) }) @@ -224,9 +219,8 @@ object TestTransport { * @param behavior * Function that takes a parameter type A and returns a Future[B]. */ - def push(behavior: Behavior[A, B]): Unit = { + def push(behavior: Behavior[A, B]): Unit = behaviorStack.add(0, behavior) - } /** * Changes the behavior to return a completed future with the given constant value. @@ -267,11 +261,10 @@ object TestTransport { /** * Restores the previous behavior. */ - def pop(): Unit = { + def pop(): Unit = if (behaviorStack.size > 1) { behaviorStack.remove(0) } - } private def currentBehavior = behaviorStack.get(0) @@ -318,20 +311,18 @@ object TestTransport { */ def remoteListenerRelativeTo( handle: TestAssociationHandle, - listenerPair: (HandleEventListener, HandleEventListener)): HandleEventListener = { + listenerPair: (HandleEventListener, HandleEventListener)): HandleEventListener = listenerPair match { case (initiator, receiver) => if (handle.inbound) initiator else receiver } - } /** * Logs a transport activity. * * @param activity Activity to be logged. */ - def logActivity(activity: Activity): Unit = { + def logActivity(activity: Activity): Unit = activityLog.add(activity) - } /** * Takes a thread-safe snapshot of the current state of the activity log. @@ -350,9 +341,8 @@ object TestTransport { /** * Clears the activity log. */ - def clearLog(): Unit = { + def clearLog(): Unit = activityLog.clear() - } /** * Records a mapping between an address and the corresponding (transport, associationEventListener) pair. @@ -364,9 +354,8 @@ object TestTransport { */ def registerTransport( transport: TestTransport, - associationEventListenerFuture: Future[AssociationEventListener]): Unit = { + associationEventListenerFuture: Future[AssociationEventListener]): Unit = transportTable.put(transport.localAddress, (transport, associationEventListenerFuture)) - } /** * Indicates if all given transports were successfully registered. No associations can be established between @@ -377,11 +366,10 @@ object TestTransport { * @return * True if all transports are successfully registered. */ - def transportsReady(addresses: Address*): Boolean = { + def transportsReady(addresses: Address*): Boolean = addresses.forall { transportTable.containsKey(_) } - } /** * Registers a Future of two handle event listeners corresponding to the two endpoints of an association. @@ -392,9 +380,8 @@ object TestTransport { * The future containing the listeners that will be responsible for handling the events of the two endpoints of the * association. Elements in the pair must be in the same order as the addresses in the key parameter. */ - def registerListenerPair(key: (Address, Address), listeners: (HandleEventListener, HandleEventListener)): Unit = { + def registerListenerPair(key: (Address, Address), listeners: (HandleEventListener, HandleEventListener)): Unit = listenersTable.put(key, listeners) - } /** * Removes an association. @@ -414,9 +401,8 @@ object TestTransport { * * @return True if there is an association for the given addresses. */ - def existsAssociation(initiatorAddress: Address, remoteAddress: Address): Boolean = { + def existsAssociation(initiatorAddress: Address, remoteAddress: Address): Boolean = listenersTable.containsKey((initiatorAddress, remoteAddress)) - } /** * Returns the event handler corresponding to the remote endpoint of the given local handle. In other words @@ -425,9 +411,8 @@ object TestTransport { * @param localHandle The handle * @return The option that contains the Future for the listener if exists. */ - def getRemoteReadHandlerFor(localHandle: TestAssociationHandle): Option[HandleEventListener] = { - Option(listenersTable.get(localHandle.key)).map { remoteListenerRelativeTo(localHandle, _) } - } + def getRemoteReadHandlerFor(localHandle: TestAssociationHandle): Option[HandleEventListener] = + Option(listenersTable.get(localHandle.key)).map(remoteListenerRelativeTo(localHandle, _)) /** * Returns the Transport bound to the given address. @@ -466,7 +451,7 @@ object AssociationRegistry { registries.getOrElseUpdate(key, new AssociationRegistry) } - def clear(): Unit = this.synchronized { registries.clear() } + def clear(): Unit = this.synchronized(registries.clear()) } @deprecated("Classic remoting is deprecated, use Artery", "Akka 2.6.0") diff --git a/remote/src/main/scala/org/apache/pekko/remote/transport/ThrottlerTransportAdapter.scala b/remote/src/main/scala/org/apache/pekko/remote/transport/ThrottlerTransportAdapter.scala index e22822e490c..300171bf28a 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/transport/ThrottlerTransportAdapter.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/transport/ThrottlerTransportAdapter.scala @@ -129,7 +129,7 @@ object ThrottlerTransportAdapter { true // Allow messages larger than capacity through, it will be recorded as negative tokens } else min(availableTokens + tokensGenerated(nanoTimeOfSend), capacity) >= tokens - override def tryConsumeTokens(nanoTimeOfSend: Long, tokens: Int): (ThrottleMode, Boolean) = { + override def tryConsumeTokens(nanoTimeOfSend: Long, tokens: Int): (ThrottleMode, Boolean) = if (isAvailable(nanoTimeOfSend, tokens)) ( this.copy( @@ -137,7 +137,6 @@ object ThrottlerTransportAdapter { availableTokens = min(availableTokens - tokens + tokensGenerated(nanoTimeOfSend), capacity)), true) else (this, false) - } override def timeToAvailable(currentNanoTime: Long, tokens: Int): FiniteDuration = { val needed = (if (tokens > capacity) 1 else tokens) - tokensGenerated(currentNanoTime) @@ -304,7 +303,7 @@ private[transport] class ThrottlerManager(wrappedTransport: Transport) val naked = nakedAddress(handle.remoteAddress) val inMode = getInboundMode(naked) wrappedHandle.outboundThrottleMode.set(getOutboundMode(naked)) - wrappedHandle.readHandlerPromise.future.map { ListenerAndMode(_, inMode) }.pipeTo(wrappedHandle.throttlerActor) + wrappedHandle.readHandlerPromise.future.map(ListenerAndMode(_, inMode)).pipeTo(wrappedHandle.throttlerActor) handleTable ::= naked -> wrappedHandle statusPromise.success(wrappedHandle) case SetThrottle(address, direction, mode) => @@ -340,26 +339,23 @@ private[transport] class ThrottlerManager(wrappedTransport: Transport) } - private def getInboundMode(nakedAddress: Address): ThrottleMode = { + private def getInboundMode(nakedAddress: Address): ThrottleMode = throttlingModes.get(nakedAddress) match { case Some((mode, direction)) if direction.includes(Direction.Receive) => mode case _ => Unthrottled } - } - private def getOutboundMode(nakedAddress: Address): ThrottleMode = { + private def getOutboundMode(nakedAddress: Address): ThrottleMode = throttlingModes.get(nakedAddress) match { case Some((mode, direction)) if direction.includes(Direction.Send) => mode case _ => Unthrottled } - } - private def setMode(nakedAddress: Address, handle: ThrottlerHandle): Future[SetThrottleAck.type] = { + private def setMode(nakedAddress: Address, handle: ThrottlerHandle): Future[SetThrottleAck.type] = throttlingModes.get(nakedAddress) match { case Some((mode, direction)) => setMode(handle, mode, direction) case None => setMode(handle, Unthrottled, Direction.Both) } - } private def setMode( handle: ThrottlerHandle, @@ -376,7 +372,7 @@ private[transport] class ThrottlerManager(wrappedTransport: Transport) // silent because of use of isTerminated @nowarn("msg=deprecated") private def askModeWithDeathCompletion(target: ActorRef, mode: ThrottleMode)( - implicit timeout: Timeout): Future[SetThrottleAck.type] = { + implicit timeout: Timeout): Future[SetThrottleAck.type] = if (target.isTerminated) Future.successful(SetThrottleAck) else { val internalTarget = target.asInstanceOf[InternalActorRef] @@ -384,7 +380,8 @@ private[transport] class ThrottlerManager(wrappedTransport: Transport) PromiseActorRef(internalTarget.provider, timeout, target, mode.getClass.getName, internalTarget.path.name) internalTarget.sendSystemMessage(Watch(internalTarget, ref)) target.tell(mode, ref) - ref.result.future.transform({ + ref.result.future.transform( + { case Terminated(t) if t.path == target.path => SetThrottleAck case SetThrottleAck => @@ -394,7 +391,6 @@ private[transport] class ThrottlerManager(wrappedTransport: Transport) throw new IllegalArgumentException() // won't happen, compiler exhaustiveness check pleaser }, t => { internalTarget.sendSystemMessage(Unwatch(target, ref)); t })(ExecutionContexts.parasitic) } - } private def wrapHandle( originalHandle: AssociationHandle, @@ -572,20 +568,19 @@ private[transport] class ThrottledAssociation( } // This method captures ASSOCIATE packets and extracts the origin address - private def peekOrigin(b: ByteString): Option[Address] = { - try { + private def peekOrigin(b: ByteString): Option[Address] = + try PekkoPduProtobufCodec.decodePdu(b) match { case Associate(info) => Some(info.origin) case _ => None } - } catch { + catch { // This layer should not care about malformed packets. Also, this also useful for testing, because // arbitrary payload could be passed in case NonFatal(_) => None } - } - def forwardOrDelay(payload: ByteString): Unit = { + def forwardOrDelay(payload: ByteString): Unit = if (inboundThrottleMode == Blackhole) { // Do nothing } else { @@ -603,7 +598,6 @@ private[transport] class ThrottledAssociation( throttledMessages = throttledMessages :+ payload } } - } def scheduleDequeue(delay: FiniteDuration): Unit = inboundThrottleMode match { case Blackhole => // Do nothing @@ -648,8 +642,7 @@ private[transport] final case class ThrottlerHandle(_wrappedHandle: AssociationH override def disassociate(): Unit = throttlerActor ! PoisonPill - def disassociateWithFailure(reason: DisassociateInfo): Unit = { + def disassociateWithFailure(reason: DisassociateInfo): Unit = throttlerActor ! ThrottledAssociation.FailWith(reason) - } } diff --git a/remote/src/main/scala/org/apache/pekko/remote/transport/Transport.scala b/remote/src/main/scala/org/apache/pekko/remote/transport/Transport.scala index 38a88d79642..4461512bfd4 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/transport/Transport.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/transport/Transport.scala @@ -159,7 +159,7 @@ trait Transport { * @param cmd Command message to the transport * @return Future that succeeds when the command was handled or dropped */ - def managementCommand(@unused cmd: Any): Future[Boolean] = { Future.successful(false) } + def managementCommand(@unused cmd: Any): Future[Boolean] = Future.successful(false) } diff --git a/remote/src/main/scala/org/apache/pekko/remote/transport/netty/NettyHelpers.scala b/remote/src/main/scala/org/apache/pekko/remote/transport/netty/NettyHelpers.scala index 3b17a577303..86736f8da5f 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/transport/netty/NettyHelpers.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/transport/netty/NettyHelpers.scala @@ -55,23 +55,20 @@ private[netty] trait NettyHelpers { */ private[netty] abstract class NettyChannelHandlerAdapter extends SimpleChannelInboundHandler[ByteBuf] with NettyHelpers { - final override def channelRead0(ctx: ChannelHandlerContext, msg: ByteBuf): Unit = { + final override def channelRead0(ctx: ChannelHandlerContext, msg: ByteBuf): Unit = onMessage(ctx, msg) - } @nowarn("msg=deprecated") - final override def exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable): Unit = { + final override def exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable): Unit = transformException(ctx, cause) - } final override def channelActive(ctx: ChannelHandlerContext): Unit = { onOpen(ctx) onConnect(ctx) } - final override def channelInactive(ctx: ChannelHandlerContext): Unit = { + final override def channelInactive(ctx: ChannelHandlerContext): Unit = onDisconnect(ctx) - } } /** diff --git a/remote/src/main/scala/org/apache/pekko/remote/transport/netty/NettySSLSupport.scala b/remote/src/main/scala/org/apache/pekko/remote/transport/netty/NettySSLSupport.scala index 1d93406b5bd..e4ea04c27bb 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/transport/netty/NettySSLSupport.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/transport/netty/NettySSLSupport.scala @@ -68,11 +68,11 @@ private[pekko] object NettySSLSupport { if (isClient) sslEngineProvider.createClientSSLEngine() else sslEngineProvider.createServerSSLEngine() val handler = new SslHandler(sslEngine) - handler.handshakeFuture().addListener((future: Future[Channel]) => { + handler.handshakeFuture().addListener { (future: Future[Channel]) => if (!future.isSuccess) { handler.closeOutbound().channel().close() } - }) + } handler } } diff --git a/remote/src/main/scala/org/apache/pekko/remote/transport/netty/NettyTransport.scala b/remote/src/main/scala/org/apache/pekko/remote/transport/netty/NettyTransport.scala index 0956548fdfe..49ee46451ef 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/transport/netty/NettyTransport.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/transport/netty/NettyTransport.scala @@ -200,9 +200,8 @@ class NettyTransportSettings(config: Config) { private[netty] trait CommonHandlers extends NettyHelpers { protected val transport: NettyTransport - override protected def onOpen(ctx: ChannelHandlerContext): Unit = { + override protected def onOpen(ctx: ChannelHandlerContext): Unit = transport.channelGroup.add(ctx.channel()) - } protected def createHandle(channel: Channel, localAddress: Address, remoteAddress: Address): AssociationHandle @@ -277,9 +276,8 @@ private[netty] abstract class ClientHandler(protected final val transport: Netty final protected val statusPromise = Promise[AssociationHandle]() def statusFuture: Future[AssociationHandle] = statusPromise.future - final protected def initOutbound(channel: Channel, remoteSocketAddress: SocketAddress): Unit = { + final protected def initOutbound(channel: Channel, remoteSocketAddress: SocketAddress): Unit = init(channel, remoteSocketAddress, remoteAddress)(statusPromise.success) - } } @@ -293,8 +291,8 @@ private[transport] object NettyTransport { @nowarn("msg=deprecated") def always(c: ChannelFuture): Future[Channel] = NettyFutureBridge(c).recover { case _ => c.channel() } for { - _ <- always { channel.writeAndFlush(Unpooled.EMPTY_BUFFER) } // Force flush by waiting on a final dummy write - _ <- always { channel.disconnect() } + _ <- always(channel.writeAndFlush(Unpooled.EMPTY_BUFFER)) // Force flush by waiting on a final dummy write + _ <- always(channel.disconnect()) } channel.close() } @@ -400,7 +398,7 @@ class NettyTransport(val settings: NettyTransportSettings, val system: ExtendedA .get) } else OptionVal.None - private def sslHandler(isClient: Boolean): SslHandler = { + private def sslHandler(isClient: Boolean): SslHandler = sslEngineProvider match { case OptionVal.Some(sslProvider) => NettySSLSupport(sslProvider, isClient) @@ -408,8 +406,6 @@ class NettyTransport(val settings: NettyTransportSettings, val system: ExtendedA throw new IllegalStateException("Expected enable-ssl=on") } - } - private val serverPipelineInitializer: ChannelInitializer[SocketChannel] = (ch: SocketChannel) => { val pipeline = newPipeline(ch) if (EnableSsl) pipeline.addFirst("SslHandler", sslHandler(isClient = false)) @@ -529,9 +525,9 @@ class NettyTransport(val settings: NettyTransportSettings, val system: ExtendedA } catch { case NonFatal(e) => log.error("failed to bind to host:{} port:{}, shutting down Netty transport", settings.BindHostname, bindPort) - try { + try shutdown() - } catch { + catch { case NonFatal(_) => } // ignore possible exception during shutdown throw e; @@ -547,7 +543,7 @@ class NettyTransport(val settings: NettyTransportSettings, val system: ExtendedA case _ => throw new IllegalArgumentException(s"Address [$addr] must contain both host and port information.") } - override def associate(remoteAddress: Address): Future[AssociationHandle] = { + override def associate(remoteAddress: Address): Future[AssociationHandle] = if (!serverChannel.isActive) Future.failed(new NettyTransportException("Transport is not bound")) else { val bootstrap: ClientBootstrap = outboundBootstrap(remoteAddress) @@ -572,7 +568,6 @@ class NettyTransport(val settings: NettyTransportSettings, val system: ExtendedA throw new NettyTransportExceptionNoStack(s"${t.getClass.getName}: $msg", t.getCause) } } - } override def shutdown(): Future[Boolean] = { def always(c: ChannelGroupFuture): Future[Boolean] = NettyFutureBridge(c).map(_ => true).recover { case _ => false } diff --git a/remote/src/main/scala/org/apache/pekko/remote/transport/netty/SSLEngineProvider.scala b/remote/src/main/scala/org/apache/pekko/remote/transport/netty/SSLEngineProvider.scala index ecab23e25ae..de00f975b1d 100644 --- a/remote/src/main/scala/org/apache/pekko/remote/transport/netty/SSLEngineProvider.scala +++ b/remote/src/main/scala/org/apache/pekko/remote/transport/netty/SSLEngineProvider.scala @@ -62,7 +62,7 @@ class ConfigSSLEngineProvider(protected val log: MarkerLoggingAdapter, private v import settings._ - private lazy val sslContext: SSLContext = { + private lazy val sslContext: SSLContext = try { val rng = createSecureRandom() val ctx = SSLContext.getInstance(SSLProtocol) @@ -80,7 +80,6 @@ class ConfigSSLEngineProvider(protected val log: MarkerLoggingAdapter, private v "Server SSL connection could not be established because SSL context could not be constructed", e) } - } /** * Subclass may override to customize loading of `KeyStore` @@ -120,9 +119,8 @@ class ConfigSSLEngineProvider(protected val log: MarkerLoggingAdapter, private v override def createClientSSLEngine(): SSLEngine = createSSLEngine(pekko.stream.Client) - private def createSSLEngine(role: TLSRole): SSLEngine = { + private def createSSLEngine(role: TLSRole): SSLEngine = createSSLEngine(sslContext, role) - } private def createSSLEngine(sslContext: SSLContext, role: TLSRole): SSLEngine = { diff --git a/remote/src/test/scala-jdk9-only/org/apache/pekko/remote/artery/jfr/JFRRemotingFlightRecorderSpec.scala b/remote/src/test/scala-jdk9-only/org/apache/pekko/remote/artery/jfr/JFRRemotingFlightRecorderSpec.scala index e64e7c885c3..d4304148533 100644 --- a/remote/src/test/scala-jdk9-only/org/apache/pekko/remote/artery/jfr/JFRRemotingFlightRecorderSpec.scala +++ b/remote/src/test/scala-jdk9-only/org/apache/pekko/remote/artery/jfr/JFRRemotingFlightRecorderSpec.scala @@ -43,9 +43,8 @@ class JFRRemotingFlightRecorderSpec extends PekkoSpec { try { val extension = RemotingFlightRecorder(system) extension should ===(NoOpRemotingFlightRecorder) - } finally { + } finally TestKit.shutdownActorSystem(system) - } } } diff --git a/remote/src/test/scala/org/apache/pekko/remote/AccrualFailureDetectorSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/AccrualFailureDetectorSpec.scala index f0a8e66267e..fa0cc41f55c 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/AccrualFailureDetectorSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/AccrualFailureDetectorSpec.scala @@ -63,9 +63,8 @@ class AccrualFailureDetectorSpec extends PekkoSpec("pekko.loglevel = INFO") { cdf(fd.phi(35L, 0, 10)) should ===(0.99977 +- 0.001) cdf(fd.phi(40L, 0, 10)) should ===(0.99997 +- 0.0001) - for (case x :: y :: Nil <- (0 to 40).toList.sliding(2)) { + for (case x :: y :: Nil <- (0 to 40).toList.sliding(2)) fd.phi(x, 0, 10) should be < fd.phi(y, 0, 10) - } cdf(fd.phi(22, 20.0, 3)) should ===(0.7475 +- 0.001) } @@ -79,9 +78,8 @@ class AccrualFailureDetectorSpec extends PekkoSpec("pekko.loglevel = INFO") { "return realistic phi values" in { val fd = createFailureDetector() val test = TreeMap(0 -> 0.0, 500 -> 0.1, 1000 -> 0.3, 1200 -> 1.6, 1400 -> 4.7, 1600 -> 10.8, 1700 -> 15.3) - for ((timeDiff, expectedPhi) <- test) { + for ((timeDiff, expectedPhi) <- test) fd.phi(timeDiff = timeDiff, mean = 1000.0, stdDeviation = 100.0) should ===(expectedPhi +- 0.1) - } // larger stdDeviation results => lower phi fd.phi(timeDiff = 1100, mean = 1000.0, stdDeviation = 500.0) should be < (fd diff --git a/remote/src/test/scala/org/apache/pekko/remote/AckedDeliverySpec.scala b/remote/src/test/scala/org/apache/pekko/remote/AckedDeliverySpec.scala index 60494a661b9..712a22b6aa9 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/AckedDeliverySpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/AckedDeliverySpec.scala @@ -315,12 +315,11 @@ class AckedDeliverySpec extends PekkoSpec { } } - def receiverStep(p: Double) = { + def receiverStep(p: Double) = if (happened(p)) { sndBuf = sndBuf.acknowledge(lastAck) dbgLog(s"$sndBuf <-- $lastAck -- $rcvBuf") } else dbgLog(s"$sndBuf X-- $lastAck -- $rcvBuf") - } // Dropping phase info(s"Starting unreliable delivery for $MsgCount messages, with delivery probability P = $DeliveryProbability") diff --git a/remote/src/test/scala/org/apache/pekko/remote/DaemonicSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/DaemonicSpec.scala index e69877cffa4..2769c713385 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/DaemonicSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/DaemonicSpec.scala @@ -59,9 +59,8 @@ class DaemonicSpec extends PekkoSpec { newNonDaemons should ===(Set.empty[Thread]) }, 4.seconds) - } finally { + } finally shutdown(daemonicSystem) - } } } } diff --git a/remote/src/test/scala/org/apache/pekko/remote/FailureDetectorRegistrySpec.scala b/remote/src/test/scala/org/apache/pekko/remote/FailureDetectorRegistrySpec.scala index c6851491ca8..20a07db6a97 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/FailureDetectorRegistrySpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/FailureDetectorRegistrySpec.scala @@ -51,7 +51,7 @@ class FailureDetectorRegistrySpec extends PekkoSpec("pekko.loglevel = INFO") { minStdDeviation: FiniteDuration = 10.millis, acceptableLostDuration: FiniteDuration = Duration.Zero, firstHeartbeatEstimate: FiniteDuration = 1.second, - clock: Clock = FailureDetector.defaultClock): FailureDetectorRegistry[String] = { + clock: Clock = FailureDetector.defaultClock): FailureDetectorRegistry[String] = new DefaultFailureDetectorRegistry[String](() => createFailureDetector( threshold, @@ -60,7 +60,6 @@ class FailureDetectorRegistrySpec extends PekkoSpec("pekko.loglevel = INFO") { acceptableLostDuration, firstHeartbeatEstimate, clock)) - } "mark node as available after a series of successful heartbeats" in { val timeInterval = List[Long](0, 1000, 100, 100) diff --git a/remote/src/test/scala/org/apache/pekko/remote/MessageLoggingSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/MessageLoggingSpec.scala index 462d7aebc19..ac4b98b67ca 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/MessageLoggingSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/MessageLoggingSpec.scala @@ -103,7 +103,6 @@ abstract class MessageLoggingSpec(config: Config) extends PekkoSpec(config) with } } - override protected def afterTermination(): Unit = { + override protected def afterTermination(): Unit = TestKit.shutdownActorSystem(remoteSystem) - } } diff --git a/remote/src/test/scala/org/apache/pekko/remote/NetworkFailureSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/NetworkFailureSpec.scala index daff38b8379..6ad63d048a5 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/NetworkFailureSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/NetworkFailureSpec.scala @@ -30,7 +30,7 @@ trait NetworkFailureSpec extends DefaultTimeout { self: PekkoSpec => val DelayMillis = "350ms" val PortRange = "1024-65535" - def replyWithTcpResetFor(duration: Duration, dead: AtomicBoolean) = { + def replyWithTcpResetFor(duration: Duration, dead: AtomicBoolean) = Future { try { enableTcpReset() @@ -43,9 +43,8 @@ trait NetworkFailureSpec extends DefaultTimeout { self: PekkoSpec => e.printStackTrace } } - } - def throttleNetworkFor(duration: Duration, dead: AtomicBoolean) = { + def throttleNetworkFor(duration: Duration, dead: AtomicBoolean) = Future { try { enableNetworkThrottling() @@ -58,9 +57,8 @@ trait NetworkFailureSpec extends DefaultTimeout { self: PekkoSpec => e.printStackTrace } } - } - def dropNetworkFor(duration: Duration, dead: AtomicBoolean) = { + def dropNetworkFor(duration: Duration, dead: AtomicBoolean) = Future { try { enableNetworkDrop() @@ -73,7 +71,6 @@ trait NetworkFailureSpec extends DefaultTimeout { self: PekkoSpec => e.printStackTrace } } - } def sleepFor(duration: Duration) = { println("===>>> Sleeping for [" + duration + "]") diff --git a/remote/src/test/scala/org/apache/pekko/remote/RemoteFeaturesSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/RemoteFeaturesSpec.scala index 78a50a3ecaf..7b84894afe1 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/RemoteFeaturesSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/RemoteFeaturesSpec.scala @@ -68,12 +68,11 @@ abstract class RemoteFeaturesSpec(c: Config) extends ArteryMultiNodeSpec(c) with protected val remoteSystem1 = newRemoteSystem(name = Some("RS1"), extraConfig = Some(common(useUnsafe))) @nowarn("msg=deprecated") - private def mute(): Unit = { + private def mute(): Unit = Seq(system, remoteSystem1).foreach( muteDeadLetters( pekko.remote.transport.AssociationHandle.Disassociated.getClass, pekko.remote.transport.ActorTransportAdapter.DisassociateUnderlying.getClass)(_)) - } mute() import pekko.remote.artery.RemoteWatcherSpec.TestRemoteWatcher diff --git a/remote/src/test/scala/org/apache/pekko/remote/RemoteRouterSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/RemoteRouterSpec.scala index a5e457e1d6b..3620f9b56fe 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/RemoteRouterSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/RemoteRouterSpec.scala @@ -103,18 +103,16 @@ class RemoteRouterSpec extends PekkoSpec(s""" }""").withFallback(system.settings.config) val masterSystem = ActorSystem(masterSystemName, conf) - override def afterTermination(): Unit = { + override def afterTermination(): Unit = shutdown(masterSystem) - } - def collectRouteePaths(probe: TestProbe, router: ActorRef, n: Int): immutable.Seq[ActorPath] = { + def collectRouteePaths(probe: TestProbe, router: ActorRef, n: Int): immutable.Seq[ActorPath] = for (i <- 1 to n) yield { val msg = i.toString router.tell(msg, probe.ref) probe.expectMsg(msg) probe.lastSender.path } - } "A Remote Router" must { diff --git a/remote/src/test/scala/org/apache/pekko/remote/Ticket1978CommunicationSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/Ticket1978CommunicationSpec.scala index 8e045fd6bfd..51ddace201d 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/Ticket1978CommunicationSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/Ticket1978CommunicationSpec.scala @@ -148,11 +148,10 @@ abstract class Ticket1978CommunicationSpec(val cipherConfig: CipherConfig) .parseString("pekko.remote.classic.netty.ssl.port = " + cipherConfig.remotePort) .withFallback(system.settings.config)) - override def afterTermination(): Unit = { + override def afterTermination(): Unit = if (cipherConfig.runTest) { shutdown(other) } - } def preCondition: Boolean = true diff --git a/remote/src/test/scala/org/apache/pekko/remote/TransientSerializationErrorSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/TransientSerializationErrorSpec.scala index 001906e21f7..fa34d676942 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/TransientSerializationErrorSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/TransientSerializationErrorSpec.scala @@ -47,13 +47,12 @@ object TransientSerializationErrorSpec { case ToBinaryIllegal => throw new IllegalArgumentException() case _ => Array.emptyByteArray } - def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = { + def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = manifest match { case "ND" => throw new NotSerializableException() // Not sure this applies here case "IOD" => throw new IllegalArgumentException() case _ => throw new NotSerializableException() } - } } } @@ -118,9 +117,8 @@ abstract class AbstractTransientSerializationErrorSpec(config: Config) } } - override def afterTermination(): Unit = { + override def afterTermination(): Unit = TestKit.shutdownActorSystem(system2) - } } class TransientSerializationErrorSpec diff --git a/remote/src/test/scala/org/apache/pekko/remote/TypedActorRemoteDeploySpec.scala b/remote/src/test/scala/org/apache/pekko/remote/TypedActorRemoteDeploySpec.scala index 6a27d632dce..ce047939e17 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/TypedActorRemoteDeploySpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/TypedActorRemoteDeploySpec.scala @@ -68,17 +68,16 @@ class TypedActorRemoteDeploySpec extends PekkoSpec(conf) { "Typed actors" must { "be possible to deploy remotely and communicate with" in { - verify({ _.getName }, remoteName) + verify(_.getName, remoteName) } "be possible to deploy remotely and be able to dereference self" in { - verify({ _.getNameSelfDeref }, remoteName) + verify(_.getNameSelfDeref, remoteName) } } - override def afterTermination(): Unit = { + override def afterTermination(): Unit = shutdown(remoteSystem) - } } diff --git a/remote/src/test/scala/org/apache/pekko/remote/artery/ArteryMultiNodeSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/artery/ArteryMultiNodeSpec.scala index 1a732a80e69..ded21c31419 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/artery/ArteryMultiNodeSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/artery/ArteryMultiNodeSpec.scala @@ -49,14 +49,13 @@ abstract class ArteryMultiNodeSpec(config: Config) private var remoteSystems: Vector[ActorSystem] = Vector.empty - override protected def withFixture(test: NoArgTest): Outcome = { + override protected def withFixture(test: NoArgTest): Outcome = // note that withFixture is also used in FlightRecorderSpecIntegration if (!RARP(system).provider.remoteSettings.Artery.Enabled) { info(s"${getClass.getName} is only enabled for Artery") Pending } else super.withFixture(test) - } /** * @return A new actor system configured with artery enabled. The system will @@ -99,7 +98,6 @@ object ArteryMultiNodeSpec { arterySettings.Transport == ArterySettings.AeronUpd } - def freePort(systemConfig: Config): Int = { + def freePort(systemConfig: Config): Int = SocketUtil.temporaryLocalPort(ArteryMultiNodeSpec.arteryUdpEnabled(systemConfig)) - } } diff --git a/remote/src/test/scala/org/apache/pekko/remote/artery/DuplicateFlushSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/artery/DuplicateFlushSpec.scala index d48f56d113e..6b0071ed703 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/artery/DuplicateFlushSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/artery/DuplicateFlushSpec.scala @@ -38,7 +38,7 @@ class DuplicateFlushSpec extends PekkoSpec(""" private val addressA = UniqueAddress(Address("pekko", "sysA", "hostA", 1001), 1) private val addressB = UniqueAddress(Address("pekko", "sysB", "hostB", 1002), 2) - private def setupStream(inboundContext: InboundContext): (TestPublisher.Probe[AnyRef], TestSubscriber.Probe[Any]) = { + private def setupStream(inboundContext: InboundContext): (TestPublisher.Probe[AnyRef], TestSubscriber.Probe[Any]) = TestSource .probe[AnyRef] .map { msg => @@ -69,7 +69,6 @@ class DuplicateFlushSpec extends PekkoSpec(""" .map(env => env.message -> env.lane) .toMat(TestSink.probe[Any])(Keep.both) .run() - } "DuplicateFlush stage" must { diff --git a/remote/src/test/scala/org/apache/pekko/remote/artery/DuplicateHandshakeSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/artery/DuplicateHandshakeSpec.scala index 1a0d0e6677a..520285ee82b 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/artery/DuplicateHandshakeSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/artery/DuplicateHandshakeSpec.scala @@ -39,7 +39,7 @@ class DuplicateHandshakeSpec extends PekkoSpec(""" val addressA = UniqueAddress(Address("pekko", "sysA", "hostA", 1001), 1) val addressB = UniqueAddress(Address("pekko", "sysB", "hostB", 1002), 2) - private def setupStream(inboundContext: InboundContext): (TestPublisher.Probe[AnyRef], TestSubscriber.Probe[Any]) = { + private def setupStream(inboundContext: InboundContext): (TestPublisher.Probe[AnyRef], TestSubscriber.Probe[Any]) = TestSource .probe[AnyRef] .map { msg => @@ -70,7 +70,6 @@ class DuplicateHandshakeSpec extends PekkoSpec(""" .map { case env: InboundEnvelope => env.message -> env.lane } .toMat(TestSink.probe[Any])(Keep.both) .run() - } "DuplicateHandshake stage" must { diff --git a/remote/src/test/scala/org/apache/pekko/remote/artery/InboundControlJunctionSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/artery/InboundControlJunctionSpec.scala index cd1cef18923..91bb504c816 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/artery/InboundControlJunctionSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/artery/InboundControlJunctionSpec.scala @@ -64,9 +64,8 @@ class InboundControlJunctionSpec .run() controlSubject.attach(new ControlMessageObserver { - override def notify(env: InboundEnvelope) = { + override def notify(env: InboundEnvelope) = observerProbe.ref ! env.message - } override def controlSubjectCompleted(signal: Try[Done]): Unit = () }) diff --git a/remote/src/test/scala/org/apache/pekko/remote/artery/LargeMessagesStreamSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/artery/LargeMessagesStreamSpec.scala index 1c4e9c7c8b5..1adcc72e0b1 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/artery/LargeMessagesStreamSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/artery/LargeMessagesStreamSpec.scala @@ -151,9 +151,8 @@ class LargeMessagesStreamSpec } } - def awaitResolve(selection: ActorSelection): ActorRef = { + def awaitResolve(selection: ActorSelection): ActorRef = awaitAssert { Await.result(selection.resolveOne(1.second), 1.seconds) } - } } diff --git a/remote/src/test/scala/org/apache/pekko/remote/artery/OutboundHandshakeSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/artery/OutboundHandshakeSpec.scala index 4a1a39a1e71..3c8893c460c 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/artery/OutboundHandshakeSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/artery/OutboundHandshakeSpec.scala @@ -43,9 +43,7 @@ class OutboundHandshakeSpec extends PekkoSpec(""" timeout: FiniteDuration = 5.seconds, retryInterval: FiniteDuration = 10.seconds, injectHandshakeInterval: FiniteDuration = 10.seconds, - livenessProbeInterval: Duration = Duration.Undefined) - : (TestPublisher.Probe[String], TestSubscriber.Probe[Any]) = { - + livenessProbeInterval: Duration = Duration.Undefined): (TestPublisher.Probe[String], TestSubscriber.Probe[Any]) = TestSource .probe[String] .map(msg => outboundEnvelopePool.acquire().init(OptionVal.None, msg, OptionVal.None)) @@ -61,7 +59,6 @@ class OutboundHandshakeSpec extends PekkoSpec(""" .map(env => env.message) .toMat(TestSink.probe[Any])(Keep.both) .run() - } "OutboundHandshake stage" must { "send HandshakeReq when first pulled" in { diff --git a/remote/src/test/scala/org/apache/pekko/remote/artery/OutboundIdleShutdownSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/artery/OutboundIdleShutdownSpec.scala index 39beddb4a23..b8ce401dbb0 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/artery/OutboundIdleShutdownSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/artery/OutboundIdleShutdownSpec.scala @@ -49,7 +49,7 @@ class OutboundIdleShutdownSpec extends ArteryMultiNodeSpec(s""" private def isArteryTcp: Boolean = RARP(system).provider.transport.asInstanceOf[ArteryTransport].settings.Transport == ArterySettings.Tcp - private def assertStreamActive(association: Association, queueIndex: Int, expected: Boolean): Unit = { + private def assertStreamActive(association: Association, queueIndex: Int, expected: Boolean): Unit = if (queueIndex == Association.ControlQueueIndex) { // the control stream is not stopped, but for TCP the connection is closed if (expected) @@ -61,8 +61,6 @@ class OutboundIdleShutdownSpec extends ArteryMultiNodeSpec(s""" association.isStreamActive(queueIndex) shouldBe expected } - } - private def futureUniqueRemoteAddress(association: Association): Future[UniqueAddress] = { val p = Promise[UniqueAddress]() association.associationState.addUniqueRemoteAddressListener(a => p.success(a)) @@ -186,9 +184,8 @@ class OutboundIdleShutdownSpec extends ArteryMultiNodeSpec(s""" eventually { localArtery.inboundCompressionAccess.get.currentCompressionOriginUids.futureValue should not contain remoteUid } - } finally { + } finally shutdown(remoteSystem2) - } } /** @@ -215,9 +212,8 @@ class OutboundIdleShutdownSpec extends ArteryMultiNodeSpec(s""" test(remoteSystem, remoteAddress, echoRef, artery, localProbe) - } finally { + } finally shutdown(remoteSystem) - } } } } diff --git a/remote/src/test/scala/org/apache/pekko/remote/artery/RemoteConnectionSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/artery/RemoteConnectionSpec.scala index 997bb106caf..a57913868dd 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/artery/RemoteConnectionSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/artery/RemoteConnectionSpec.scala @@ -21,13 +21,12 @@ import pekko.testkit.{ EventFilter, ImplicitSender, TestActors, TestEvent, TestP class RemoteConnectionSpec extends ArteryMultiNodeSpec("pekko.remote.retry-gate-closed-for = 5s") with ImplicitSender { - def muteSystem(system: ActorSystem): Unit = { + def muteSystem(system: ActorSystem): Unit = system.eventStream.publish( TestEvent.Mute( EventFilter.error(start = "AssociationError"), EventFilter.warning(start = "AssociationError"), EventFilter.warning(pattern = "received dead letter.*"))) - } "Remoting between systems" should { diff --git a/remote/src/test/scala/org/apache/pekko/remote/artery/RemoteDeploymentSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/artery/RemoteDeploymentSpec.scala index 13c5fd9a7e6..a89a6f8cc40 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/artery/RemoteDeploymentSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/artery/RemoteDeploymentSpec.scala @@ -36,13 +36,11 @@ object RemoteDeploymentSpec { } override def preStart(): Unit = {} - override def preRestart(cause: Throwable, msg: Option[Any]): Unit = { + override def preRestart(cause: Throwable, msg: Option[Any]): Unit = target ! "preRestart" - } override def postRestart(cause: Throwable): Unit = {} - override def postStop(): Unit = { + override def postStop(): Unit = target ! "postStop" - } } def parentProps(probe: ActorRef): Props = @@ -163,9 +161,8 @@ class RemoteDeploymentSpec val probes = Vector.fill(numParents, numChildren)(TestProbe()(masterSystem)) val childProps = Props[Echo1]() - for (p <- 0 until numParents; c <- 0 until numChildren) { + for (p <- 0 until numParents; c <- 0 until numChildren) parents(p).tell((childProps, numMessages), probes(p)(c).ref) - } for (p <- 0 until numParents; c <- 0 until numChildren) { val probe = probes(p)(c) diff --git a/remote/src/test/scala/org/apache/pekko/remote/artery/RemoteInstrumentsSerializationSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/artery/RemoteInstrumentsSerializationSpec.scala index fb76ecb83f8..e8b5253b4ae 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/artery/RemoteInstrumentsSerializationSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/artery/RemoteInstrumentsSerializationSpec.scala @@ -33,14 +33,13 @@ class RemoteInstrumentsSerializationSpec extends PekkoSpec("pekko.loglevel = DEB new RemoteInstruments(system.asInstanceOf[ExtendedActorSystem], system.log, vec) } - def ensureDebugLog[T](messages: String*)(f: => T): T = { + def ensureDebugLog[T](messages: String*)(f: => T): T = if (messages.isEmpty) f else EventFilter.debug(message = messages.head, occurrences = 1).intercept { ensureDebugLog(messages.tail: _*)(f) } - } "RemoteInstruments" should { "not write anything in the buffer if not deserializing" in { @@ -151,7 +150,7 @@ object RemoteInstrumentsSerializationSpec { id: Int, metadata: String, sentThrowable: Throwable = null, - receiveThrowable: Throwable = null): RemoteInstrument = { + receiveThrowable: Throwable = null): RemoteInstrument = new RemoteInstrument { private val charset = StandardCharsets.UTF_8 private val encoder = charset.newEncoder() @@ -200,7 +199,6 @@ object RemoteInstrumentsSerializationSpec { size: Int, time: Long): Unit = () } - } def serialize(ri: RemoteInstruments, buffer: ByteBuffer): Unit = { val mockOutbound = new ReusableOutboundEnvelope() diff --git a/remote/src/test/scala/org/apache/pekko/remote/artery/RemoteRouterSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/artery/RemoteRouterSpec.scala index f1fd7986a1e..e877c8142ad 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/artery/RemoteRouterSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/artery/RemoteRouterSpec.scala @@ -93,18 +93,16 @@ class RemoteRouterSpec val masterSystem = ActorSystem("Master" + sysName, conf) - override def afterTermination(): Unit = { + override def afterTermination(): Unit = shutdown(masterSystem) - } - def collectRouteePaths(probe: TestProbe, router: ActorRef, n: Int): immutable.Seq[ActorPath] = { + def collectRouteePaths(probe: TestProbe, router: ActorRef, n: Int): immutable.Seq[ActorPath] = for (i <- 1 to n) yield { val msg = i.toString router.tell(msg, probe.ref) probe.expectMsg(msg) probe.lastSender.path } - } "A Remote Router" must { diff --git a/remote/src/test/scala/org/apache/pekko/remote/artery/RemoteWatcherSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/artery/RemoteWatcherSpec.scala index 8f57457a0d9..d475d0e38d8 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/artery/RemoteWatcherSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/artery/RemoteWatcherSpec.scala @@ -69,10 +69,9 @@ object RemoteWatcherSpec { // that doesn't interfere with the real watch that is going on in the background context.system.eventStream.publish(TestRemoteWatcher.AddressTerm(address)) - override def quarantine(address: Address, uid: Option[Long], reason: String, harmless: Boolean): Unit = { + override def quarantine(address: Address, uid: Option[Long], reason: String, harmless: Boolean): Unit = // don't quarantine in remoting, but publish a testable message context.system.eventStream.publish(TestRemoteWatcher.Quarantined(address, uid)) - } } diff --git a/remote/src/test/scala/org/apache/pekko/remote/artery/RollingEventLogSimulationSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/artery/RollingEventLogSimulationSpec.scala index 1913d090330..0ea2fe20338 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/artery/RollingEventLogSimulationSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/artery/RollingEventLogSimulationSpec.scala @@ -59,7 +59,7 @@ class RollingEventLogSimulationSpec extends PekkoSpec { // CAS on the commit status field, if fails jump to start of loop case object TryMarkDirty extends Instruction { - override def apply(simulator: Simulator): String = { + override def apply(simulator: Simulator): String = if (simulator.simulatedBuffer(slot) == Dirty) { instructionPtr = 0 // Retry loop s"$letterCode sees dirty record at $seenHeader, retries" @@ -68,7 +68,6 @@ class RollingEventLogSimulationSpec extends PekkoSpec { advance() s"$letterCode sees committed record at $seenHeader, proceeds" } - } } // This step is just to be able to do consistency checks. Simply writes the ID of the writer as the first @@ -114,9 +113,8 @@ class RollingEventLogSimulationSpec extends PekkoSpec { Array.fill(EntrySize - 2)(WriteByte) :+ Commit - def step(simulator: Simulator): String = { + def step(simulator: Simulator): String = instructions(instructionPtr)(simulator) - } private def advance(): Unit = { instructionPtr += 1 @@ -145,7 +143,7 @@ class RollingEventLogSimulationSpec extends PekkoSpec { } def run(): Unit = { - try { + try while (activeWriters > 0) { val writer = chooseWriter val event = writer.step(this) @@ -153,7 +151,7 @@ class RollingEventLogSimulationSpec extends PekkoSpec { if (writer.isFinished) activeWriters -= 1 consistencyChecks() } - } catch { + catch { case NonFatal(e) => println(log.reverse.mkString("\n")) println("----------- BUFFER CONTENT -------------") @@ -169,13 +167,12 @@ class RollingEventLogSimulationSpec extends PekkoSpec { } // No Committed records should contain bytes from two different writes (Dirty records might, though). - def checkNoPartialWrites(): Unit = { + def checkNoPartialWrites(): Unit = for (entry <- 0 until entryCount if simulatedBuffer(entry * EntrySize) == Committed) { val ofs = entry * EntrySize if (simulatedBuffer(ofs + 2) != simulatedBuffer(ofs + 3)) fail(s"Entry $entry is corrupted, partial writes are visible") } - } // All writes for a given ID must: // - contain the last write, or no writes at all @@ -188,7 +185,7 @@ class RollingEventLogSimulationSpec extends PekkoSpec { // bad examples // [2, 3] // [2, 4] - def checkGaplessWrites(): Unit = { + def checkGaplessWrites(): Unit = for (id <- 0 until writerCount) { val writeCount = writers(id).writeCount val lastWrittenSlot = (headPointer - EntrySize) % EntrySize @@ -205,14 +202,11 @@ class RollingEventLogSimulationSpec extends PekkoSpec { } } } - } - def allRecordsCommitted(): Unit = { - for (entry <- 0 until entryCount) { + def allRecordsCommitted(): Unit = + for (entry <- 0 until entryCount) if (simulatedBuffer(entry * EntrySize) != Committed) fail(s"Entry $entry is not Committed") - } - } } "RollingEventLog algorithm" must { diff --git a/remote/src/test/scala/org/apache/pekko/remote/artery/SendQueueSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/artery/SendQueueSpec.scala index 062d1358dd1..849753e97f5 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/artery/SendQueueSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/artery/SendQueueSpec.scala @@ -68,10 +68,9 @@ class SendQueueSpec extends PekkoSpec(""" def sendToDeadLetters[T](pending: Vector[T]): Unit = pending.foreach(system.deadLetters ! _) - def createQueue[E](capacity: Int): Queue[E] = { + def createQueue[E](capacity: Int): Queue[E] = // new java.util.concurrent.LinkedBlockingQueue[E](capacity) new ManyToOneConcurrentArrayQueue[E](capacity) - } "SendQueue" must { @@ -125,10 +124,9 @@ class SendQueueSpec extends PekkoSpec(""" sendQueue.inject(queue) for (round <- 1 to 100000) { - for (n <- 1 to burstSize) { + for (n <- 1 to burstSize) if (!sendQueue.offer(round * 1000 + n)) fail(s"offer failed at round $round message $n") - } downstream.expectNext((1 to burstSize).map(_ + round * 1000).toList) downstream.request(1) } @@ -170,8 +168,7 @@ class SendQueueSpec extends PekkoSpec(""" "deliver first message" in { - def test(f: (Queue[String], SendQueue.QueueValue[String], TestSubscriber.Probe[String]) => Unit): Unit = { - + def test(f: (Queue[String], SendQueue.QueueValue[String], TestSubscriber.Probe[String]) => Unit): Unit = (1 to 100).foreach { _ => val queue = createQueue[String](16) val (sendQueue, downstream) = @@ -188,7 +185,6 @@ class SendQueueSpec extends PekkoSpec(""" downstream.expectNext("d") downstream.cancel() } - } test { (queue, sendQueue, downstream) => queue.offer("a") diff --git a/remote/src/test/scala/org/apache/pekko/remote/artery/SystemMessageDeliverySpec.scala b/remote/src/test/scala/org/apache/pekko/remote/artery/SystemMessageDeliverySpec.scala index 22d520e7e4b..ccc4c6b1220 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/artery/SystemMessageDeliverySpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/artery/SystemMessageDeliverySpec.scala @@ -98,9 +98,9 @@ abstract class AbstractSystemMessageDeliverySpec(c: Config) extends ArteryMultiN .via(new SystemMessageAcker(inboundContext)) } - protected def drop(dropSeqNumbers: Vector[Long]): Flow[OutboundEnvelope, OutboundEnvelope, NotUsed] = { + protected def drop(dropSeqNumbers: Vector[Long]): Flow[OutboundEnvelope, OutboundEnvelope, NotUsed] = Flow[OutboundEnvelope].statefulMap(() => dropSeqNumbers)( - (dropping, outboundEnvelope) => { + (dropping, outboundEnvelope) => outboundEnvelope.message match { case SystemMessageEnvelope(_, seqNo, _) => val i = dropping.indexOf(seqNo) @@ -109,10 +109,8 @@ abstract class AbstractSystemMessageDeliverySpec(c: Config) extends ArteryMultiN } else (dropping, Some(outboundEnvelope)) case _ => (dropping, None) - } - }, _ => None) + }, _ => None) .collect { case Some(outboundEnvelope) => outboundEnvelope } - } protected def randomDrop[T](dropRate: Double): Flow[T, T, NotUsed] = Flow[T].mapConcat { elem => if (ThreadLocalRandom.current().nextDouble() < dropRate) Nil @@ -188,9 +186,8 @@ class SystemMessageDeliverySpec extends AbstractSystemMessageDeliverySpec(System system.log.debug("systemC terminated") // DeathWatchNotification is sent from systemC, failure detection takes longer than 3 seconds expectTerminated(remoteRef, 10.seconds) - } finally { + } finally shutdown(systemC) - } } "be resent when some in the middle are lost" in { diff --git a/remote/src/test/scala/org/apache/pekko/remote/artery/TestContext.scala b/remote/src/test/scala/org/apache/pekko/remote/artery/TestContext.scala index 4093116deb2..6397aaf5e46 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/artery/TestContext.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/artery/TestContext.scala @@ -41,10 +41,9 @@ private[remote] class TestInboundContext( private val associationsByAddress = new ConcurrentHashMap[Address, OutboundContext]() private val associationsByUid = new ConcurrentHashMap[Long, OutboundContext]() - override def sendControl(to: Address, message: ControlMessage) = { + override def sendControl(to: Address, message: ControlMessage) = if (ThreadLocalRandom.current().nextDouble() >= replyDropRate) association(to).sendControl(message) - } override def association(remoteAddress: Address): OutboundContext = associationsByAddress.get(remoteAddress) match { @@ -128,9 +127,8 @@ private[remote] class TestControlMessageSubject extends ControlMessageSubject { Future.successful(Done) } - override def detach(observer: ControlMessageObserver): Unit = { + override def detach(observer: ControlMessageObserver): Unit = observers.remove(observer) - } def sendControl(env: InboundEnvelope): Unit = { val iter = observers.iterator() diff --git a/remote/src/test/scala/org/apache/pekko/remote/artery/UntrustedSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/artery/UntrustedSpec.scala index 2151f7a6248..0dafc35e949 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/artery/UntrustedSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/artery/UntrustedSpec.scala @@ -53,9 +53,8 @@ object UntrustedSpec { } class Child(testActor: ActorRef) extends Actor { - override def postStop(): Unit = { + override def postStop(): Unit = testActor ! s"${self.path.name} stopped" - } def receive = { case msg => testActor.forward(msg) } @@ -86,11 +85,9 @@ class UntrustedSpec extends ArteryMultiNodeSpec(UntrustedSpec.config) with Impli val receptionist = system.actorOf(Props(classOf[Receptionist], testActor), "receptionist") lazy val remoteDaemon = { - { - val p = TestProbe()(client) - client.actorSelection(RootActorPath(address) / receptionist.path.elements).tell(IdentifyReq("/remote"), p.ref) - p.expectMsgType[ActorIdentity].ref.get - } + val p = TestProbe()(client) + client.actorSelection(RootActorPath(address) / receptionist.path.elements).tell(IdentifyReq("/remote"), p.ref) + p.expectMsgType[ActorIdentity].ref.get } lazy val target2 = { diff --git a/remote/src/test/scala/org/apache/pekko/remote/artery/compress/CompressionIntegrationSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/artery/compress/CompressionIntegrationSpec.scala index 34e9975b8ab..5e6a1af654f 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/artery/compress/CompressionIntegrationSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/artery/compress/CompressionIntegrationSpec.scala @@ -437,10 +437,9 @@ class TestMessageSerializer(val system: ExtendedActorSystem) extends SerializerW case _ => throw new NotSerializableException() } - override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = { + override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = manifest match { case TestMessageManifest => TestMessage(new String(bytes)) case unknown => throw new Exception("Unknown manifest: " + unknown) } - } } diff --git a/remote/src/test/scala/org/apache/pekko/remote/artery/tcp/SecureRandomFactorySpec.scala b/remote/src/test/scala/org/apache/pekko/remote/artery/tcp/SecureRandomFactorySpec.scala index 19dfe783206..afce05c4c27 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/artery/tcp/SecureRandomFactorySpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/artery/tcp/SecureRandomFactorySpec.scala @@ -31,7 +31,7 @@ class SecureRandomFactoryInvalidPRNGSpec extends SecureRandomFactorySpec("Invali abstract class SecureRandomFactorySpec(alg: String) extends PekkoSpec { var prng: SecureRandom = null - def isSupported: Boolean = { + def isSupported: Boolean = try { prng = SecureRandomFactory.createSecureRandom(alg, NoMarkerLogging) prng.nextInt() // Has to work @@ -44,7 +44,6 @@ abstract class SecureRandomFactorySpec(alg: String) extends PekkoSpec { info(e.toString) false } - } s"Artery's Secure Random support ($alg)" must { if (isSupported) { diff --git a/remote/src/test/scala/org/apache/pekko/remote/artery/tcp/TlsTcpSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/artery/tcp/TlsTcpSpec.scala index 4a642864031..a89681e82b2 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/artery/tcp/TlsTcpSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/artery/tcp/TlsTcpSpec.scala @@ -73,14 +73,13 @@ class TlsTcpWithRotatingKeysSSLEngineSpec extends TlsTcpSpec(ConfigFactory.parse object TlsTcpSpec { - lazy val config: Config = { + lazy val config: Config = ConfigFactory.parseString(s""" pekko.remote.artery { transport = tls-tcp large-message-destinations = [ "/user/large" ] } """) - } } diff --git a/remote/src/test/scala/org/apache/pekko/remote/artery/tcp/ssl/PeerSubjectVerifierSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/artery/tcp/ssl/PeerSubjectVerifierSpec.scala index 90c9bce52d6..b57b20777a0 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/artery/tcp/ssl/PeerSubjectVerifierSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/artery/tcp/ssl/PeerSubjectVerifierSpec.scala @@ -47,7 +47,7 @@ class PeerSubjectVerifierSpec extends AnyWordSpec with Matchers { } } - def inMemSession(peerCert: X509Certificate): SSLSession = { + def inMemSession(peerCert: X509Certificate): SSLSession = new SSLSession { override def getPeerCertificates: Array[Certificate] = Array(peerCert) override def getId: Array[Byte] = throw new UnsupportedOperationException() @@ -71,5 +71,4 @@ class PeerSubjectVerifierSpec extends AnyWordSpec with Matchers { override def getPacketBufferSize: Int = throw new UnsupportedOperationException() override def getApplicationBufferSize: Int = throw new UnsupportedOperationException() } - } } diff --git a/remote/src/test/scala/org/apache/pekko/remote/artery/tcp/ssl/RotatingKeysSSLEngineProviderSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/artery/tcp/ssl/RotatingKeysSSLEngineProviderSpec.scala index 0c3b2680a98..edd4b81806d 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/artery/tcp/ssl/RotatingKeysSSLEngineProviderSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/artery/tcp/ssl/RotatingKeysSSLEngineProviderSpec.scala @@ -214,15 +214,14 @@ object RotatingKeysSSLEngineProviderSpec { case NonFatal(t) => throw new RuntimeException(s"Can't copy resource [$resourceName] to [$to].", t) } } - def deployCaCert(): Unit = { + def deployCaCert(): Unit = deployResource("ssl/exampleca.crt", cacertLocation.toPath) - } def deployKeySet(setName: String): Unit = { deployResource(setName + ".crt", certLocation.toPath) deployResource(setName + ".pem", keyLocation.toPath) } def cleanupTemporaryDirectory(): Unit = { - temporaryDirectory.toFile.listFiles().foreach { _.delete() } + temporaryDirectory.toFile.listFiles().foreach(_.delete()) temporaryDirectory.toFile.delete() } } @@ -256,9 +255,8 @@ abstract class RotatingKeysSSLEngineProviderSpec(extraConfig: String) } // sleep to force the cache in sysB's instance to expire - def awaitCacheExpiration(): Unit = { + def awaitCacheExpiration(): Unit = Thread.sleep((RotatingKeysSSLEngineProviderSpec.cacheTtlInSeconds + 1) * 1000) - } def contact(fromSystem: ActorSystem, toPath: ActorPath): Unit = { val senderOnSource = TestProbe()(fromSystem) diff --git a/remote/src/test/scala/org/apache/pekko/remote/classic/ActorsLeakSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/classic/ActorsLeakSpec.scala index 2a9dd698d05..c825a1182f7 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/classic/ActorsLeakSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/classic/ActorsLeakSpec.scala @@ -110,9 +110,8 @@ class ActorsLeakSpec extends PekkoSpec(ActorsLeakSpec.config) with ImplicitSende remoteSystem.actorSelection(echoPath).tell(Identify(1), probe.ref) probe.expectMsgType[ActorIdentity].ref.nonEmpty should be(true) - } finally { + } finally remoteSystem.terminate() - } Await.result(remoteSystem.whenTerminated, 10.seconds) } @@ -153,9 +152,8 @@ class ActorsLeakSpec extends PekkoSpec(ActorsLeakSpec.config) with ImplicitSende assertResult(beforeQuarantineActors)(afterQuarantineActors) - } finally { + } finally remoteSystem.terminate() - } Await.result(remoteSystem.whenTerminated, 10.seconds) @@ -182,9 +180,8 @@ class ActorsLeakSpec extends PekkoSpec(ActorsLeakSpec.config) with ImplicitSende // This will make sure that no SHUTDOWN message gets through Await.result(RARP(system).provider.transport.managementCommand(ForceDisassociate(remoteAddress)), 3.seconds) - } finally { + } finally remoteSystem.terminate() - } EventFilter .warning(start = s"Association with remote system [$remoteAddress] has failed", occurrences = 1) @@ -217,9 +214,8 @@ class ActorsLeakSpec extends PekkoSpec(ActorsLeakSpec.config) with ImplicitSende // This will make sure that no SHUTDOWN message gets through Await.result(RARP(system).provider.transport.managementCommand(ForceDisassociate(remoteAddress)), 3.seconds) - } finally { + } finally remoteSystem.terminate() - } Await.result(remoteSystem.whenTerminated, 10.seconds) awaitAssert(assertResult(initialActors)(targets.flatMap(collectLiveActors).toSet), 10.seconds) diff --git a/remote/src/test/scala/org/apache/pekko/remote/classic/RemoteDeathWatchSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/classic/RemoteDeathWatchSpec.scala index c448719f3e6..cf9673ccd92 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/classic/RemoteDeathWatchSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/classic/RemoteDeathWatchSpec.scala @@ -66,13 +66,11 @@ pekko.actor.warn-about-java-serializer-usage = off pekko.remote.classic.netty.tcp.port=2666 """).withFallback(system.settings.config)) - override def beforeTermination(): Unit = { + override def beforeTermination(): Unit = system.eventStream.publish(TestEvent.Mute(EventFilter.warning(pattern = "received dead letter.*Disassociate"))) - } - override def afterTermination(): Unit = { + override def afterTermination(): Unit = shutdown(other) - } override def expectedTestDuration: FiniteDuration = 120.seconds diff --git a/remote/src/test/scala/org/apache/pekko/remote/classic/RemoteDeploymentAllowListSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/classic/RemoteDeploymentAllowListSpec.scala index 458057f7358..62980782c96 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/classic/RemoteDeploymentAllowListSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/classic/RemoteDeploymentAllowListSpec.scala @@ -35,13 +35,11 @@ object RemoteDeploymentAllowListSpec { } override def preStart(): Unit = {} - override def preRestart(cause: Throwable, msg: Option[Any]): Unit = { + override def preRestart(cause: Throwable, msg: Option[Any]): Unit = target ! "preRestart" - } override def postRestart(cause: Throwable): Unit = {} - override def postStop(): Unit = { + override def postStop(): Unit = target ! "postStop" - } } class EchoNotAllowed extends Actor { @@ -53,13 +51,11 @@ object RemoteDeploymentAllowListSpec { } override def preStart(): Unit = {} - override def preRestart(cause: Throwable, msg: Option[Any]): Unit = { + override def preRestart(cause: Throwable, msg: Option[Any]): Unit = target ! "preRestart" - } override def postRestart(cause: Throwable): Unit = {} - override def postStop(): Unit = { + override def postStop(): Unit = target ! "postStop" - } } val cfg: Config = ConfigFactory.parseString(s""" @@ -105,13 +101,12 @@ object RemoteDeploymentAllowListSpec { pekko.actor.warn-about-java-serializer-usage = off """) - def muteSystem(system: ActorSystem): Unit = { + def muteSystem(system: ActorSystem): Unit = system.eventStream.publish( TestEvent.Mute( EventFilter.error(start = "AssociationError"), EventFilter.warning(start = "AssociationError"), EventFilter.warning(pattern = "received dead letter.*"))) - } } @nowarn("msg=deprecated") diff --git a/remote/src/test/scala/org/apache/pekko/remote/classic/RemoteInitErrorSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/classic/RemoteInitErrorSpec.scala index 5d374eaa11e..3422ce0f938 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/classic/RemoteInitErrorSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/classic/RemoteInitErrorSpec.scala @@ -61,13 +61,12 @@ class RemoteInitErrorSpec extends AnyWordSpec with Matchers { ActorSystem("duplicate", ConfigFactory.parseString("pekko.loglevel=OFF").withFallback(conf)) fail("initialization should fail due to invalid IP address") } catch { - case NonFatal(_) => { + case NonFatal(_) => eventually(timeout(30 seconds), interval(800 milliseconds)) { val current = currentThreadIds() // no new threads should remain compared to the start state (current.diff(start)) should be(empty) } - } } } } diff --git a/remote/src/test/scala/org/apache/pekko/remote/classic/RemoteWatcherSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/classic/RemoteWatcherSpec.scala index d5ba9b048f0..83900cd9f0e 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/classic/RemoteWatcherSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/classic/RemoteWatcherSpec.scala @@ -69,10 +69,9 @@ object RemoteWatcherSpec { // that doesn't interfere with the real watch that is going on in the background context.system.eventStream.publish(TestRemoteWatcher.AddressTerm(address)) - override def quarantine(address: Address, uid: Option[Long], reason: String, harmless: Boolean): Unit = { + override def quarantine(address: Address, uid: Option[Long], reason: String, harmless: Boolean): Unit = // don't quarantine in remoting, but publish a testable message context.system.eventStream.publish(TestRemoteWatcher.Quarantined(address, uid)) - } } @@ -111,9 +110,8 @@ class RemoteWatcherSpec extends PekkoSpec(""" pekko.remote.transport.AssociationHandle.Disassociated.getClass, pekko.remote.transport.ActorTransportAdapter.DisassociateUnderlying.getClass)(_)) - override def afterTermination(): Unit = { + override def afterTermination(): Unit = shutdown(remoteSystem) - } val heartbeatRspB = HeartbeatRsp(remoteAddressUid) diff --git a/remote/src/test/scala/org/apache/pekko/remote/classic/RemotingSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/classic/RemotingSpec.scala index e5ede514be4..f5838ad3032 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/classic/RemotingSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/classic/RemotingSpec.scala @@ -49,13 +49,11 @@ object RemotingSpec { } override def preStart(): Unit = {} - override def preRestart(cause: Throwable, msg: Option[Any]): Unit = { + override def preRestart(cause: Throwable, msg: Option[Any]): Unit = target ! "preRestart" - } override def postRestart(cause: Throwable): Unit = {} - override def postStop(): Unit = { + override def postStop(): Unit = target ! "postStop" - } } class Echo2 extends Actor { @@ -135,13 +133,12 @@ object RemotingSpec { } """) - def muteSystem(system: ActorSystem): Unit = { + def muteSystem(system: ActorSystem): Unit = system.eventStream.publish( TestEvent.Mute( EventFilter.error(start = "AssociationError"), EventFilter.warning(start = "AssociationError"), EventFilter.warning(pattern = "received dead letter.*"))) - } } @nowarn @@ -164,9 +161,8 @@ class RemotingSpec extends PekkoSpec(RemotingSpec.cfg) with ImplicitSender with def getOtherAddress(sys: ActorSystem, proto: String) = sys.asInstanceOf[ExtendedActorSystem].provider.getExternalAddressFor(Address(s"pekko.$proto", "", "", 0)).get def port(sys: ActorSystem, proto: String) = getOtherAddress(sys, proto).port.get - def deploy(sys: ActorSystem, d: Deploy): Unit = { + def deploy(sys: ActorSystem, d: Deploy): Unit = sys.asInstanceOf[ExtendedActorSystem].provider.asInstanceOf[RemoteActorRefProvider].deployer.deploy(d) - } val remote = remoteSystem.actorOf(Props[Echo2](), "echo") @@ -544,9 +540,8 @@ class RemotingSpec extends PekkoSpec(RemotingSpec.cfg) with ImplicitSender with proxySsl ! otherGuy expectMsg(3.seconds, ("pong", otherGuyRemoteTest)) }(otherSystem) - } finally { + } finally shutdown(otherSystem) - } } "should not publish AddressTerminated even on InvalidAssociationExceptions" in { @@ -786,9 +781,9 @@ class RemotingSpec extends PekkoSpec(RemotingSpec.cfg) with ImplicitSender with thisSystem.actorSelection(s"pekko.tcp://other-system@localhost:${otherAddress.getPort}/user/echo") otherSelection.tell("ping", probe.ref) probe.expectNoMessage(200.millis) - try { + try (ActorSystem("other-system", otherConfig), otherSelection) - } catch { + catch { case NonFatal(ex) if ex.getMessage.contains("Failed to bind") && retries > 0 => selectionAndBind(config, thisSystem, probe, retries = retries - 1) case other => @@ -817,12 +812,10 @@ class RemotingSpec extends PekkoSpec(RemotingSpec.cfg) with ImplicitSender with assert(probe.expectMsgType[(String, ActorRef)](500.millis)._1 == "pong") } } - } finally { + } finally shutdown(otherSystem) - } - } finally { + } finally shutdown(thisSystem) - } } "allow other system to connect even if it's not there at first" in { @@ -859,12 +852,10 @@ class RemotingSpec extends PekkoSpec(RemotingSpec.cfg) with ImplicitSender with assert(otherProbe.expectMsgType[(String, ActorRef)](500.millis)._1 == "pong") } } - } finally { + } finally shutdown(otherSystem) - } - } finally { + } finally shutdown(thisSystem) - } } } } diff --git a/remote/src/test/scala/org/apache/pekko/remote/classic/UntrustedSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/classic/UntrustedSpec.scala index c4c74213a79..fc2a822fdd9 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/classic/UntrustedSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/classic/UntrustedSpec.scala @@ -55,9 +55,8 @@ object UntrustedSpec { } class Child(testActor: ActorRef) extends Actor { - override def postStop(): Unit = { + override def postStop(): Unit = testActor ! s"${self.path.name} stopped" - } def receive = { case msg => testActor.forward(msg) } @@ -111,11 +110,9 @@ pekko.actor.serialization-bindings { val receptionist = system.actorOf(Props(classOf[Receptionist], testActor), "receptionist") lazy val remoteDaemon = { - { - val p = TestProbe()(client) - client.actorSelection(RootActorPath(address) / receptionist.path.elements).tell(IdentifyReq("/remote"), p.ref) - p.expectMsgType[ActorIdentity].ref.get - } + val p = TestProbe()(client) + client.actorSelection(RootActorPath(address) / receptionist.path.elements).tell(IdentifyReq("/remote"), p.ref) + p.expectMsgType[ActorIdentity].ref.get } lazy val target2 = { @@ -124,9 +121,8 @@ pekko.actor.serialization-bindings { p.expectMsgType[ActorIdentity].ref.get } - override def afterTermination(): Unit = { + override def afterTermination(): Unit = shutdown(client) - } // need to enable debug log-level without actually printing those messages system.eventStream.publish(TestEvent.Mute(EventFilter.debug())) diff --git a/remote/src/test/scala/org/apache/pekko/remote/classic/transport/SystemMessageDeliveryStressTest.scala b/remote/src/test/scala/org/apache/pekko/remote/classic/transport/SystemMessageDeliveryStressTest.scala index 4c05610b35b..d0afb84e887 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/classic/transport/SystemMessageDeliveryStressTest.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/classic/transport/SystemMessageDeliveryStressTest.scala @@ -75,12 +75,11 @@ object SystemMessageDeliveryStressTest { override def getParent = provider.tempContainer - override def sendSystemMessage(message: SystemMessage): Unit = { + override def sendSystemMessage(message: SystemMessage): Unit = message match { case Failed(_, _, seq) => testActor ! seq case _ => } - } } class SystemMessageSender(val msgCount: Int, val burstSize: Int, val burstDelay: FiniteDuration, val target: ActorRef) diff --git a/remote/src/test/scala/org/apache/pekko/remote/classic/transport/ThrottlerTransportAdapterSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/classic/transport/ThrottlerTransportAdapterSpec.scala index 1acffea7122..9821bdbaa64 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/classic/transport/ThrottlerTransportAdapterSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/classic/transport/ThrottlerTransportAdapterSpec.scala @@ -138,13 +138,12 @@ class ThrottlerTransportAdapterSpec extends PekkoSpec(configA) with ImplicitSend // after we remove the Blackhole we can't be certain of the state // of the connection, repeat until success here ! Lost("Blackhole 3") - awaitCond({ - if (receiveOne(Duration.Zero) == Lost("Blackhole 3")) - true - else { - here ! Lost("Blackhole 3") - false - } + awaitCond( + if (receiveOne(Duration.Zero) == Lost("Blackhole 3")) + true + else { + here ! Lost("Blackhole 3") + false }, 15.seconds) here ! "Cleanup" diff --git a/remote/src/test/scala/org/apache/pekko/remote/classic/transport/netty/NettyTransportSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/classic/transport/netty/NettyTransportSpec.scala index 3f84936b8d0..03fbb413aee 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/classic/transport/netty/NettyTransportSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/classic/transport/netty/NettyTransportSpec.scala @@ -88,9 +88,8 @@ class NettyTransportSpec extends AnyWordSpec with Matchers with BindBehavior { getInternal() should not contain address.toAkkaAddress("tcp") Await.result(sys.terminate(), Duration.Inf) - } finally { + } finally openSS.close() - } } diff --git a/remote/src/test/scala/org/apache/pekko/remote/serialization/DaemonMsgCreateSerializerAllowJavaSerializationSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/serialization/DaemonMsgCreateSerializerAllowJavaSerializationSpec.scala index 1773f9c5a09..c53dc971a0d 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/serialization/DaemonMsgCreateSerializerAllowJavaSerializationSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/serialization/DaemonMsgCreateSerializerAllowJavaSerializationSpec.scala @@ -52,11 +52,10 @@ private[pekko] trait SerializationVerification { self: PekkoSpec => def ser: Serialization - def verifySerialization(msg: DaemonMsgCreate): Unit = { + def verifySerialization(msg: DaemonMsgCreate): Unit = assertDaemonMsgCreate( msg, ser.deserialize(ser.serialize(msg).get, classOf[DaemonMsgCreate]).get.asInstanceOf[DaemonMsgCreate]) - } def assertDaemonMsgCreate(expected: DaemonMsgCreate, got: DaemonMsgCreate): Unit = { // can't compare props.creator when function diff --git a/remote/src/test/scala/org/apache/pekko/remote/serialization/SerializationTransportInformationSpec.scala b/remote/src/test/scala/org/apache/pekko/remote/serialization/SerializationTransportInformationSpec.scala index 946f87abcea..351865bc13a 100644 --- a/remote/src/test/scala/org/apache/pekko/remote/serialization/SerializationTransportInformationSpec.scala +++ b/remote/src/test/scala/org/apache/pekko/remote/serialization/SerializationTransportInformationSpec.scala @@ -66,7 +66,7 @@ object SerializationTransportInformationSpec { } } - private def verifyTransportInfo(): Unit = { + private def verifyTransportInfo(): Unit = Serialization.currentTransportInformation.value match { case null => throw new IllegalStateException("currentTransportInformation was not set") @@ -77,7 +77,6 @@ object SerializationTransportInformationSpec { throw new IllegalStateException( s"wrong address in currentTransportInformation, ${t.address} != ${system.provider.getDefaultAddress}") } - } } } @@ -135,9 +134,8 @@ abstract class AbstractSerializationTransportInformationSpec(config: Config) } } - override def afterTermination(): Unit = { + override def afterTermination(): Unit = shutdown(system2) - } } class SerializationTransportInformationSpec diff --git a/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/ActorRefModule.scala b/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/ActorRefModule.scala index 6a59afed5ce..840da554892 100644 --- a/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/ActorRefModule.scala +++ b/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/ActorRefModule.scala @@ -67,11 +67,10 @@ import pekko.annotation.InternalApi extends StdScalarDeserializer[ActorRef](classOf[ActorRef]) with ActorSystemAccess { - def deserialize(jp: JsonParser, ctxt: DeserializationContext): ActorRef = { + def deserialize(jp: JsonParser, ctxt: DeserializationContext): ActorRef = if (jp.currentTokenId() == JsonTokenId.ID_STRING) { val serializedActorRef = jp.getText() currentSystem().provider.resolveActorRef(serializedActorRef) } else ctxt.handleUnexpectedToken(handledType(), jp).asInstanceOf[ActorRef] - } } diff --git a/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/ActorSystemAccess.scala b/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/ActorSystemAccess.scala index 34d0d829bb2..8db23686477 100644 --- a/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/ActorSystemAccess.scala +++ b/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/ActorSystemAccess.scala @@ -22,14 +22,13 @@ import pekko.serialization.Serialization * INTERNAL API */ @InternalApi private[pekko] trait ActorSystemAccess { - def currentSystem(): ExtendedActorSystem = { + def currentSystem(): ExtendedActorSystem = Serialization.currentTransportInformation.value match { case null => throw new IllegalStateException( "Can't access current ActorSystem, Serialization.currentTransportInformation was not set.") case Serialization.Information(_, system) => system.asInstanceOf[ExtendedActorSystem] } - } } /** diff --git a/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/AddressModule.scala b/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/AddressModule.scala index 0b47aa7316c..32f0f55cd1f 100644 --- a/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/AddressModule.scala +++ b/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/AddressModule.scala @@ -44,9 +44,8 @@ import pekko.annotation.InternalApi * INTERNAL API */ @InternalApi private[pekko] class AddressSerializer extends StdScalarSerializer[Address](classOf[Address]) { - override def serialize(value: Address, jgen: JsonGenerator, provider: SerializerProvider): Unit = { + override def serialize(value: Address, jgen: JsonGenerator, provider: SerializerProvider): Unit = jgen.writeString(value.toString) - } } /** @@ -61,11 +60,10 @@ import pekko.annotation.InternalApi */ @InternalApi private[pekko] class AddressDeserializer extends StdScalarDeserializer[Address](classOf[Address]) { - def deserialize(jp: JsonParser, ctxt: DeserializationContext): Address = { + def deserialize(jp: JsonParser, ctxt: DeserializationContext): Address = if (jp.currentTokenId() == JsonTokenId.ID_STRING) { val serializedAddress = jp.getText() AddressFromURIString(serializedAddress) } else ctxt.handleUnexpectedToken(handledType(), jp).asInstanceOf[Address] - } } diff --git a/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/FiniteDurationModule.scala b/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/FiniteDurationModule.scala index 50fe97ae20c..fb016315cc2 100644 --- a/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/FiniteDurationModule.scala +++ b/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/FiniteDurationModule.scala @@ -50,9 +50,8 @@ import pekko.util.JavaDurationConverters._ */ @InternalApi private[pekko] class FiniteDurationSerializer extends StdScalarSerializer[FiniteDuration](classOf[FiniteDuration]) { - override def serialize(value: FiniteDuration, jgen: JsonGenerator, provider: SerializerProvider): Unit = { + override def serialize(value: FiniteDuration, jgen: JsonGenerator, provider: SerializerProvider): Unit = DurationSerializer.INSTANCE.serialize(value.asJava, jgen, provider) - } } /** @@ -68,7 +67,6 @@ import pekko.util.JavaDurationConverters._ @InternalApi private[pekko] class FiniteDurationDeserializer extends StdScalarDeserializer[FiniteDuration](classOf[FiniteDuration]) { - def deserialize(jp: JsonParser, ctxt: DeserializationContext): FiniteDuration = { + def deserialize(jp: JsonParser, ctxt: DeserializationContext): FiniteDuration = DurationDeserializer.INSTANCE.deserialize(jp, ctxt).asScala - } } diff --git a/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/JacksonModule.scala b/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/JacksonModule.scala index cbb0a2dae3c..9cd05931c0c 100644 --- a/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/JacksonModule.scala +++ b/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/JacksonModule.scala @@ -48,12 +48,11 @@ import pekko.annotation.InternalApi override def findSerializer( config: SerializationConfig, javaType: JavaType, - beanDesc: BeanDescription): JsonSerializer[_] = { + beanDesc: BeanDescription): JsonSerializer[_] = if (clazz.isAssignableFrom(javaType.getRawClass)) deserializer() else super.findSerializer(config, javaType, beanDesc) - } } @@ -62,12 +61,11 @@ import pekko.annotation.InternalApi override def findBeanDeserializer( javaType: JavaType, config: DeserializationConfig, - beanDesc: BeanDescription): JsonDeserializer[_] = { + beanDesc: BeanDescription): JsonDeserializer[_] = if (clazz.isAssignableFrom(javaType.getRawClass)) serializer() else super.findBeanDeserializer(javaType, config, beanDesc) - } } } @@ -89,19 +87,17 @@ import pekko.annotation.InternalApi def version: Version = JacksonModule.version - def setupModule(context: SetupContext): Unit = { + def setupModule(context: SetupContext): Unit = initializers.result().foreach(_.apply(context)) - } def addSerializer( clazz: Class[_], serializer: () => JsonSerializer[_], - deserializer: () => JsonDeserializer[_]): this.type = { + deserializer: () => JsonDeserializer[_]): this.type = this += { ctx => ctx.addSerializers(new SerializerResolverByClass(clazz, serializer)) ctx.addDeserializers(new DeserializerResolverByClass(clazz, deserializer)) } - } protected def +=(init: SetupContext => Unit): this.type = { initializers += init; this } protected def +=(ser: Serializers): this.type = this += (_.addSerializers(ser)) diff --git a/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/JacksonObjectMapperProvider.scala b/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/JacksonObjectMapperProvider.scala index deae791ae66..74a30993604 100644 --- a/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/JacksonObjectMapperProvider.scala +++ b/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/JacksonObjectMapperProvider.scala @@ -156,7 +156,7 @@ object JacksonObjectMapperProvider extends ExtensionId[JacksonObjectMapperProvid jsonFactory } - private def getBufferRecyclerPool(cfg: Config): RecyclerPool[BufferRecycler] = { + private def getBufferRecyclerPool(cfg: Config): RecyclerPool[BufferRecycler] = cfg.getString("buffer-recycler.pool-instance") match { case "thread-local" => JsonRecyclerPools.threadLocalPool() case "lock-free" => JsonRecyclerPools.newLockFreePool() @@ -166,7 +166,6 @@ object JacksonObjectMapperProvider extends ExtensionId[JacksonObjectMapperProvid case "bounded" => JsonRecyclerPools.newBoundedPool(cfg.getInt("buffer-recycler.bounded-pool-size")) case other => throw new IllegalArgumentException(s"Unknown recycler-pool: $other") } - } @nowarn("msg=deprecated") private def configureObjectMapperFeatures( @@ -356,9 +355,8 @@ final class JacksonObjectMapperProvider(system: ExtendedActorSystem) extends Ext * @param jsonFactory optional `JsonFactory` such as `CBORFactory`, for plain JSON `None` (defaults) * can be used */ - def getOrCreate(bindingName: String, jsonFactory: Option[JsonFactory]): ObjectMapper = { + def getOrCreate(bindingName: String, jsonFactory: Option[JsonFactory]): ObjectMapper = objectMappers.computeIfAbsent(bindingName, _ => create(bindingName, jsonFactory)) - } /** * Java API: Returns an existing Jackson `ObjectMapper` that was created previously with this method, or diff --git a/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/JacksonSerializer.scala b/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/JacksonSerializer.scala index a400ba0de61..d410e7075cc 100644 --- a/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/JacksonSerializer.scala +++ b/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/JacksonSerializer.scala @@ -52,23 +52,21 @@ import pekko.util.OptionVal private val prefixSpring: String = "org.springframework." private val prefixC3P0: String = "com.mchange.v2.c3p0." - def isAllowedClassName(className: String): Boolean = { + def isAllowedClassName(className: String): Boolean = if (defaultNoDeserClassNames.contains(className)) false else if (className.startsWith(prefixC3P0) && className.endsWith("DataSource")) false else true - } - def isAllowedClass(clazz: Class[_]): Boolean = { + def isAllowedClass(clazz: Class[_]): Boolean = if (clazz.getName.startsWith(prefixSpring)) { isAllowedSpringClass(clazz) } else true - } - @tailrec private def isAllowedSpringClass(clazz: Class[_]): Boolean = { + @tailrec private def isAllowedSpringClass(clazz: Class[_]): Boolean = if (clazz == null || clazz.equals(classOf[java.lang.Object])) true else { @@ -81,17 +79,15 @@ import pekko.util.OptionVal else isAllowedSpringClass(clazz.getSuperclass) } - } } val disallowedSerializationBindings: Set[Class[_]] = Set(classOf[java.io.Serializable], classOf[java.io.Serializable], classOf[java.lang.Comparable[_]]) - def isGZipped(bytes: Array[Byte]): Boolean = { + def isGZipped(bytes: Array[Byte]): Boolean = (bytes != null) && (bytes.length >= 2) && (bytes(0) == GZIPInputStream.GZIP_MAGIC.toByte) && (bytes(1) == (GZIPInputStream.GZIP_MAGIC >> 8).toByte) - } final case class LZ4Meta(offset: Int, length: Int) { import LZ4Meta._ @@ -113,11 +109,10 @@ import pekko.util.OptionVal object LZ4Meta { val LZ4_MAGIC = 0x87D96DF6 // The last 4 bytes of `printf akka | sha512sum` - def apply(bytes: Array[Byte]): LZ4Meta = { + def apply(bytes: Array[Byte]): LZ4Meta = LZ4Meta(8, bytes.length) - } - def get(buffer: ByteBuffer): OptionVal[LZ4Meta] = { + def get(buffer: ByteBuffer): OptionVal[LZ4Meta] = if (buffer.remaining() < 4) { OptionVal.None } else if (buffer.getInt() != LZ4_MAGIC) { @@ -125,17 +120,14 @@ import pekko.util.OptionVal } else { OptionVal.Some(LZ4Meta(8, buffer.getInt())) } - } - def get(bytes: Array[Byte]): OptionVal[LZ4Meta] = { + def get(bytes: Array[Byte]): OptionVal[LZ4Meta] = get(ByteBuffer.wrap(bytes)) - } } - def isLZ4(bytes: Array[Byte]): Boolean = { + def isLZ4(bytes: Array[Byte]): Boolean = LZ4Meta.get(bytes).isDefined - } } @@ -191,7 +183,7 @@ import pekko.util.OptionVal private val conf = JacksonObjectMapperProvider.configForBinding(bindingName, system.settings.config) private val isDebugEnabled = conf.getBoolean("verbose-debug-logging") && log.isDebugEnabled private final val BufferSize = 1024 * 4 - private val compressionAlgorithm: Compression.Algoritm = { + private val compressionAlgorithm: Compression.Algoritm = toRootLowerCase(conf.getString("compression.algorithm")) match { case "off" => Compression.Off case "gzip" => @@ -205,7 +197,6 @@ import pekko.util.OptionVal s"Unknown compression algorithm [$other], possible values are " + """"off" or "gzip"""") } - } private val migrations: Map[String, JacksonMigration] = { import pekko.util.ccompat.JavaConverters._ conf.getConfig("migrations").root.unwrapped.asScala.toMap.map { @@ -298,7 +289,7 @@ import pekko.util.OptionVal result } - private def logToBinaryDuration(obj: AnyRef, startTime: Long, bytes: Array[Byte], result: Array[Byte]) = { + private def logToBinaryDuration(obj: AnyRef, startTime: Long, bytes: Array[Byte], result: Array[Byte]) = if (isDebugEnabled) { val durationMicros = (System.nanoTime - startTime) / 1000 if (bytes.length == result.length) @@ -315,7 +306,6 @@ import pekko.util.OptionVal result.length, bytes.length) } - } override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = { checkAllowedSerializationBindings() @@ -395,7 +385,7 @@ import pekko.util.OptionVal bytes: Array[Byte], decompressBytes: Array[Byte], startTime: Long, - clazz: Class[_ <: AnyRef]) = { + clazz: Class[_ <: AnyRef]) = if (isDebugEnabled) { val durationMicros = (System.nanoTime - startTime) / 1000 if (bytes.length == decompressBytes.length) @@ -412,21 +402,19 @@ import pekko.util.OptionVal bytes.length, decompressBytes.length) } - } private def isCaseObject(className: String): Boolean = className.length > 0 && className.charAt(className.length - 1) == '$' - private def checkAllowedClassName(className: String): Unit = { + private def checkAllowedClassName(className: String): Unit = if (!denyList.isAllowedClassName(className)) { val warnMsg = s"Can't serialize/deserialize object of type [$className] in [${getClass.getName}]. " + s"Disallowed (on deny list) for security reasons." log.warning(LogMarker.Security, warnMsg) throw new IllegalArgumentException(warnMsg) } - } - private def checkAllowedClass(clazz: Class[_]): Unit = { + private def checkAllowedClass(clazz: Class[_]): Unit = if (!denyList.isAllowedClass(clazz)) { val warnMsg = s"Can't serialize/deserialize object of type [${clazz.getName}] in [${getClass.getName}]. " + s"Not allowed for security reasons." @@ -440,7 +428,6 @@ import pekko.util.OptionVal log.warning(LogMarker.Security, warnMsg) throw new IllegalArgumentException(warnMsg) } - } /** * Using the `serialization-bindings` as source for the allowed classes. @@ -457,11 +444,10 @@ import pekko.util.OptionVal * That is also possible when changing a binding from a JacksonSerializer to another serializer (e.g. protobuf) * and still bind with the same class (interface). */ - private def isInAllowList(clazz: Class[_]): Boolean = { + private def isInAllowList(clazz: Class[_]): Boolean = isBoundToJacksonSerializer(clazz) || hasAllowedClassPrefix(clazz.getName) - } - private def isBoundToJacksonSerializer(clazz: Class[_]): Boolean = { + private def isBoundToJacksonSerializer(clazz: Class[_]): Boolean = try { // The reason for using isInstanceOf rather than `eq this` is to allow change of // serializer within the Jackson family, but we don't trust other serializers @@ -471,7 +457,6 @@ import pekko.util.OptionVal } catch { case NonFatal(_) => false // not bound } - } private def hasAllowedClassPrefix(className: String): Boolean = allowedClassPrefix.exists(className.startsWith) @@ -483,12 +468,12 @@ import pekko.util.OptionVal * This check is run on first access since it can't be run from constructor because SerializationExtension * can't be accessed from there. */ - private def checkAllowedSerializationBindings(): Unit = { + private def checkAllowedSerializationBindings(): Unit = if (!serializationBindingsCheckedOk) { def isBindingOk(clazz: Class[_]): Boolean = - try { + try serialization.serializerFor(clazz) ne this - } catch { + catch { case NonFatal(_) => true // not bound } @@ -503,7 +488,6 @@ import pekko.util.OptionVal } serializationBindingsCheckedOk = true } - } private def parseManifest(manifest: String) = { val i = manifest.lastIndexOf('#') @@ -512,7 +496,7 @@ import pekko.util.OptionVal (fromVersion, manifestClassName) } - def compress(bytes: Array[Byte]): Array[Byte] = { + def compress(bytes: Array[Byte]): Array[Byte] = compressionAlgorithm match { case Compression.Off => bytes case Compression.GZip(largerThan) if bytes.length <= largerThan => bytes @@ -523,15 +507,13 @@ import pekko.util.OptionVal finally zip.close() bos.toByteArray case Compression.LZ4(largerThan) if bytes.length <= largerThan => bytes - case Compression.LZ4(_) => { + case Compression.LZ4(_) => val meta = LZ4Meta(bytes) val compressed = lz4Compressor.compress(bytes) meta.prependTo(compressed) - } } - } - def decompress(bytes: Array[Byte]): Array[Byte] = { + def decompress(bytes: Array[Byte]): Array[Byte] = if (isGZipped(bytes)) { val in = new GZIPInputStream(new ByteArrayInputStream(bytes)) val out = new ByteArrayOutputStream() @@ -555,6 +537,5 @@ import pekko.util.OptionVal case _ => bytes } } - } } diff --git a/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/StreamRefModule.scala b/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/StreamRefModule.scala index 3d588271e11..aa0985efb8a 100644 --- a/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/StreamRefModule.scala +++ b/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/StreamRefModule.scala @@ -72,13 +72,12 @@ import pekko.stream.StreamRefResolver extends StdScalarDeserializer[SourceRef[_]](classOf[SourceRef[_]]) with ActorSystemAccess { - def deserialize(jp: JsonParser, ctxt: DeserializationContext): SourceRef[_] = { + def deserialize(jp: JsonParser, ctxt: DeserializationContext): SourceRef[_] = if (jp.currentTokenId() == JsonTokenId.ID_STRING) { val serializedSourceRef = jp.getText() StreamRefResolver(currentSystem()).resolveSourceRef(serializedSourceRef) } else ctxt.handleUnexpectedToken(handledType(), jp).asInstanceOf[SourceRef[_]] - } } /** @@ -116,11 +115,10 @@ import pekko.stream.StreamRefResolver extends StdScalarDeserializer[SinkRef[_]](classOf[SinkRef[_]]) with ActorSystemAccess { - def deserialize(jp: JsonParser, ctxt: DeserializationContext): SinkRef[_] = { + def deserialize(jp: JsonParser, ctxt: DeserializationContext): SinkRef[_] = if (jp.currentTokenId() == JsonTokenId.ID_STRING) { val serializedSinkref = jp.getText() StreamRefResolver(currentSystem()).resolveSinkRef(serializedSinkref) } else ctxt.handleUnexpectedToken(handledType(), jp).asInstanceOf[SinkRef[_]] - } } diff --git a/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/TypedActorRefModule.scala b/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/TypedActorRefModule.scala index 7d73b1c944e..5574084dedf 100644 --- a/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/TypedActorRefModule.scala +++ b/serialization-jackson/src/main/scala/org/apache/pekko/serialization/jackson/TypedActorRefModule.scala @@ -67,11 +67,10 @@ import pekko.annotation.InternalApi extends StdScalarDeserializer[ActorRef[_]](classOf[ActorRef[_]]) with ActorSystemAccess { - def deserialize(jp: JsonParser, ctxt: DeserializationContext): ActorRef[_] = { + def deserialize(jp: JsonParser, ctxt: DeserializationContext): ActorRef[_] = if (jp.currentTokenId() == JsonTokenId.ID_STRING) { val serializedActorRef = jp.getText() ActorRefResolver(currentSystem().toTyped).resolveActorRef(serializedActorRef) } else ctxt.handleUnexpectedToken(handledType(), jp).asInstanceOf[ActorRef[_]] - } } diff --git a/serialization-jackson/src/test/scala/doc/org/apache/pekko/serialization/jackson/CustomAdtSerializer.scala b/serialization-jackson/src/test/scala/doc/org/apache/pekko/serialization/jackson/CustomAdtSerializer.scala index ef7eb10d1cc..c824aa45d30 100644 --- a/serialization-jackson/src/test/scala/doc/org/apache/pekko/serialization/jackson/CustomAdtSerializer.scala +++ b/serialization-jackson/src/test/scala/doc/org/apache/pekko/serialization/jackson/CustomAdtSerializer.scala @@ -53,14 +53,13 @@ object CustomAdtSerializer { class DirectionJsonDeserializer extends StdDeserializer[Direction](classOf[Direction]) { import Direction._ - override def deserialize(p: JsonParser, ctxt: DeserializationContext): Direction = { + override def deserialize(p: JsonParser, ctxt: DeserializationContext): Direction = p.getText match { case "N" => North case "E" => East case "S" => South case "W" => West } - } } final case class Compass(currentDirection: Direction) extends MySerializable diff --git a/serialization-jackson/src/test/scala/doc/org/apache/pekko/serialization/jackson/SerializationDocSpec.scala b/serialization-jackson/src/test/scala/doc/org/apache/pekko/serialization/jackson/SerializationDocSpec.scala index 67e435aeec1..556c69c31d9 100644 --- a/serialization-jackson/src/test/scala/doc/org/apache/pekko/serialization/jackson/SerializationDocSpec.scala +++ b/serialization-jackson/src/test/scala/doc/org/apache/pekko/serialization/jackson/SerializationDocSpec.scala @@ -235,9 +235,8 @@ class SerializationDocSpec val serialization: Serialization = SerializationExtension(system) - override def afterAll(): Unit = { + override def afterAll(): Unit = shutdown() - } def verifySerialization(obj: AnyRef): AnyRef = { val serializer = serialization.serializerFor(obj.getClass) diff --git a/serialization-jackson/src/test/scala/org/apache/pekko/serialization/jackson/JacksonSerializerSpec.scala b/serialization-jackson/src/test/scala/org/apache/pekko/serialization/jackson/JacksonSerializerSpec.scala index b0759cf4699..0a6f977eeda 100644 --- a/serialization-jackson/src/test/scala/org/apache/pekko/serialization/jackson/JacksonSerializerSpec.scala +++ b/serialization-jackson/src/test/scala/org/apache/pekko/serialization/jackson/JacksonSerializerSpec.scala @@ -484,7 +484,7 @@ class JacksonJsonSerializerSpec extends JacksonSerializerSpec("jackson-json") { } val customJacksonObjectMapperFactory = new JacksonObjectMapperFactory { - override def newObjectMapper(bindingName: String, jsonFactory: JsonFactory): ObjectMapper = { + override def newObjectMapper(bindingName: String, jsonFactory: JsonFactory): ObjectMapper = if (bindingName == "jackson-json") { val mapper: ObjectMapper = JsonMapper.builder(jsonFactory).build() // some customer configuration of the mapper @@ -492,17 +492,15 @@ class JacksonJsonSerializerSpec extends JacksonSerializerSpec("jackson-json") { mapper } else super.newObjectMapper(bindingName, jsonFactory) - } override def overrideConfiguredSerializationFeatures( bindingName: String, configuredFeatures: immutable.Seq[(SerializationFeature, Boolean)]) - : immutable.Seq[(SerializationFeature, Boolean)] = { + : immutable.Seq[(SerializationFeature, Boolean)] = if (bindingName == "jackson-json") configuredFeatures :+ (SerializationFeature.INDENT_OUTPUT -> true) else super.overrideConfiguredSerializationFeatures(bindingName, configuredFeatures) - } override def overrideConfiguredModules( bindingName: String, @@ -743,29 +741,27 @@ abstract class JacksonSerializerSpec(serializerName: String) def serialization(sys: ActorSystem = system): Serialization = SerializationExtension(sys) - override def afterAll(): Unit = { + override def afterAll(): Unit = shutdown() - } def withSystem[T](config: String)(block: ActorSystem => T): T = { val sys = ActorSystem(system.name, ConfigFactory.parseString(config).withFallback(system.settings.config)) - try { + try block(sys) - } finally shutdown(sys) + finally shutdown(sys) } def withSystem[T](setup: ActorSystemSetup)(block: ActorSystem => T): T = { val sys = ActorSystem(system.name, setup) - try { + try block(sys) - } finally shutdown(sys) + finally shutdown(sys) } - def withTransportInformation[T](sys: ActorSystem = system)(block: () => T): T = { + def withTransportInformation[T](sys: ActorSystem = system)(block: () => T): T = Serialization.withTransportInformation(sys.asInstanceOf[ExtendedActorSystem]) { () => block() } - } def checkSerialization(obj: AnyRef, sys: ActorSystem = system): Unit = { val serializer = serializerFor(obj, sys) @@ -797,10 +793,9 @@ abstract class JacksonSerializerSpec(serializerName: String) blob: Array[Byte], serializerId: Int, manifest: String, - sys: ActorSystem = system): AnyRef = { + sys: ActorSystem = system): AnyRef = // TransportInformation added by serialization.deserialize serialization(sys).deserialize(blob, serializerId, manifest).get - } def serializerFor(obj: AnyRef, sys: ActorSystem = system): JacksonSerializer = serialization(sys).findSerializerFor(obj) match { @@ -1219,11 +1214,11 @@ abstract class JacksonSerializerSpec(serializerName: String) "not allow serialization of deny listed class" in { val serializer = serializerFor(SimpleCommand("ok")) val fileHandler = new FileHandler(s"target/tmp-${this.getClass.getName}") - try { + try intercept[IllegalArgumentException] { serializer.manifest(fileHandler) }.getMessage.toLowerCase should include("deny list") - } finally fileHandler.close() + finally fileHandler.close() } "not allow deserialization of deny list class" in { @@ -1270,9 +1265,9 @@ abstract class JacksonSerializerSpec(serializerName: String) "org.apache.pekko.serialization.jackson.ScalaTestMessages$$TestMessage" = $serializerName } """).withFallback(system.settings.config)) - try { + try SerializationExtension(sys).serialize(SimpleCommand("hi")).get - } finally shutdown(sys) + finally shutdown(sys) } } } diff --git a/slf4j/src/main/scala/org/apache/pekko/event/slf4j/Slf4jLogger.scala b/slf4j/src/main/scala/org/apache/pekko/event/slf4j/Slf4jLogger.scala index 7fbc1fae372..87022cba085 100644 --- a/slf4j/src/main/scala/org/apache/pekko/event/slf4j/Slf4jLogger.scala +++ b/slf4j/src/main/scala/org/apache/pekko/event/slf4j/Slf4jLogger.scala @@ -137,9 +137,8 @@ class Slf4jLogger extends Actor with SLF4JLogging with RequiresMessageQueue[Logg logEvent.mdc.foreach { case (k, v) => MDC.put(k, String.valueOf(v)) } try logStatement - finally { + finally MDC.clear() - } } private final def markerIfPresent(event: LogEvent): Marker = diff --git a/slf4j/src/test/scala/org/apache/pekko/event/slf4j/Slf4jLoggerSpec.scala b/slf4j/src/test/scala/org/apache/pekko/event/slf4j/Slf4jLoggerSpec.scala index 612874a0b66..c2e87992d42 100644 --- a/slf4j/src/test/scala/org/apache/pekko/event/slf4j/Slf4jLoggerSpec.scala +++ b/slf4j/src/test/scala/org/apache/pekko/event/slf4j/Slf4jLoggerSpec.scala @@ -89,9 +89,8 @@ class Slf4jLoggerSpec extends PekkoSpec(Slf4jLoggerSpec.config) with BeforeAndAf val producer = system.actorOf(Props[LogProducer](), name = "logProducer") - override def beforeEach(): Unit = { + override def beforeEach(): Unit = output.reset() - } val sourceThreadRegex = "sourceThread=Slf4jLoggerSpec-pekko.actor.default-dispatcher-[1-9][0-9]*" diff --git a/slf4j/src/test/scala/org/apache/pekko/event/slf4j/Slf4jLoggingFilterSpec.scala b/slf4j/src/test/scala/org/apache/pekko/event/slf4j/Slf4jLoggingFilterSpec.scala index 53e0ff07361..5f3805f0176 100644 --- a/slf4j/src/test/scala/org/apache/pekko/event/slf4j/Slf4jLoggingFilterSpec.scala +++ b/slf4j/src/test/scala/org/apache/pekko/event/slf4j/Slf4jLoggingFilterSpec.scala @@ -55,7 +55,7 @@ object Slf4jLoggingFilterSpec { ref ! "OK" case event: LogEvent => println("# event: " + event) - target.foreach { _ ! event } + target.foreach(_ ! event) } } diff --git a/stream-testkit/src/main/scala/org/apache/pekko/stream/testkit/StreamTestKit.scala b/stream-testkit/src/main/scala/org/apache/pekko/stream/testkit/StreamTestKit.scala index 9486e0d11a0..e8343d530ea 100644 --- a/stream-testkit/src/main/scala/org/apache/pekko/stream/testkit/StreamTestKit.scala +++ b/stream-testkit/src/main/scala/org/apache/pekko/stream/testkit/StreamTestKit.scala @@ -155,9 +155,8 @@ object TestPublisher { * JAVA API * @since 1.1.0 */ - def executeAfterSubscription[T](f: function.Creator[T]): T = { + def executeAfterSubscription[T](f: function.Creator[T]): T = executeAfterSubscription(f.create()) - } /** * Expect a subscription. @@ -490,9 +489,8 @@ object TestSubscriber { /** * Expect and return a stream element. */ - def expectNext(): I = { + def expectNext(): I = expectNext(probe.testKitSettings.SingleExpectDefaultTimeout.dilated) - } /** * Expect and return a stream element during specified time or timeout. @@ -655,9 +653,8 @@ object TestSubscriber { * * See also [[#expectSubscriptionAndError(signalDemand:Boolean)* #expectSubscriptionAndError(signalDemand: Boolean)]] if no demand should be signalled. */ - def expectSubscriptionAndError(): Throwable = { + def expectSubscriptionAndError(): Throwable = expectSubscriptionAndError(true) - } /** * Expect subscription to be followed immediately by an error signal. @@ -733,7 +730,7 @@ object TestSubscriber { * * Expect given next element or error signal, returning whichever was signalled. */ - def expectNextOrError(): Either[Throwable, I] = { + def expectNextOrError(): Either[Throwable, I] = probe.fishForMessage(hint = s"OnNext(_) or error") { case OnNext(_) => true case OnError(_) => true @@ -742,13 +739,12 @@ object TestSubscriber { case OnError(err) => Left(err) case _ => throw new RuntimeException() // compiler exhaustiveness check pleaser } - } /** * Fluent DSL * Expect given next element or error signal. */ - def expectNextOrError(element: I, cause: Throwable): Either[Throwable, I] = { + def expectNextOrError(element: I, cause: Throwable): Either[Throwable, I] = probe.fishForMessage(hint = s"OnNext($element) or ${cause.getClass.getName}") { case OnNext(`element`) => true case OnError(`cause`) => true @@ -757,12 +753,11 @@ object TestSubscriber { case OnError(err) => Left(err) case _ => throw new RuntimeException() // compiler exhaustiveness check pleaser } - } /** * Expect next element or stream completion - returning whichever was signalled. */ - def expectNextOrComplete(): Either[OnComplete.type, I] = { + def expectNextOrComplete(): Either[OnComplete.type, I] = probe.fishForMessage(hint = s"OnNext(_) or OnComplete") { case OnNext(_) => true case OnComplete => true @@ -771,7 +766,6 @@ object TestSubscriber { case OnNext(n: I @unchecked) => Right(n) case _ => throw new RuntimeException() // compiler exhaustiveness check pleaser } - } /** * Fluent DSL diff --git a/stream-testkit/src/main/scala/org/apache/pekko/stream/testkit/TestGraphStage.scala b/stream-testkit/src/main/scala/org/apache/pekko/stream/testkit/TestGraphStage.scala index 459ba03fcc3..ddb287bcb47 100644 --- a/stream-testkit/src/main/scala/org/apache/pekko/stream/testkit/TestGraphStage.scala +++ b/stream-testkit/src/main/scala/org/apache/pekko/stream/testkit/TestGraphStage.scala @@ -69,7 +69,7 @@ private[testkit] class TestSinkStage[T, M]( val inHandler = logic.handlers(in.id).asInstanceOf[InHandler] logic.handlers(in.id) = new InHandler { - override def onPush(): Unit = { + override def onPush(): Unit = try { inHandler.onPush() probe.ref ! GraphStageMessages.Push @@ -78,8 +78,7 @@ private[testkit] class TestSinkStage[T, M]( probe.ref ! GraphStageMessages.StageFailure(GraphStageMessages.Push, ex) throw ex } - } - override def onUpstreamFinish(): Unit = { + override def onUpstreamFinish(): Unit = try { inHandler.onUpstreamFinish() probe.ref ! GraphStageMessages.UpstreamFinish @@ -89,8 +88,7 @@ private[testkit] class TestSinkStage[T, M]( throw ex } - } - override def onUpstreamFailure(ex: Throwable): Unit = { + override def onUpstreamFailure(ex: Throwable): Unit = try { inHandler.onUpstreamFailure(ex) probe.ref ! GraphStageMessages.Failure(ex) @@ -99,7 +97,6 @@ private[testkit] class TestSinkStage[T, M]( probe.ref ! GraphStageMessages.StageFailure(GraphStageMessages.Failure(ex), ex) throw ex } - } } (logic, mat) } @@ -133,7 +130,7 @@ private[testkit] class TestSourceStage[T, M]( val outHandler = logic.handlers(out.id).asInstanceOf[OutHandler] logic.handlers(out.id) = new OutHandler { - override def onPull(): Unit = { + override def onPull(): Unit = try { outHandler.onPull() probe.ref ! GraphStageMessages.Pull @@ -142,8 +139,7 @@ private[testkit] class TestSourceStage[T, M]( probe.ref ! GraphStageMessages.StageFailure(GraphStageMessages.Pull, ex) throw ex } - } - override def onDownstreamFinish(cause: Throwable): Unit = { + override def onDownstreamFinish(cause: Throwable): Unit = try { outHandler.onDownstreamFinish(cause) probe.ref ! GraphStageMessages.DownstreamFinish @@ -152,7 +148,6 @@ private[testkit] class TestSourceStage[T, M]( probe.ref ! GraphStageMessages.StageFailure(GraphStageMessages.DownstreamFinish, ex) throw ex } - } } (logic, mat) } diff --git a/stream-testkit/src/main/scala/org/apache/pekko/stream/testkit/javadsl/StreamTestKit.scala b/stream-testkit/src/main/scala/org/apache/pekko/stream/testkit/javadsl/StreamTestKit.scala index 5f42371bf38..009adaa3d12 100644 --- a/stream-testkit/src/main/scala/org/apache/pekko/stream/testkit/javadsl/StreamTestKit.scala +++ b/stream-testkit/src/main/scala/org/apache/pekko/stream/testkit/javadsl/StreamTestKit.scala @@ -38,7 +38,6 @@ object StreamTestKit { * Usually this assertion is run after a test-case to check that all of the * stages have terminated successfully. */ - def assertAllStagesStopped(system: ClassicActorSystemProvider): Unit = { + def assertAllStagesStopped(system: ClassicActorSystemProvider): Unit = assertAllStagesStopped(SystemMaterializer(system).materializer) - } } diff --git a/stream-testkit/src/main/scala/org/apache/pekko/stream/testkit/scaladsl/StreamTestKit.scala b/stream-testkit/src/main/scala/org/apache/pekko/stream/testkit/scaladsl/StreamTestKit.scala index 85d5d5623b8..4eab2ef6cd9 100644 --- a/stream-testkit/src/main/scala/org/apache/pekko/stream/testkit/scaladsl/StreamTestKit.scala +++ b/stream-testkit/src/main/scala/org/apache/pekko/stream/testkit/scaladsl/StreamTestKit.scala @@ -138,7 +138,7 @@ object StreamTestKit { builder.toString() } - private def appendInterpreterSnapshot(builder: StringBuilder, snapshot: RunningInterpreterImpl): Unit = { + private def appendInterpreterSnapshot(builder: StringBuilder, snapshot: RunningInterpreterImpl): Unit = try { builder.append("\ndot format graph for deadlock analysis:\n") builder.append("================================================================\n") @@ -173,6 +173,5 @@ object StreamTestKit { } catch { case _: NoSuchElementException => builder.append("Not all logics has a stage listed, cannot create graph") } - } } diff --git a/stream-testkit/src/test/scala/org/apache/pekko/stream/impl/fusing/GraphInterpreterSpecKit.scala b/stream-testkit/src/test/scala/org/apache/pekko/stream/impl/fusing/GraphInterpreterSpecKit.scala index 0cdbafea717..02c4de01be1 100644 --- a/stream-testkit/src/test/scala/org/apache/pekko/stream/impl/fusing/GraphInterpreterSpecKit.scala +++ b/stream-testkit/src/test/scala/org/apache/pekko/stream/impl/fusing/GraphInterpreterSpecKit.scala @@ -250,9 +250,8 @@ object GraphInterpreterSpecKit { stage.shape.outlets.zipWithIndex.foreach { case (inlet, idx) => inlet.id = idx } } - private def setLogicIds(logics: Array[GraphStageLogic]): Unit = { + private def setLogicIds(logics: Array[GraphStageLogic]): Unit = logics.zipWithIndex.foreach { case (logic, idx) => logic.stageId = idx } - } } @@ -537,13 +536,12 @@ trait GraphInterpreterSpecKit extends StreamSpec { // Must be lazy because I turned this stage "inside-out" therefore changing initialization order // to make tests a bit more readable lazy val insideOutStage: GraphStageLogic = new GraphStageLogic(stageshape) { - private def mayFail(task: => Unit): Unit = { + private def mayFail(task: => Unit): Unit = if (!_failOnNextEvent) task else { _failOnNextEvent = false throw testException } - } setHandler(stagein, new InHandler { @@ -630,10 +628,9 @@ trait GraphInterpreterSpecKit extends StreamSpec { setHandler( out, new OutHandler { - override def onPull(): Unit = { + override def onPull(): Unit = if (lastEvent.contains(RequestOne)) lastEvent += RequestAnother else lastEvent += RequestOne - } override def onDownstreamFinish(cause: Throwable): Unit = lastEvent += Cancel(cause) }) @@ -667,9 +664,8 @@ trait GraphInterpreterSpecKit extends StreamSpec { new InHandler { // Modified onPush that does not grab() automatically the element. This accesses some internals. - override def onPush(): Unit = { + override def onPush(): Unit = lastEvent += OnNext(grab(in)) - } override def onUpstreamFinish() = lastEvent += OnComplete override def onUpstreamFailure(ex: Throwable) = lastEvent += OnError(ex) diff --git a/stream-testkit/src/test/scala/org/apache/pekko/stream/testkit/ScriptedTest.scala b/stream-testkit/src/test/scala/org/apache/pekko/stream/testkit/ScriptedTest.scala index 0f4925556fe..72dafcc9507 100644 --- a/stream-testkit/src/test/scala/org/apache/pekko/stream/testkit/ScriptedTest.scala +++ b/stream-testkit/src/test/scala/org/apache/pekko/stream/testkit/ScriptedTest.scala @@ -104,7 +104,7 @@ trait ScriptedTest extends Matchers { completed) } - def complete(): Script[In, Out] = { + def complete(): Script[In, Out] = if (finished) new Script( providedInputs, @@ -115,7 +115,6 @@ trait ScriptedTest extends Matchers { outputEndCursor, completed = true) else fail("received onComplete prematurely") - } def finished: Boolean = outputCursor == expectedOutputs.size @@ -256,8 +255,7 @@ trait ScriptedTest extends Matchers { settings: ActorMaterializerSettings, maximumOverrun: Int = 3, maximumRequest: Int = 3, - maximumBuffer: Int = 3)(op: Flow[In, In, NotUsed] => Flow[In, Out, M])(implicit system: ActorSystem): Unit = { + maximumBuffer: Int = 3)(op: Flow[In, In, NotUsed] => Flow[In, Out, M])(implicit system: ActorSystem): Unit = new ScriptRunner(op, settings, script, maximumOverrun, maximumRequest, maximumBuffer).run() - } } diff --git a/stream-testkit/src/test/scala/org/apache/pekko/stream/testkit/StreamSpec.scala b/stream-testkit/src/test/scala/org/apache/pekko/stream/testkit/StreamSpec.scala index 827a3c4918c..ac7933027ea 100644 --- a/stream-testkit/src/test/scala/org/apache/pekko/stream/testkit/StreamSpec.scala +++ b/stream-testkit/src/test/scala/org/apache/pekko/stream/testkit/StreamSpec.scala @@ -43,7 +43,7 @@ abstract class StreamSpec(_system: ActorSystem) extends PekkoSpec(_system) { def this() = this(ActorSystem(TestKitUtils.testNameFromCallStack(classOf[StreamSpec], "".r), PekkoSpec.testConf)) - override def withFixture(test: NoArgTest) = { + override def withFixture(test: NoArgTest) = super.withFixture(test) match { case failed: Failed => implicit val ec = system.dispatcher @@ -78,5 +78,4 @@ abstract class StreamSpec(_system: ActorSystem) extends PekkoSpec(_system) { case _ => other } } - } } diff --git a/stream-testkit/src/test/scala/org/apache/pekko/stream/testkit/StreamTestKitSpec.scala b/stream-testkit/src/test/scala/org/apache/pekko/stream/testkit/StreamTestKitSpec.scala index 21850fc9d25..7b725251158 100644 --- a/stream-testkit/src/test/scala/org/apache/pekko/stream/testkit/StreamTestKitSpec.scala +++ b/stream-testkit/src/test/scala/org/apache/pekko/stream/testkit/StreamTestKitSpec.scala @@ -59,9 +59,8 @@ class StreamTestKitSpec extends PekkoSpec { error.getMessage should startWith("toStrict received OnError") error.getMessage should include("List(1, 2)") error.getCause should ===(ex) - } finally { + } finally system.eventStream.publish(UnMute(EventFilter[Exception]())) - } } "#toStrict when subscription was already obtained" in { diff --git a/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/ActorSystemLifecycle.scala b/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/ActorSystemLifecycle.scala index 135bd376675..efc0aa16969 100644 --- a/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/ActorSystemLifecycle.scala +++ b/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/ActorSystemLifecycle.scala @@ -48,10 +48,10 @@ trait ActorSystemLifecycle { } @AfterClass - def shutdownActorSystem(): Unit = { - try { + def shutdownActorSystem(): Unit = + try Await.ready(system.terminate(), shutdownTimeout) - } catch { + catch { case _: TimeoutException => val msg = "Failed to stop [%s] within [%s] \n%s".format( system.name, @@ -59,6 +59,5 @@ trait ActorSystemLifecycle { system.asInstanceOf[ActorSystemImpl].printTree) throw new RuntimeException(msg) } - } } diff --git a/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/CancelledSinkSubscriberTest.scala b/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/CancelledSinkSubscriberTest.scala index a24ab2d9715..97fa1ec8e64 100644 --- a/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/CancelledSinkSubscriberTest.scala +++ b/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/CancelledSinkSubscriberTest.scala @@ -25,13 +25,10 @@ class CancelledSinkSubscriberTest extends PekkoSubscriberBlackboxVerification[In override def createElement(element: Int): Int = element - override def required_spec201_blackbox_mustSignalDemandViaSubscriptionRequest() = { + override def required_spec201_blackbox_mustSignalDemandViaSubscriptionRequest() = throw new SkipException("Cancelled sink doesn't signal demand") - } - override def required_spec209_blackbox_mustBePreparedToReceiveAnOnCompleteSignalWithPrecedingRequestCall() = { + override def required_spec209_blackbox_mustBePreparedToReceiveAnOnCompleteSignalWithPrecedingRequestCall() = throw new SkipException("Cancelled sink doesn't signal demand") - } - override def required_spec210_blackbox_mustBePreparedToReceiveAnOnErrorSignalWithPrecedingRequestCall() = { + override def required_spec210_blackbox_mustBePreparedToReceiveAnOnErrorSignalWithPrecedingRequestCall() = throw new SkipException("Cancelled sink doesn't signal demand") - } } diff --git a/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/ConcatTest.scala b/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/ConcatTest.scala index 0d77dae4133..f55239599b8 100644 --- a/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/ConcatTest.scala +++ b/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/ConcatTest.scala @@ -21,8 +21,7 @@ import pekko.stream.scaladsl.Source class ConcatTest extends PekkoPublisherVerification[Int] { - def createPublisher(elements: Long): Publisher[Int] = { + def createPublisher(elements: Long): Publisher[Int] = Source(iterable(elements / 2)).concat(Source(iterable((elements + 1) / 2))).runWith(Sink.asPublisher(false)) - } } diff --git a/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/FusableProcessorTest.scala b/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/FusableProcessorTest.scala index 9be1b43314a..51298825f81 100644 --- a/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/FusableProcessorTest.scala +++ b/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/FusableProcessorTest.scala @@ -21,13 +21,12 @@ import pekko.stream.scaladsl.Flow class FusableProcessorTest extends PekkoIdentityProcessorVerification[Int] { - override def createIdentityProcessor(maxBufferSize: Int): Processor[Int, Int] = { + override def createIdentityProcessor(maxBufferSize: Int): Processor[Int, Int] = Flow[Int] .map(identity) .toProcessor .withAttributes(Attributes.inputBuffer(initial = maxBufferSize / 2, max = maxBufferSize)) .run() - } override def createElement(element: Int): Int = element diff --git a/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/InputStreamSourceTest.scala b/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/InputStreamSourceTest.scala index 55e78c3e93e..69214abff04 100644 --- a/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/InputStreamSourceTest.scala +++ b/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/InputStreamSourceTest.scala @@ -24,7 +24,7 @@ import pekko.util.ByteString class InputStreamSourceTest extends PekkoPublisherVerification[ByteString] { - def createPublisher(elements: Long): Publisher[ByteString] = { + def createPublisher(elements: Long): Publisher[ByteString] = StreamConverters .fromInputStream(() => new InputStream { @@ -37,5 +37,4 @@ class InputStreamSourceTest extends PekkoPublisherVerification[ByteString] { .withAttributes(ActorAttributes.dispatcher("pekko.test.stream-dispatcher")) .take(elements) .runWith(Sink.asPublisher(false)) - } } diff --git a/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/IterablePublisherTest.scala b/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/IterablePublisherTest.scala index a15d1e63b7f..ebe50c4c670 100644 --- a/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/IterablePublisherTest.scala +++ b/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/IterablePublisherTest.scala @@ -21,8 +21,7 @@ import pekko.stream.scaladsl.Source class IterablePublisherTest extends PekkoPublisherVerification[Int] { - override def createPublisher(elements: Long): Publisher[Int] = { + override def createPublisher(elements: Long): Publisher[Int] = Source(iterable(elements)).runWith(Sink.asPublisher(false)) - } } diff --git a/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/MapTest.scala b/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/MapTest.scala index f4a21911a22..c4caced18ee 100644 --- a/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/MapTest.scala +++ b/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/MapTest.scala @@ -19,9 +19,8 @@ import org.apache.pekko.stream.scaladsl.Flow class MapTest extends PekkoIdentityProcessorVerification[Int] { - override def createIdentityProcessor(maxBufferSize: Int): Processor[Int, Int] = { + override def createIdentityProcessor(maxBufferSize: Int): Processor[Int, Int] = Flow[Int].map(elem => elem).named("identity").toProcessor.run() - } override def createElement(element: Int): Int = element diff --git a/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/PekkoIdentityProcessorVerification.scala b/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/PekkoIdentityProcessorVerification.scala index e1ee6f24f8a..116c69eee96 100644 --- a/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/PekkoIdentityProcessorVerification.scala +++ b/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/PekkoIdentityProcessorVerification.scala @@ -40,7 +40,7 @@ abstract class PekkoIdentityProcessorVerification[T](env: TestEnvironment, publi override def createFailedPublisher(): Publisher[T] = TestPublisher.error(new Exception("Unable to serve subscribers right now!")) - def processorFromSubscriberAndPublisher(sub: Subscriber[T], pub: Publisher[T]): Processor[T, T] = { + def processorFromSubscriberAndPublisher(sub: Subscriber[T], pub: Publisher[T]): Processor[T, T] = new Processor[T, T] { override def onSubscribe(s: Subscription): Unit = sub.onSubscribe(s) override def onError(t: Throwable): Unit = sub.onError(t) @@ -48,7 +48,6 @@ abstract class PekkoIdentityProcessorVerification[T](env: TestEnvironment, publi override def onNext(t: T): Unit = sub.onNext(t) override def subscribe(s: Subscriber[_ >: T]): Unit = pub.subscribe(s) } - } /** By default, Pekko Publishers do not support Fanout! */ override def maxSupportedSubscribers: Long = 1L diff --git a/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/SinkholeSubscriberTest.scala b/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/SinkholeSubscriberTest.scala index 4b29185f7ed..41b986d27a7 100644 --- a/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/SinkholeSubscriberTest.scala +++ b/stream-tests-tck/src/test/scala/org/apache/pekko/stream/tck/SinkholeSubscriberTest.scala @@ -27,7 +27,7 @@ import pekko.Done import pekko.stream.impl.SinkholeSubscriber class SinkholeSubscriberTest extends SubscriberWhiteboxVerification[JInt](new TestEnvironment()) with TestNGSuiteLike { - override def createSubscriber(probe: WhiteboxSubscriberProbe[JInt]): Subscriber[JInt] = { + override def createSubscriber(probe: WhiteboxSubscriberProbe[JInt]): Subscriber[JInt] = new Subscriber[JInt] { val hole = new SinkholeSubscriber[JInt](Promise[Done]()) @@ -54,7 +54,6 @@ class SinkholeSubscriberTest extends SubscriberWhiteboxVerification[JInt](new Te probe.registerOnNext(t) } } - } override def createElement(element: Int): JInt = element } diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/ActorMaterializerSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/ActorMaterializerSpec.scala index 2e90a5ef428..35ad2f5d866 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/ActorMaterializerSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/ActorMaterializerSpec.scala @@ -47,9 +47,8 @@ class IndirectMaterializerCreation(ex: ExtendedActorSystem) extends Extension { // extension instantiation blocked on materializer (which has Await.result inside) implicit val mat: ActorMaterializer = ActorMaterializer()(ex) - def futureThing(n: Int): Future[Int] = { + def futureThing(n: Int): Future[Int] = Source.single(n).runWith(Sink.head) - } } @@ -88,9 +87,8 @@ class ActorMaterializerSpec extends StreamSpec with ImplicitSender { // with starvation these fail result.futureValue.size should ===(n + 1) - } finally { + } finally TestKit.shutdownActorSystem(deadlockSystem) - } } "report shutdown status properly" in { @@ -178,9 +176,9 @@ object ActorMaterializerSpec { .take(1) .concat(Source.maybe) .map(p.ref ! _) - .runWith(Sink.onComplete(signal => { + .runWith(Sink.onComplete { signal => p.ref ! signal - })) + }) def receive = Actor.emptyBehavior } diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/DslConsistencySpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/DslConsistencySpec.scala index 7c78fe1af34..6e07990cf75 100755 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/DslConsistencySpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/DslConsistencySpec.scala @@ -114,12 +114,11 @@ class DslConsistencySpec extends AnyWordSpec with Matchers { @nowarn def materializing(m: Method): Boolean = m.getParameterTypes.contains(classOf[ActorMaterializer]) - def assertHasMethod(c: Class[_], name: String): Unit = { + def assertHasMethod(c: Class[_], name: String): Unit = // include class name to get better error message if (!allowMissing.getOrElse(c, Set.empty).contains(name)) c.getMethods.collect { case m if !ignore(m.getName) => c.getName + "." + m.getName } should contain( c.getName + "." + name) - } "Java and Scala DSLs" must { diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/DslFactoriesConsistencySpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/DslFactoriesConsistencySpec.scala index 0d3de6261f6..4253e1e4a2b 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/DslFactoriesConsistencySpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/DslFactoriesConsistencySpec.scala @@ -76,7 +76,7 @@ class DslFactoriesConsistencySpec extends AnyWordSpec with Matchers { (classOf[pekko.stream.scaladsl.Sink[_, _]], classOf[pekko.stream.javadsl.Sink[_, _]]) :: (classOf[pekko.stream.scaladsl.Flow[_, _, _]], classOf[pekko.stream.javadsl.Flow[_, _, _]]) :: (classOf[pekko.stream.scaladsl.RunnableGraph[_]], classOf[pekko.stream.javadsl.RunnableGraph[_]]) :: - (2 to 22) .map { i => (Class.forName(s"scala.Function$i"), Class.forName(s"org.apache.pekko.japi.function.Function$i")) }.toList + (2 to 22) .map {i => (Class.forName(s"scala.Function$i"), Class.forName(s"org.apache.pekko.japi.function.Function$i"))}.toList // format: ON val sSource = classOf[scaladsl.Source[_, _]] @@ -214,7 +214,7 @@ class DslFactoriesConsistencySpec extends AnyWordSpec with Matchers { for { row <- results.groupBy(_.s) matches = row._2.filter(_.matches) - } { + } if (matches.length == 0) { warnings += 1 alert("No match for " + row._1) @@ -237,7 +237,6 @@ class DslFactoriesConsistencySpec extends AnyWordSpec with Matchers { alert(s" > ${m.j.toString}") } } - } if (warnings > 0) { jMethods.foreach { m => @@ -264,7 +263,7 @@ class DslFactoriesConsistencySpec extends AnyWordSpec with Matchers { case class MatchFailure(s: Method, j: Method, reason: String = "") extends MatchResult { val matches = false } case class Match(s: Method, j: Method, reason: String = "") extends MatchResult { val matches = true } - def delegationCheck(s: Method, j: Method): MatchResult = { + def delegationCheck(s: Method, j: Method): MatchResult = if (nameMatch(s.name, j.name)) { if (s.parameterTypes.length == j.parameterTypes.length) if (typeMatch(s.parameterTypes, j.parameterTypes)) @@ -279,7 +278,6 @@ class DslFactoriesConsistencySpec extends AnyWordSpec with Matchers { } else { MatchFailure(s, j, "Names don't match!") } - } def nameMatch(scalaName: String, javaName: String): Boolean = (scalaName, javaName) match { diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/FusingSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/FusingSpec.scala index 59299c9ae2b..58183396199 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/FusingSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/FusingSpec.scala @@ -28,11 +28,10 @@ import pekko.stream.testkit.Utils.TE class FusingSpec extends StreamSpec { - def actorRunningStage = { + def actorRunningStage = GraphInterpreter.currentInterpreter.context - } - val snitchFlow = Flow[Int].map(x => { testActor ! actorRunningStage; x }).async + val snitchFlow = Flow[Int].map { x => testActor ! actorRunningStage; x }.async "SubFusingActorMaterializer" must { @@ -48,7 +47,7 @@ class FusingSpec extends StreamSpec { } "use multiple actors when there are asynchronous boundaries in the subflows (manual)" in { - val async = Flow[Int].map(x => { testActor ! actorRunningStage; x }).async + val async = Flow[Int].map { x => testActor ! actorRunningStage; x }.async Source(0 to 9) .via(snitchFlow.async) .flatMapMerge(5, i => Source.single(i).via(async)) diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/impl/GraphStageLogicSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/impl/GraphStageLogicSpec.scala index 787bbd029eb..b49ffacdad3 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/impl/GraphStageLogicSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/impl/GraphStageLogicSpec.scala @@ -54,9 +54,8 @@ class GraphStageLogicSpec extends StreamSpec with GraphInterpreterSpecKit with S override def onPull(): Unit = { val subOut = new SubSourceOutlet[Int]("subOut") subOut.setHandler(new OutHandler { - override def onPull(): Unit = { + override def onPull(): Unit = () - } }) subOut.push(1) subOut.push(2) // expecting this to fail! @@ -262,7 +261,7 @@ class GraphStageLogicSpec extends StreamSpec with GraphInterpreterSpecKit with S } } - val ex = intercept[IllegalStateException] { Source.fromGraph(source).runWith(Sink.ignore) } + val ex = intercept[IllegalStateException](Source.fromGraph(source).runWith(Sink.ignore)) ex.getMessage should startWith("not yet initialized: only setHandler is allowed in GraphStageLogic constructor") } @@ -275,7 +274,7 @@ class GraphStageLogicSpec extends StreamSpec with GraphInterpreterSpecKit with S } } - val ex = intercept[IllegalStateException] { Source.single(1).runWith(sink) } + val ex = intercept[IllegalStateException](Source.single(1).runWith(sink)) ex.getMessage should startWith("not yet initialized: only setHandler is allowed in GraphStageLogic constructor") } diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/impl/SubInletOutletSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/impl/SubInletOutletSpec.scala index 2afa00c5555..b25d639cc7c 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/impl/SubInletOutletSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/impl/SubInletOutletSpec.scala @@ -91,10 +91,9 @@ class SubInletOutletSpec extends StreamSpec { setHandler(out, new OutHandler { - override def onPull(): Unit = { + override def onPull(): Unit = if (!subIn.hasBeenPulled) subIn.pull() - } }) } } diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/impl/TraversalTestUtils.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/impl/TraversalTestUtils.scala index f16b136bfdb..bb85a4ae0cc 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/impl/TraversalTestUtils.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/impl/TraversalTestUtils.scala @@ -89,9 +89,8 @@ object TraversalTestUtils { val attributesAssignments: List[(AtomicModule[Shape, Any], Attributes)], val islandAssignments: List[(AtomicModule[Shape, Any], Attributes, IslandTag)]) { - override def toString = { + override def toString = outlets.iterator.zip(inlets.iterator).mkString("connections: ", ", ", "") - } } case object TestDefaultIsland extends IslandTag diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/impl/fusing/ActorGraphInterpreterSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/impl/fusing/ActorGraphInterpreterSpec.scala index 770a5caaae7..1817d6e4558 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/impl/fusing/ActorGraphInterpreterSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/impl/fusing/ActorGraphInterpreterSpec.scala @@ -374,12 +374,11 @@ class ActorGraphInterpreterSpec extends StreamSpec { "be able to handle Publisher spec violations without leaking" in { val filthyPublisher = new Publisher[Int] { - override def subscribe(s: Subscriber[_ >: Int]): Unit = { + override def subscribe(s: Subscriber[_ >: Int]): Unit = s.onSubscribe(new Subscription { override def cancel(): Unit = () override def request(n: Long): Unit = throw TE("violating your spec") }) - } } val upstream = TestPublisher.probe[Int]() @@ -444,9 +443,8 @@ class ActorGraphInterpreterSpec extends StreamSpec { override def onPull(): Unit = pull(in) }) - override def postStop(): Unit = { + override def postStop(): Unit = gotStop.countDown() - } } } diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/impl/fusing/AsyncCallbackSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/impl/fusing/AsyncCallbackSpec.scala index 75da2a2fb3e..37a7d96b0fa 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/impl/fusing/AsyncCallbackSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/impl/fusing/AsyncCallbackSpec.scala @@ -61,13 +61,11 @@ class AsyncCallbackSpec extends PekkoSpec(""" early.foreach(cb => cb(callback)) - override def preStart(): Unit = { + override def preStart(): Unit = probe ! Started - } - override def postStop(): Unit = { + override def postStop(): Unit = probe ! Stopped - } setHandlers(in, out, new InHandler with OutHandler { @@ -77,9 +75,8 @@ class AsyncCallbackSpec extends PekkoSpec(""" push(out, n) } - def onPull(): Unit = { + def onPull(): Unit = pull(in) - } }) } @@ -278,7 +275,7 @@ class AsyncCallbackSpec extends PekkoSpec(""" Source.fromGraph(new ManyAsyncCallbacksStage(acbProbe.ref)).toMat(Sink.fromSubscriber(out))(Keep.left).run() val happyPathFeedbacks = - acbs.map(acb => Future { acb.invokeWithFeedback("bö") }.flatMap(identity)) + acbs.map(acb => Future(acb.invokeWithFeedback("bö")).flatMap(identity)) Future.sequence(happyPathFeedbacks).futureValue // will throw on fail or timeout on not completed for (_ <- 0 to 10) acbProbe.expectMsg("bö") diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/impl/fusing/GraphInterpreterPortsSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/impl/fusing/GraphInterpreterPortsSpec.scala index c44b3520b11..a22b04f97c2 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/impl/fusing/GraphInterpreterPortsSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/impl/fusing/GraphInterpreterPortsSpec.scala @@ -33,8 +33,8 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(false) - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() in.pull() @@ -44,9 +44,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(true) in.isClosed should be(false) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() stepAll() @@ -56,8 +56,8 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(true) in.isClosed should be(false) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy in.grab() out.push(0) @@ -67,9 +67,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(true) in.isClosed should be(false) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() stepAll() @@ -79,7 +79,7 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(true) in.hasBeenPulled should be(false) in.isClosed should be(false) - an[IllegalArgumentException] should be thrownBy { out.push(0) } + an[IllegalArgumentException] should be thrownBy out.push(0) in.grab() should ===(0) @@ -89,8 +89,8 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(false) - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() // Cycle completed } @@ -106,7 +106,7 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.pull() - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.grab() } s"propagate complete while downstream is active (chasing = $chasing)" in new PortTestSetup(chasing) { @@ -125,7 +125,7 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(false) - an[IllegalArgumentException] should be thrownBy { out.push(0) } + an[IllegalArgumentException] should be thrownBy out.push(0) stepAll() @@ -135,9 +135,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() in.cancel() // This should have no effect now stepAll() @@ -148,9 +148,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() out.complete() // This should have no effect now stepAll() @@ -161,9 +161,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() } s"propagate complete while upstream is active (chasing = $chasing)" in new PortTestSetup(chasing) { @@ -185,7 +185,7 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(true) in.isClosed should be(false) - an[IllegalArgumentException] should be thrownBy { out.push(0) } + an[IllegalArgumentException] should be thrownBy out.push(0) stepAll() @@ -195,9 +195,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() in.cancel() // This should have no effect now stepAll() @@ -208,9 +208,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() out.complete() // This should have no effect now stepAll() @@ -221,9 +221,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() } @@ -245,7 +245,7 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(true) in.isClosed should be(false) - an[IllegalArgumentException] should be thrownBy { out.push(0) } + an[IllegalArgumentException] should be thrownBy out.push(0) stepAll() @@ -255,9 +255,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() in.cancel() // This should have no effect now stepAll() @@ -268,9 +268,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() out.complete() // This should have no effect now stepAll() @@ -281,9 +281,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() } s"propagate complete while push is in flight (chasing = $chasing)" in new PortTestSetup(chasing) { @@ -308,7 +308,7 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(true) in.isClosed should be(false) - an[IllegalArgumentException] should be thrownBy { out.push(0) } + an[IllegalArgumentException] should be thrownBy out.push(0) step() @@ -318,9 +318,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(true) in.hasBeenPulled should be(false) in.isClosed should be(false) - an[IllegalArgumentException] should be thrownBy { out.push(0) } + an[IllegalArgumentException] should be thrownBy out.push(0) in.grab() should ===(0) - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.grab() step() @@ -330,9 +330,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() out.complete() // This should have no effect now stepAll() @@ -343,9 +343,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() } s"propagate complete while push is in flight and keep ungrabbed element (chasing = $chasing)" in new PortTestSetup( @@ -392,9 +392,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() } s"ignore pull while completing (chasing = $chasing)" in new PortTestSetup(chasing) { @@ -411,9 +411,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() } s"propagate cancel while downstream is active (chasing = $chasing)" in new PortTestSetup(chasing) { @@ -432,8 +432,8 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy in.grab() stepAll() @@ -443,9 +443,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() out.complete() // This should have no effect now stepAll() @@ -456,9 +456,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() in.cancel() // This should have no effect now stepAll() @@ -469,9 +469,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() } s"propagate cancel while upstream is active (chasing = $chasing)" in new PortTestSetup(chasing) { @@ -493,8 +493,8 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy in.grab() stepAll() @@ -504,9 +504,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() out.complete() // This should have no effect now stepAll() @@ -517,9 +517,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() in.cancel() // This should have no effect now stepAll() @@ -530,9 +530,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() } @@ -554,8 +554,8 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() stepAll() @@ -565,9 +565,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() out.complete() // This should have no effect now stepAll() @@ -578,9 +578,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() in.cancel() // This should have no effect now stepAll() @@ -591,9 +591,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() } s"propagate cancel while push is in flight (chasing = $chasing)" in new PortTestSetup(chasing) { @@ -618,7 +618,7 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } + an[IllegalArgumentException] should be thrownBy in.pull() stepAll() @@ -628,9 +628,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() out.complete() // This should have no effect now stepAll() @@ -641,9 +641,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() in.cancel() // This should have no effect now stepAll() @@ -654,9 +654,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() } s"ignore push while cancelling (chasing = $chasing)" in new PortTestSetup(chasing) { @@ -677,9 +677,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() } s"clear ungrabbed element even when cancelled (chasing = $chasing)" in new PortTestSetup(chasing) { @@ -699,8 +699,8 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy in.grab() stepAll() lastEvents() should be(Set(Cancel(out, SubscriptionWithCancelException.NoMoreElementsNeeded))) @@ -709,9 +709,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() } s"ignore any completion if they are concurrent (cancel first) (chasing = $chasing)" in new PortTestSetup( @@ -727,9 +727,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() } s"ignore any completion if they are concurrent (complete first) (chasing = $chasing)" in new PortTestSetup( @@ -745,9 +745,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() } s"ignore completion from a push-complete if cancelled while in flight (chasing = $chasing)" in new PortTestSetup( @@ -768,9 +768,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() } s"ignore completion from a push-complete if cancelled after onPush (chasing = $chasing)" in new PortTestSetup( @@ -790,7 +790,7 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(true) in.hasBeenPulled should be(false) in.isClosed should be(false) - an[IllegalArgumentException] should be thrownBy { out.push(0) } + an[IllegalArgumentException] should be thrownBy out.push(0) in.grab() should ===(0) in.cancel() @@ -802,9 +802,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() } s"not allow to grab element before it arrives (chasing = $chasing)" in new PortTestSetup(chasing) { @@ -812,7 +812,7 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit stepAll() out.push(0) - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.grab() } s"not allow to grab element if already cancelled (chasing = $chasing)" in new PortTestSetup(chasing) { @@ -824,7 +824,7 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit stepAll() - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.grab() } s"propagate failure while downstream is active (chasing = $chasing)" in new PortTestSetup(chasing) { @@ -843,7 +843,7 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(false) - an[IllegalArgumentException] should be thrownBy { out.push(0) } + an[IllegalArgumentException] should be thrownBy out.push(0) stepAll() @@ -853,9 +853,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() in.cancel() // This should have no effect now stepAll() @@ -866,9 +866,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() out.complete() // This should have no effect now stepAll() @@ -879,9 +879,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() } s"propagate failure while upstream is active (chasing = $chasing)" in new PortTestSetup(chasing) { @@ -903,7 +903,7 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(true) in.isClosed should be(false) - an[IllegalArgumentException] should be thrownBy { out.push(0) } + an[IllegalArgumentException] should be thrownBy out.push(0) stepAll() @@ -913,9 +913,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() in.cancel() // This should have no effect now stepAll() @@ -926,9 +926,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() out.complete() // This should have no effect now stepAll() @@ -939,9 +939,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() } @@ -963,7 +963,7 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(true) in.isClosed should be(false) - an[IllegalArgumentException] should be thrownBy { out.push(0) } + an[IllegalArgumentException] should be thrownBy out.push(0) stepAll() @@ -973,9 +973,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() in.cancel() // This should have no effect now stepAll() @@ -986,9 +986,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() out.complete() // This should have no effect now stepAll() @@ -999,9 +999,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() } s"propagate failure while push is in flight (chasing = $chasing)" in new PortTestSetup(chasing) { @@ -1026,7 +1026,7 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(true) in.isClosed should be(false) - an[IllegalArgumentException] should be thrownBy { out.push(0) } + an[IllegalArgumentException] should be thrownBy out.push(0) step() @@ -1036,9 +1036,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(true) in.hasBeenPulled should be(false) in.isClosed should be(false) - an[IllegalArgumentException] should be thrownBy { out.push(0) } + an[IllegalArgumentException] should be thrownBy out.push(0) in.grab() should ===(0) - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.grab() step() @@ -1048,9 +1048,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() out.complete() // This should have no effect now stepAll() @@ -1061,9 +1061,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() } s"propagate failure while push is in flight and keep ungrabbed element (chasing = $chasing)" in new PortTestSetup( @@ -1101,9 +1101,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() } s"ignore any failure completion if they are concurrent (cancel first) (chasing = $chasing)" in new PortTestSetup( @@ -1119,9 +1119,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() } s"ignore any failure completion if they are concurrent (complete first) (chasing = $chasing)" in new PortTestSetup( @@ -1137,9 +1137,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() } s"ignore failure from a push-then-fail if cancelled while in flight (chasing = $chasing)" in new PortTestSetup( @@ -1160,9 +1160,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() } s"ignore failure from a push-then-fail if cancelled after onPush (chasing = $chasing)" in new PortTestSetup( @@ -1182,7 +1182,7 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(true) in.hasBeenPulled should be(false) in.isClosed should be(false) - an[IllegalArgumentException] should be thrownBy { out.push(0) } + an[IllegalArgumentException] should be thrownBy out.push(0) in.grab() should ===(0) in.cancel() @@ -1194,9 +1194,9 @@ class GraphInterpreterPortsSpec extends StreamSpec with GraphInterpreterSpecKit in.isAvailable should be(false) in.hasBeenPulled should be(false) in.isClosed should be(true) - an[IllegalArgumentException] should be thrownBy { in.pull() } - an[IllegalArgumentException] should be thrownBy { out.push(0) } - an[IllegalArgumentException] should be thrownBy { in.grab() } + an[IllegalArgumentException] should be thrownBy in.pull() + an[IllegalArgumentException] should be thrownBy out.push(0) + an[IllegalArgumentException] should be thrownBy in.grab() } } diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/impl/fusing/InterpreterSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/impl/fusing/InterpreterSpec.scala index 1422b5fb7c7..8f01faff3c6 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/impl/fusing/InterpreterSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/impl/fusing/InterpreterSpec.scala @@ -565,14 +565,13 @@ class InterpreterSpec extends StreamSpec with GraphInterpreterSpecKit { * Called when the output port has received a pull, and therefore ready to emit an element, i.e. [[GraphStageLogic.push]] * is now allowed to be called on this port. */ - override def onPull(): Unit = { + override def onPull(): Unit = if (oneMore) { push(out, latest) oneMore = false } else { pull(in) } - } setHandlers(in, out, this) } @@ -592,13 +591,12 @@ class InterpreterSpec extends StreamSpec with GraphInterpreterSpecKit { } // note that the default value of lastElem will be always pushed if the upstream closed at the very beginning without a pulling - override def onPull(): Unit = { + override def onPull(): Unit = if (isClosed(in)) { push(out, lastElem) } else { pull(in) } - } override def onUpstreamFinish(): Unit = {} diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/impl/fusing/KeepGoingStageSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/impl/fusing/KeepGoingStageSpec.scala index ff1f45d1875..94b18bfe1ab 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/impl/fusing/KeepGoingStageSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/impl/fusing/KeepGoingStageSpec.scala @@ -81,9 +81,9 @@ class KeepGoingStageSpec extends StreamSpec { failStage(TE("test")) listener.foreach(_ ! EndOfEventHandler) case Throw => - try { + try throw TE("test") - } finally listener.foreach(_ ! EndOfEventHandler) + finally listener.foreach(_ ! EndOfEventHandler) } setHandler(shape.in, diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/io/DeprecatedTlsSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/io/DeprecatedTlsSpec.scala index ef56dfffcc6..fae589844fa 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/io/DeprecatedTlsSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/io/DeprecatedTlsSpec.scala @@ -94,9 +94,8 @@ object DeprecatedTlsSpec { new OutHandler { override def onPull(): Unit = pull(in) }) - override def onTimer(x: Any): Unit = { + override def onTimer(x: Any): Unit = failStage(new TimeoutException(s"timeout expired, last element was $last")) - } } } @@ -378,7 +377,7 @@ class DeprecatedTlsSpec extends StreamSpec(DeprecatedTlsSpec.configOverrides) wi for { commPattern <- communicationPatterns scenario <- scenarios - } { + } s"work in mode ${commPattern.name} while sending ${scenario.name}" in { val onRHS = debug.via(scenario.flow) val output = @@ -411,7 +410,6 @@ class DeprecatedTlsSpec extends StreamSpec(DeprecatedTlsSpec.configOverrides) wi commPattern.cleanup() } - } "emit an error if the TLS handshake fails certificate checks" in { val getError = Flow[SslTlsInbound] @@ -507,9 +505,9 @@ class DeprecatedTlsSpec extends StreamSpec(DeprecatedTlsSpec.configOverrides) wi Source(scenario.inputs) .via(outFlow) .via(inFlow) - .map(result => { + .map { result => ks.shutdown(); result - }) + } .runWith(Sink.last) Await.result(f, 8.second).utf8String should be(scenario.output.utf8String) @@ -538,13 +536,12 @@ class DeprecatedTlsSpec extends StreamSpec(DeprecatedTlsSpec.configOverrides) wi } } - def rootCauseOf(e: Throwable): Throwable = { + def rootCauseOf(e: Throwable): Throwable = if (JavaVersion.majorVersion >= 11) e // Wrapped in extra 'General SSLEngine problem' (sometimes multiple) // on 1.8.0-265 and before, but not 1.8.0-272 and later... else if (e.isInstanceOf[SSLHandshakeException]) rootCauseOf(e.getCause) else e - } "A SslTlsPlacebo" must { diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/io/FileSinkSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/io/FileSinkSpec.scala index 87eccbe8433..b009a75c875 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/io/FileSinkSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/io/FileSinkSpec.scala @@ -183,9 +183,8 @@ class FileSinkSpec extends StreamSpec(UnboundedMailboxConfig) with ScalaFutures fileSink.get } assertDispatcher(ref, ActorAttributes.IODispatcher.dispatcher) - } finally { + } finally forever.complete(Success(None)) - } } } @@ -202,9 +201,8 @@ class FileSinkSpec extends StreamSpec(UnboundedMailboxConfig) with ScalaFutures .tell(StreamSupervisor.GetChildren, testActor) val ref = expectMsgType[Children].children.find(_.path.toString contains "fileSink").get assertDispatcher(ref, "pekko.actor.default-dispatcher") - } finally { + } finally forever.complete(Success(None)) - } } } @@ -235,7 +233,7 @@ class FileSinkSpec extends StreamSpec(UnboundedMailboxConfig) with ScalaFutures } .runWith(FileIO.toPath(f)) - val ex = intercept[IOOperationIncompleteException] { Await.result(completion, 3.seconds) } + val ex = intercept[IOOperationIncompleteException](Await.result(completion, 3.seconds)) ex.count should equal(1001) ex.getCause should equal(te) checkFileContents(f, TestLines.takeWhile(!_.contains('b')).mkString("")) @@ -262,8 +260,7 @@ class FileSinkSpec extends StreamSpec(UnboundedMailboxConfig) with ScalaFutures new String(out) should ===(contents) } - override def afterTermination(): Unit = { + override def afterTermination(): Unit = fs.close() - } } diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/io/FileSourceSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/io/FileSourceSpec.scala index 9b9f3d9060b..bbeb9992e30 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/io/FileSourceSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/io/FileSourceSpec.scala @@ -48,14 +48,13 @@ class FileSourceSpec extends StreamSpec(UnboundedMailboxConfig) { val fs = Jimfs.newFileSystem("FileSourceSpec", Configuration.unix()) - val TestText = { + val TestText = ("a" * 1000) + ("b" * 1000) + ("c" * 1000) + ("d" * 1000) + ("e" * 1000) + ("f" * 1000) - } val testFile = { val f = Files.createTempFile(fs.getPath("/"), "file-source-spec", ".tmp") @@ -157,9 +156,8 @@ class FileSourceSpec extends StreamSpec(UnboundedMailboxConfig) { sub.request(5000) - for (_ <- 1 to 10) { + for (_ <- 1 to 10) c.expectNext().utf8String should ===(nextChunk().toString) - } c.expectComplete() } @@ -306,8 +304,7 @@ class FileSourceSpec extends StreamSpec(UnboundedMailboxConfig) { } } - override def afterTermination(): Unit = { + override def afterTermination(): Unit = fs.close() - } } diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/io/InputStreamSinkSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/io/InputStreamSinkSpec.scala index f209f523060..f5e0506b0b4 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/io/InputStreamSinkSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/io/InputStreamSinkSpec.scala @@ -215,7 +215,7 @@ class InputStreamSinkSpec extends StreamSpec(UnboundedMailboxConfig) { probe.sendError(ex) sinkProbe.expectMsg(GraphStageMessages.Failure(ex)) - val e = intercept[IOException] { Await.result(Future(inputStream.read()), timeout) } + val e = intercept[IOException](Await.result(Future(inputStream.read()), timeout)) e.getCause should ===(ex) } diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/io/InputStreamSourceSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/io/InputStreamSourceSpec.scala index 6cf45ae934e..98dd931210d 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/io/InputStreamSourceSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/io/InputStreamSourceSpec.scala @@ -72,9 +72,9 @@ class InputStreamSourceSpec extends StreamSpec(UnboundedMailboxConfig) { "return failure if creation fails" in { val fail = new RuntimeException("oh dear indeed") StreamConverters - .fromInputStream(() => { + .fromInputStream { () => throw fail - }) + } .toMat(Sink.ignore)(Keep.left) .run() .failed @@ -124,7 +124,7 @@ class InputStreamSourceSpec extends StreamSpec(UnboundedMailboxConfig) { () => new InputStream { @volatile var emitted = false - override def read(): Int = { + override def read(): Int = if (!emitted) { emitted = true 'M'.toInt @@ -132,7 +132,6 @@ class InputStreamSourceSpec extends StreamSpec(UnboundedMailboxConfig) { latch.await() -1 } - } }, chunkSize = 1) .runWith(TestSink.probe) diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/io/OutputStreamSinkSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/io/OutputStreamSinkSpec.scala index 09498fc5559..e3284c9ad10 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/io/OutputStreamSinkSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/io/OutputStreamSinkSpec.scala @@ -99,13 +99,13 @@ class OutputStreamSinkSpec extends StreamSpec(UnboundedMailboxConfig) with Scala "complete materialized value with the error if creation fails" in { val completion = Source .single(ByteString(1)) - .runWith(StreamConverters.fromOutputStream(() => { + .runWith(StreamConverters.fromOutputStream { () => throw TE("Boom!") new OutputStream { override def write(i: Int): Unit = () override def close() = () } - })) + }) completion.failed.futureValue shouldBe an[IOOperationIncompleteException] } @@ -113,14 +113,13 @@ class OutputStreamSinkSpec extends StreamSpec(UnboundedMailboxConfig) with Scala "complete materialized value with the error if write fails" in { val completion = Source .single(ByteString(1)) - .runWith(StreamConverters.fromOutputStream(() => { + .runWith(StreamConverters.fromOutputStream { () => new OutputStream { - override def write(i: Int): Unit = { + override def write(i: Int): Unit = throw TE("Boom!") - } override def close() = () } - })) + }) completion.failed.futureValue shouldBe an[IOOperationIncompleteException] } @@ -131,9 +130,8 @@ class OutputStreamSinkSpec extends StreamSpec(UnboundedMailboxConfig) with Scala .runWith(StreamConverters.fromOutputStream(() => new OutputStream { override def write(i: Int): Unit = () - override def close(): Unit = { + override def close(): Unit = throw TE("Boom!") - } })) completion.failed.futureValue shouldBe an[IOOperationIncompleteException] diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/io/TcpSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/io/TcpSpec.scala index 403994cf1b8..14c31ab964e 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/io/TcpSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/io/TcpSpec.scala @@ -158,9 +158,8 @@ class TcpSpec extends StreamSpec(""" .runFold(ByteString.empty)((acc, in) => acc ++ in) val serverConnection = server.waitAccept() - for (in <- testInput) { + for (in <- testInput) serverConnection.write(in) - } serverConnection.confirmedClose() Await.result(resultFuture, 3.seconds) should be(expectedOutput) @@ -581,9 +580,9 @@ class TcpSpec extends StreamSpec(""" // Some more verbose info when #21839 happens again system2.actorSelection(path).tell(Identify(()), probe.ref) - try { + try probe.expectMsgType[ActorIdentity].ref.get - } catch { + catch { case _: AssertionError | _: NoSuchElementException => val tree = system2.asInstanceOf[ExtendedActorSystem].printTree fail(s"No TCP selector actor running at [$path], actor tree: $tree") @@ -593,9 +592,8 @@ class TcpSpec extends StreamSpec(""" result.failed.futureValue shouldBe a[StreamTcpException] binding.unbind() - } finally { + } finally TestKit.shutdownActorSystem(system2) - } } "provide full exceptions when connection attempt fails because name cannot be resolved" in { @@ -617,16 +615,15 @@ class TcpSpec extends StreamSpec(""" test.getCause shouldBe a[UnknownHostException] - } finally { + } finally TestKit.shutdownActorSystem(systemWithBrokenDns) - } } } "TCP listen stream" must { // Reusing handler - val echoHandler = Sink.foreach[Tcp.IncomingConnection] { _.flow.join(Flow[ByteString]).run() } + val echoHandler = Sink.foreach[Tcp.IncomingConnection](_.flow.join(Flow[ByteString]).run()) "be able to implement echo" in { val serverAddress = temporaryServerAddress() diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/io/TlsSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/io/TlsSpec.scala index 19de2f0a66f..144f946e77a 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/io/TlsSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/io/TlsSpec.scala @@ -93,9 +93,8 @@ object TlsSpec { new OutHandler { override def onPull(): Unit = pull(in) }) - override def onTimer(x: Any): Unit = { + override def onTimer(x: Any): Unit = failStage(new TimeoutException(s"timeout expired, last element was $last")) - } } } @@ -113,10 +112,10 @@ class TlsSpec extends StreamSpec(TlsSpec.configOverrides) with WithLogCapturing import system.dispatcher "SslTls" must { - "work for TLSv1.2" must { workFor("TLSv1.2", TLS12Ciphers) } + "work for TLSv1.2" must workFor("TLSv1.2", TLS12Ciphers) if (JavaVersion.majorVersion >= 11) - "work for TLSv1.3" must { workFor("TLSv1.3", TLS13Ciphers) } + "work for TLSv1.3" must workFor("TLSv1.3", TLS13Ciphers) def workFor(protocol: String, ciphers: Set[String]): Unit = { val sslContext = initSslContext(protocol) @@ -415,7 +414,7 @@ class TlsSpec extends StreamSpec(TlsSpec.configOverrides) with WithLogCapturing for { commPattern <- communicationPatterns scenario <- scenarios - } { + } s"work in mode ${commPattern.name} while sending ${scenario.name}" in { val onRHS = debug.via(scenario.flow) val output = @@ -447,7 +446,6 @@ class TlsSpec extends StreamSpec(TlsSpec.configOverrides) with WithLogCapturing commPattern.cleanup() } - } "emit an error if the TLS handshake fails certificate checks" in { val getError = Flow[SslTlsInbound] @@ -551,10 +549,10 @@ class TlsSpec extends StreamSpec(TlsSpec.configOverrides) with WithLogCapturing Source(scenario.inputs) .via(outFlow) .via(inFlow) - .map(result => { + .map { result => ks.shutdown() result - }) + } .runWith(Sink.last) Await.result(f, 8.second.dilated).utf8String should be(scenario.output.utf8String) } @@ -588,13 +586,12 @@ class TlsSpec extends StreamSpec(TlsSpec.configOverrides) with WithLogCapturing } } - def rootCauseOf(e: Throwable): Throwable = { + def rootCauseOf(e: Throwable): Throwable = if (JavaVersion.majorVersion >= 11) e // Wrapped in extra 'General SSLEngine problem' (sometimes multiple) // on 1.8.0-265 and before, but not 1.8.0-272 and later... else if (e.isInstanceOf[SSLHandshakeException]) rootCauseOf(e.getCause) else e - } "A SslTlsPlacebo" must { diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/io/compression/CodecSpecSupport.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/io/compression/CodecSpecSupport.scala index 54b9228e20b..7b64de45221 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/io/compression/CodecSpecSupport.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/io/compression/CodecSpecSupport.scala @@ -25,7 +25,7 @@ import org.scalatest.matchers.should.Matchers trait CodecSpecSupport extends Matchers with BeforeAndAfterAll { self: Suite => def readAs(string: String, charset: String = "UTF8") = - equal(string).matcher[String].compose { (_: ByteString).decodeString(charset) } + equal(string).matcher[String].compose((_: ByteString).decodeString(charset)) def hexDump(bytes: ByteString) = bytes.map("%02x".format(_)).mkString def fromHexDump(dump: String) = dump.grouped(2).toArray.map(chars => Integer.parseInt(new String(chars), 16).toByte) diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/io/compression/DeflateSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/io/compression/DeflateSpec.scala index 90a7f3551b8..dd1f0f69773 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/io/compression/DeflateSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/io/compression/DeflateSpec.scala @@ -35,11 +35,10 @@ class DeflateSpec extends CoderSpec("deflate") { protected def newEncodedOutputStream(underlying: OutputStream): OutputStream = new DeflaterOutputStream(underlying) - override def extraTests(): Unit = { + override def extraTests(): Unit = "throw early if header is corrupt" in { (the[RuntimeException] thrownBy { ourDecode(ByteString(0, 1, 2, 3, 4)) }).ultimateCause should be(a[DataFormatException]) } - } } diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/ActorRefBackpressureSourceSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/ActorRefBackpressureSourceSpec.scala index 897a1f52a99..38cabf830cd 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/ActorRefBackpressureSourceSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/ActorRefBackpressureSourceSpec.scala @@ -69,7 +69,7 @@ class ActorRefBackpressureSourceSpec extends StreamSpec { sub.request(1) @scala.annotation.tailrec - def verifyNext(n: Int): Unit = { + def verifyNext(n: Int): Unit = if (n > 10) s.expectComplete() else @@ -81,7 +81,6 @@ class ActorRefBackpressureSourceSpec extends StreamSpec { case Left(e) => fail(s"Expected IllegalStateException, got ${e.getClass}", e) } - } verifyNext(1) } diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/ActorRefSourceSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/ActorRefSourceSpec.scala index d4afb84a2c4..053178f2ade 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/ActorRefSourceSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/ActorRefSourceSpec.scala @@ -167,7 +167,7 @@ class ActorRefSourceSpec extends StreamSpec { s.request(10) - def verifyNext(n: Int): Unit = { + def verifyNext(n: Int): Unit = if (n > 10) s.expectComplete() else @@ -176,7 +176,6 @@ class ActorRefSourceSpec extends StreamSpec { case Right(x) => fail(s"expected $n, got $x") case Left(_) => // ok, completed } - } verifyNext(1) } @@ -200,12 +199,11 @@ class ActorRefSourceSpec extends StreamSpec { } "complete and materialize the stream after receiving completion message" in { - val (ref, done) = { + val (ref, done) = Source .actorRef({ case "ok" => CompletionStrategy.draining }, PartialFunction.empty, 3, OverflowStrategy.dropBuffer) .toMat(Sink.ignore)(Keep.both) .run() - } ref ! "ok" done.futureValue should be(Done) } diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/AggregateWithBoundarySpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/AggregateWithBoundarySpec.scala index 0cda1362b65..57541046864 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/AggregateWithBoundarySpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/AggregateWithBoundarySpec.scala @@ -90,12 +90,11 @@ class AggregateWithTimeBoundaryAndSimulatedTimeSpec extends AnyWordSpecLike with "pekko.scheduler.implementation", ConfigValueFactory.fromAnyRef("org.apache.pekko.testkit.ExplicitlyTriggeredScheduler")))) - private def getEts(actor: ActorSystem): ExplicitlyTriggeredScheduler = { + private def getEts(actor: ActorSystem): ExplicitlyTriggeredScheduler = actor.scheduler match { case ets: ExplicitlyTriggeredScheduler => ets case other => throw new Exception(s"expecting ${classOf[ExplicitlyTriggeredScheduler]} but got ${other.getClass}") } - } private def timePasses(amount: FiniteDuration)(implicit actorSystem: ActorSystem): Unit = getEts(actorSystem).timePasses(amount) diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/AttributesSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/AttributesSpec.scala index 15e37fe7443..dd417756f0b 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/AttributesSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/AttributesSpec.scala @@ -83,9 +83,8 @@ object AttributesSpec { override val shape = SinkShape(in) override def createLogicAndMaterializedValue(inheritedAttributes: Attributes): (GraphStageLogic, Attributes) = { val logic = new GraphStageLogic(shape) { - override def preStart(): Unit = { + override def preStart(): Unit = pull(in) - } setHandler(in, new InHandler { override def onPush(): Unit = { @@ -389,9 +388,8 @@ class AttributesSpec val inputBoundary = logics.find(_.label.startsWith("BatchingActorInputBoundary")).get inputBoundary.label should include("fill=0/1,") // dodgy but see no other way to inspect from snapshot - } finally { + } finally materializer.shutdown() - } } } @@ -473,9 +471,8 @@ class AttributesSpec sourcePromise.success(None) complete.futureValue // block until stream completes - } finally { + } finally materializer.shutdown() - } } "get input buffer size from surrounding .addAttributes (wrapping)" in { @@ -508,9 +505,8 @@ class AttributesSpec sourcePromise.success(None) complete.futureValue // block until stream completes - } finally { + } finally materializer.shutdown() - } } "get input buffer size from async(dispatcher, inputBufferSize)" in { @@ -548,9 +544,8 @@ class AttributesSpec sourcePromise.success(None) complete.futureValue // block until stream completes - } finally { + } finally materializer.shutdown() - } } } @@ -686,9 +681,8 @@ class AttributesSpec // should not override stage specific dispatcher dispatcher should startWith("AttributesSpec-pekko.actor.default-blocking-io-dispatcher") - } finally { + } finally myDispatcherMaterializer.shutdown() - } } @@ -726,9 +720,8 @@ class AttributesSpec threadName.futureValue should startWith("AttributesSpec-default-dispatcher-override-my-dispatcher-") - } finally { + } finally TestKit.shutdownActorSystem(system) - } } "use the default-io-dispatcher by default" in { @@ -754,9 +747,8 @@ class AttributesSpec threadName.futureValue should startWith("AttributesSpec-io-dispatcher-override-my-io-dispatcher-") - } finally { + } finally TestKit.shutdownActorSystem(system) - } } } diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/BoundedSourceQueueSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/BoundedSourceQueueSpec.scala index 738e84d9657..af34ec30495 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/BoundedSourceQueueSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/BoundedSourceQueueSpec.scala @@ -200,10 +200,9 @@ class BoundedSourceQueueSpec extends StreamSpec("""pekko.loglevel = debug downstream.request(10) for (round <- 1 to 100000) { - for (n <- 1 to burstSize) { + for (n <- 1 to burstSize) if (sendQueue.offer(round * 1000 + n) != QueueOfferResult.Enqueued) fail(s"offer failed at round $round message $n") - } downstream.expectNext((1 to burstSize).map(_ + round * 1000).toList) downstream.request(1) } diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/CoupledTerminationFlowSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/CoupledTerminationFlowSpec.scala index 2e6f914833b..c400b76c02f 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/CoupledTerminationFlowSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/CoupledTerminationFlowSpec.scala @@ -112,13 +112,12 @@ class CoupledTerminationFlowSpec extends StreamSpec(""" val probe = TestProbe() val f = Flow.fromSinkAndSourceCoupledMat(Sink.cancelled, Source.fromPublisher(new Publisher[String] { - override def subscribe(subscriber: Subscriber[_ >: String]): Unit = { + override def subscribe(subscriber: Subscriber[_ >: String]): Unit = subscriber.onSubscribe(new Subscription { override def cancel(): Unit = probe.ref ! "cancelled" override def request(l: Long): Unit = () // do nothing }) - } }))(Keep.none) // completes right away, should complete the sink as well f.runWith(Source.maybe, Sink.ignore) // these do nothing. @@ -251,10 +250,10 @@ class CoupledTerminationFlowSpec extends StreamSpec(""" val catchEffect = Source .maybe[String] - .mapMaterializedValue(p => { + .mapMaterializedValue { p => p.future.onComplete(t => probe.ref ! t) NotUsed - }) + } val assertCancel = () => { val m = probe.expectMsgType[Try[Option[String]]] m.isFailure should ===(false) diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowBatchSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowBatchSpec.scala index feb38298616..a8294952f48 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowBatchSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowBatchSpec.scala @@ -60,9 +60,8 @@ class FlowBatchSpec extends StreamSpec(""" .run() val sub = subscriber.expectSubscription() - for (i <- 1 to 10) { + for (i <- 1 to 10) publisher.sendNext(i) - } subscriber.expectNoMessage(1.second) sub.request(1) subscriber.expectNext(List(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)) diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowBufferSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowBufferSpec.scala index a287dc4fb8f..3e1e804da51 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowBufferSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowBufferSpec.scala @@ -197,9 +197,8 @@ class FlowBufferSpec extends StreamSpec(""" subscriber.expectNoMessage(500.millis) // drain - for (i <- 1 to 100) { + for (i <- 1 to 100) subscriber.requestNext(i) - } subscriber.request(1) subscriber.expectNoMessage(1.seconds) @@ -238,8 +237,7 @@ class FlowBufferSpec extends StreamSpec(""" subscriber.expectError(error) } - for (strategy <- List(OverflowStrategy.dropHead, OverflowStrategy.dropTail, OverflowStrategy.dropBuffer)) { - + for (strategy <- List(OverflowStrategy.dropHead, OverflowStrategy.dropTail, OverflowStrategy.dropBuffer)) s"work with $strategy if buffer size of one" in { val publisher = TestPublisher.probe[Int]() @@ -265,7 +263,6 @@ class FlowBufferSpec extends StreamSpec(""" sub.cancel() } - } } } diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowCompileSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowCompileSpec.scala index 21ae42a0e40..76cd5685be7 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowCompileSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowCompileSpec.scala @@ -30,7 +30,7 @@ class FlowCompileSpec extends StreamSpec { val strSeq = Source(Seq("a", "b", "c")) import scala.concurrent.ExecutionContext.Implicits.global - val intFut = Source.fromFuture(Future { 3 }) + val intFut = Source.fromFuture(Future(3)) "Flow" should { "not run" in { diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowConcatAllLazySpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowConcatAllLazySpec.scala index 7495360c770..f36bdea92ed 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowConcatAllLazySpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowConcatAllLazySpec.scala @@ -82,10 +82,10 @@ class FlowConcatAllLazySpec extends StreamSpec(""" "lazy materialization other sources" in { val materialized = new AtomicBoolean() Source(1 to 3) - .concatAllLazy(Source.lazySource(() => { + .concatAllLazy(Source.lazySource { () => materialized.set(true) Source.single(4) - })) + }) .runWith(TestSink.probe) .request(2) .expectNext(1, 2) diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowConflateSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowConflateSpec.scala index b7e70f94023..92ed5726537 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowConflateSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowConflateSpec.scala @@ -82,9 +82,8 @@ class FlowConflateSpec extends StreamSpec(""" .run() val sub = subscriber.expectSubscription() - for (i <- 1 to 100) { + for (i <- 1 to 100) publisher.sendNext(i) - } subscriber.expectNoMessage(1.second) sub.request(1) subscriber.expectNext(5050) @@ -98,9 +97,8 @@ class FlowConflateSpec extends StreamSpec(""" Source.fromPublisher(publisher).conflate(_ + _).to(Sink.fromSubscriber(subscriber)).run() val sub = subscriber.expectSubscription() - for (i <- 1 to 100) { + for (i <- 1 to 100) publisher.sendNext(i) - } subscriber.expectNoMessage(1.second) sub.request(1) subscriber.expectNext(5050) diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowDelaySpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowDelaySpec.scala index 1b0a5d1e898..0a0fe1270d7 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowDelaySpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowDelaySpec.scala @@ -296,10 +296,10 @@ class FlowDelaySpec extends StreamSpec { .map(start => System.nanoTime() - start) .runWith(TestSink.probe) - elems.foreach(_ => { + elems.foreach { _ => val next = probe.request(1).expectNext(fixedDelay + fixedDelay.dilated) next should be >= fixedDelay.toNanos - }) + } probe.expectComplete() diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowDispatcherSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowDispatcherSpec.scala index 51e47f7e494..9268452bc38 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowDispatcherSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowDispatcherSpec.scala @@ -33,7 +33,7 @@ class FlowDispatcherSpec extends StreamSpec(s"my-dispatcher = $${pekko.test.stre implicit val materializer: ActorMaterializer = ActorMaterializer(settings) val probe = TestProbe() - Source(List(1, 2, 3)).map(i => { probe.ref ! Thread.currentThread().getName(); i }).to(Sink.ignore).run() + Source(List(1, 2, 3)).map { i => probe.ref ! Thread.currentThread().getName(); i }.to(Sink.ignore).run() probe.receiveN(3).foreach { case s: String => s should startWith(system.name + "-" + dispatcher) case unexpected => throw new RuntimeException(s"Unexpected: $unexpected") diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowExpandSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowExpandSpec.scala index e99d9917053..e13beca4526 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowExpandSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowExpandSpec.scala @@ -62,9 +62,8 @@ class FlowExpandSpec extends StreamSpec(""" publisher.sendNext(42) - for (_ <- 1 to 100) { + for (_ <- 1 to 100) subscriber.requestNext(42) - } publisher.sendNext(-42) diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowExtrapolateSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowExtrapolateSpec.scala index 2586a7162be..3a90cda9c3b 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowExtrapolateSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowExtrapolateSpec.scala @@ -62,9 +62,8 @@ class FlowExtrapolateSpec extends StreamSpec(""" publisher.sendNext(42) subscriber.requestNext(42) - for (_ <- 1 to 100) { + for (_ <- 1 to 100) subscriber.requestNext(42 + 1) - } publisher.sendNext(-42) diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowFilterSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowFilterSpec.scala index 44061bf8b10..c0a27dc1e13 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowFilterSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowFilterSpec.scala @@ -49,9 +49,8 @@ class FlowFilterSpec extends StreamSpec(""" .run() val subscription = probe.expectSubscription() - for (_ <- 1 to 10000) { + for (_ <- 1 to 10000) subscription.request(Int.MaxValue) - } probe.expectNext(1) probe.expectComplete() diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowGroupBySpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowGroupBySpec.scala index 356ed65cc57..c1450f61d3e 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowGroupBySpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowGroupBySpec.scala @@ -669,7 +669,7 @@ class FlowGroupBySpec extends StreamSpec(""" .queue[Elem](3) .groupBy(2, _.substream) .buffer(2, OverflowStrategy.backpressure) - .map { _.f() } + .map(_.f()) .async .to(Sink.ignore) .run() diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowMapAsyncSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowMapAsyncSpec.scala index 9edee111d50..0620bb578a5 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowMapAsyncSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowMapAsyncSpec.scala @@ -462,14 +462,13 @@ class FlowMapAsyncSpec extends StreamSpec { } timer.start - def deferred(): Future[Int] = { + def deferred(): Future[Int] = if (counter.incrementAndGet() > parallelism) Future.failed(new Exception("parallelism exceeded")) else { val p = Promise[Int]() queue.offer(p -> System.nanoTime()) p.future } - } try { val N = 10000 @@ -477,9 +476,8 @@ class FlowMapAsyncSpec extends StreamSpec { .mapAsync(parallelism)(_ => deferred()) .runFold(0)((c, _) => c + 1) .futureValue(Timeout(3.seconds)) should ===(N) - } finally { + } finally timer.interrupt() - } } "not invoke the decider twice for the same failed future" in { diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowMapAsyncUnorderedSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowMapAsyncUnorderedSpec.scala index c23b251124e..dd8e99a0611 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowMapAsyncUnorderedSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowMapAsyncUnorderedSpec.scala @@ -347,14 +347,13 @@ class FlowMapAsyncUnorderedSpec extends StreamSpec { } timer.start - def deferred(): Future[Int] = { + def deferred(): Future[Int] = if (counter.incrementAndGet() > parallelism) Future.failed(new Exception("parallelism exceeded")) else { val p = Promise[Int]() queue.offer(p -> System.nanoTime()) p.future } - } try { val N = 10000 @@ -362,9 +361,8 @@ class FlowMapAsyncUnorderedSpec extends StreamSpec { .mapAsyncUnordered(parallelism)(_ => deferred()) .runFold(0)((c, _) => c + 1) .futureValue(Timeout(3.seconds)) should ===(N) - } finally { + } finally timer.interrupt() - } } } diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowMapConcatSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowMapConcatSpec.scala index 6ff2127cad5..b181e13f308 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowMapConcatSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowMapConcatSpec.scala @@ -52,7 +52,7 @@ class FlowMapConcatSpec extends StreamSpec(""" "map and concat grouping with slow downstream" in { val s = TestSubscriber.manualProbe[Int]() val input = (1 to 20).grouped(5).toList - Source(input).mapConcat(identity).map(x => { Thread.sleep(10); x }).runWith(Sink.fromSubscriber(s)) + Source(input).mapConcat(identity).map { x => Thread.sleep(10); x }.runWith(Sink.fromSubscriber(s)) val sub = s.expectSubscription() sub.request(100) for (i <- 1 to 20) s.expectNext(i) diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowMapSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowMapSpec.scala index 701e35b0ff0..461f50810f2 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowMapSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowMapSpec.scala @@ -43,9 +43,8 @@ class FlowMapSpec extends StreamSpec(""" .subscribe(probe) val subscription = probe.expectSubscription() - for (_ <- 1 to 10000) { + for (_ <- 1 to 10000) subscription.request(Int.MaxValue) - } probe.expectNext(6) probe.expectComplete() diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowMapWithResourceSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowMapWithResourceSpec.scala index 56db0ed6254..9b63d8aaeff 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowMapWithResourceSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowMapWithResourceSpec.scala @@ -49,14 +49,13 @@ class FlowMapWithResourceSpec extends StreamSpec(UnboundedMailboxConfig) { private val fs = Jimfs.newFileSystem("MapWithResourceSpec", Configuration.unix()) private val ex = new Exception("TEST") with NoStackTrace - private val manyLines = { + private val manyLines = ("a" * 100 + "\n") * 10 + ("b" * 100 + "\n") * 10 + ("c" * 100 + "\n") * 10 + ("d" * 100 + "\n") * 10 + ("e" * 100 + "\n") * 10 + ("f" * 100 + "\n") * 10 - } private val manyLinesArray = manyLines.split("\n") private val manyLinesPath = { @@ -71,7 +70,7 @@ class FlowMapWithResourceSpec extends StreamSpec(UnboundedMailboxConfig) { } @tailrec - def loop(builder: ListBuffer[String], n: Int): ListBuffer[String] = { + def loop(builder: ListBuffer[String], n: Int): ListBuffer[String] = if (n == 0) { builder } else { @@ -83,16 +82,14 @@ class FlowMapWithResourceSpec extends StreamSpec(UnboundedMailboxConfig) { loop(builder, n - 1) } } - } loop(ListBuffer.empty, maxCount).result() } "MapWithResource" must { "can read contents from a file" in { val p = Source(List(1, 10, 20, 30)) - .mapWithResource(() => newBufferedReader())((reader, count) => { - readLines(reader, count) - }, + .mapWithResource(() => newBufferedReader())((reader, count) => + readLines(reader, count), reader => { reader.close() None @@ -140,10 +137,10 @@ class FlowMapWithResourceSpec extends StreamSpec(UnboundedMailboxConfig) { p.subscribe(c) val sub = c.expectSubscription() - (0 to 49).foreach(i => { + (0 to 49).foreach { i => sub.request(1) c.expectNext() should ===(if (i < 10) manyLinesArray(i) else manyLinesArray(i + 10)) - }) + } sub.request(1) c.expectComplete() } @@ -167,10 +164,10 @@ class FlowMapWithResourceSpec extends StreamSpec(UnboundedMailboxConfig) { p.subscribe(c) val sub = c.expectSubscription() - (0 to 19).foreach(_ => { + (0 to 19).foreach { _ => sub.request(1) c.expectNext() should ===(manyLinesArray(0)) - }) + } sub.cancel() } @@ -204,10 +201,10 @@ class FlowMapWithResourceSpec extends StreamSpec(UnboundedMailboxConfig) { p.subscribe(c) val sub = c.expectSubscription() - (0 to 121).foreach(_ => { + (0 to 121).foreach { _ => sub.request(1) c.expectNext().utf8String should ===(nextChunk()) - }) + } sub.request(1) c.expectComplete() } @@ -395,9 +392,9 @@ class FlowMapWithResourceSpec extends StreamSpec(UnboundedMailboxConfig) { val promise = Promise[Done]() val matVal = Source .single(1) - .mapWithResource(() => { + .mapWithResource { () => newBufferedReader() - })((reader, count) => readLines(reader, count), + }((reader, count) => readLines(reader, count), reader => { reader.close() promise.complete(Success(Done)) @@ -527,9 +524,9 @@ class FlowMapWithResourceSpec extends StreamSpec(UnboundedMailboxConfig) { val p = Source .fromIterator(() => (0 to 50).iterator) .mapWithResource(create, - (_: AutoCloseable, elem) => { + (_: AutoCloseable, elem) => if (elem == 10) throw TE("") else elem - }) + ) .withAttributes(supervisionStrategy(resumingDecider)) .runWith(Sink.asPublisher(false)) val c = TestSubscriber.manualProbe[Int]() @@ -537,10 +534,10 @@ class FlowMapWithResourceSpec extends StreamSpec(UnboundedMailboxConfig) { p.subscribe(c) val sub = c.expectSubscription() - (0 to 48).foreach(i => { + (0 to 48).foreach { i => sub.request(1) c.expectNext() should ===(if (i < 10) i else i + 1) - }) + } sub.request(1) c.expectNext(50) c.expectComplete() @@ -556,9 +553,9 @@ class FlowMapWithResourceSpec extends StreamSpec(UnboundedMailboxConfig) { val p = Source .fromIterator(() => (0 to 50).iterator) .mapWithResource(create, - (_: AutoCloseable, elem) => { + (_: AutoCloseable, elem) => if (elem == 10 || elem == 20) throw TE("") else elem - }) + ) .withAttributes(supervisionStrategy(restartingDecider)) .runWith(Sink.asPublisher(false)) val c = TestSubscriber.manualProbe[Int]() @@ -566,11 +563,11 @@ class FlowMapWithResourceSpec extends StreamSpec(UnboundedMailboxConfig) { p.subscribe(c) val sub = c.expectSubscription() - (0 to 30).filter(i => i != 10 && i != 20).foreach(i => { + (0 to 30).filter(i => i != 10 && i != 20).foreach { i => sub.request(1) c.expectNext() shouldBe i closedCounter.get should ===(if (i < 10) 0 else if (i < 20) 1 else 2) - }) + } sub.cancel() } @@ -583,9 +580,9 @@ class FlowMapWithResourceSpec extends StreamSpec(UnboundedMailboxConfig) { val p = Source .fromIterator(() => (0 to 50).iterator) .mapWithResource(create, - (_: AutoCloseable, elem) => { + (_: AutoCloseable, elem) => if (elem == 10) throw TE("") else elem - }) + ) .withAttributes(supervisionStrategy(stoppingDecider)) .runWith(Sink.asPublisher(false)) val c = TestSubscriber.manualProbe[Int]() @@ -593,17 +590,16 @@ class FlowMapWithResourceSpec extends StreamSpec(UnboundedMailboxConfig) { p.subscribe(c) val sub = c.expectSubscription() - (0 to 9).foreach(i => { + (0 to 9).foreach { i => sub.request(1) c.expectNext() shouldBe i - }) + } sub.request(1) c.expectError() closedCounter.get shouldBe 1 } } - override def afterTermination(): Unit = { + override def afterTermination(): Unit = fs.close() - } } diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowOnCompleteSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowOnCompleteSpec.scala index d2badf0e408..e649b16924d 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowOnCompleteSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowOnCompleteSpec.scala @@ -79,7 +79,7 @@ class FlowOnCompleteSpec extends StreamSpec(""" x } .runWith(foreachSink) - future.onComplete { onCompleteProbe.ref ! _ } + future.onComplete(onCompleteProbe.ref ! _) val proc = p.expectSubscription() proc.expectRequest() proc.sendNext(42) diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowReduceSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowReduceSpec.scala index 05501407265..3672f9f0ef6 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowReduceSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowReduceSpec.scala @@ -82,19 +82,19 @@ class FlowReduceSpec extends StreamSpec { "fail on empty stream using Source.runReduce" in { val result = Source.empty[Int].runReduce(_ + _) - val ex = intercept[NoSuchElementException] { Await.result(result, 3.seconds) } + val ex = intercept[NoSuchElementException](Await.result(result, 3.seconds)) ex.getMessage should include("empty stream") } "fail on empty stream using Flow.reduce" in { val result = Source.empty[Int].via(reduceFlow).runWith(Sink.fold(0)(_ + _)) - val ex = intercept[NoSuchElementException] { Await.result(result, 3.seconds) } + val ex = intercept[NoSuchElementException](Await.result(result, 3.seconds)) ex.getMessage should include("empty stream") } "fail on empty stream using Sink.reduce" in { val result = Source.empty[Int].runWith(reduceSink) - val ex = intercept[NoSuchElementException] { Await.result(result, 3.seconds) } + val ex = intercept[NoSuchElementException](Await.result(result, 3.seconds)) ex.getMessage should include("empty stream") } diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowSpec.scala index 3c918db1ecb..6237f477ac7 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowSpec.scala @@ -64,19 +64,17 @@ class FlowSpec extends StreamSpec(ConfigFactory.parseString("pekko.actor.debug.r def toFanoutPublisher[In, Out](elasticity: Int): (Source[Out, _], Materializer) => Publisher[Out] = (f, m) => f.runWith(Sink.asPublisher(true).withAttributes(Attributes.inputBuffer(elasticity, elasticity)))(m) - def materializeIntoSubscriberAndPublisher[In, Out](flow: Flow[In, Out, _]): (Subscriber[In], Publisher[Out]) = { + def materializeIntoSubscriberAndPublisher[In, Out](flow: Flow[In, Out, _]): (Subscriber[In], Publisher[Out]) = flow.runWith(Source.asSubscriber[In], Sink.asPublisher[Out](false)) - } "A Flow" must { - for ((name, op) <- List("identity" -> identity, "identity2" -> identity2); n <- List(1, 2, 4)) { + for ((name, op) <- List("identity" -> identity, "identity2" -> identity2); n <- List(1, 2, 4)) s"request initial elements from upstream ($name, $n)" in { new ChainSetup(op, settings.withInputBuffer(initialSize = n, maxSize = n), toPublisher) { upstream.expectRequest(upstreamSubscription, this.settings.maxInputBufferSize) } } - } "request more elements from upstream when downstream requests more elements" in { new ChainSetup(identity, settings, toPublisher) { @@ -227,7 +225,7 @@ class FlowSpec extends StreamSpec(ConfigFactory.parseString("pekko.actor.debug.r } "perform transformation operation" in { - val flow = Flow[Int].map(i => { testActor ! i.toString; i.toString }) + val flow = Flow[Int].map { i => testActor ! i.toString; i.toString } val publisher = Source(List(1, 2, 3)).runWith(Sink.asPublisher(false)) Source.fromPublisher(publisher).via(flow).to(Sink.ignore).run() @@ -557,7 +555,7 @@ class FlowSpec extends StreamSpec(ConfigFactory.parseString("pekko.actor.debug.r Source(data).via( Flow.optionalVia( flow, - Flow.fromFunction { (string: String) => string.toInt } + Flow.fromFunction((string: String) => string.toInt) )(Keep.none) ).runWith(TestSink.probe[Option[Int]]) .request(4) diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowStatefulMapConcatSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowStatefulMapConcatSpec.scala index 47a7d44cd30..bea1b7af171 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowStatefulMapConcatSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowStatefulMapConcatSpec.scala @@ -34,7 +34,7 @@ class FlowStatefulMapConcatSpec extends StreamSpec(""" "work in happy case" in { val script = Script(Seq(2) -> Seq(), Seq(1) -> Seq(1, 1), Seq(3) -> Seq(3), Seq(6) -> Seq(6, 6, 6)) TestConfig.RandomTestRange.foreach(_ => - runScript(script)(_.statefulMapConcat(() => { + runScript(script)(_.statefulMapConcat { () => var prev: Option[Int] = None x => prev match { @@ -45,12 +45,12 @@ class FlowStatefulMapConcatSpec extends StreamSpec(""" prev = Some(x) List.empty[Int] } - }))) + })) } "be able to restart" in { Source(List(2, 1, 3, 4, 1)) - .statefulMapConcat(() => { + .statefulMapConcat { () => var prev: Option[Int] = None x => { if (x % 3 == 0) throw ex @@ -63,7 +63,7 @@ class FlowStatefulMapConcatSpec extends StreamSpec(""" List.empty[Int] } } - }) + } .withAttributes(ActorAttributes.supervisionStrategy(Supervision.restartingDecider)) .runWith(TestSink.probe[Int]) .request(2) @@ -75,7 +75,7 @@ class FlowStatefulMapConcatSpec extends StreamSpec(""" "be able to resume" in { Source(List(2, 1, 3, 4, 1)) - .statefulMapConcat(() => { + .statefulMapConcat { () => var prev: Option[Int] = None x => { if (x % 3 == 0) throw ex @@ -88,7 +88,7 @@ class FlowStatefulMapConcatSpec extends StreamSpec(""" List.empty[Int] } } - }) + } .withAttributes(ActorAttributes.supervisionStrategy(Supervision.resumingDecider)) .runWith(TestSink.probe[Int]) .request(2) diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowStatefulMapSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowStatefulMapSpec.scala index 2cf80a96d37..d044ef85aaa 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowStatefulMapSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowStatefulMapSpec.scala @@ -48,11 +48,11 @@ class FlowStatefulMapSpec extends StreamSpec { class BeenCalledTimesGate(nTimes: Int) { private val beenCalled = new AtomicInteger(0) - def mark(): Unit = beenCalled.updateAndGet(current => { + def mark(): Unit = beenCalled.updateAndGet { current => if (current == nTimes) { throw new IllegalStateException(s"Has been called:[$nTimes] times, should not be called anymore.") } else current + 1 - }) + } def ensure(): Unit = if (beenCalled.get() != nTimes) { throw new IllegalStateException(s"Expected to be called:[$nTimes], but only be called:[$beenCalled]") @@ -63,9 +63,8 @@ class FlowStatefulMapSpec extends StreamSpec { "work in the happy case" in { val gate = BeenCalledTimesGate() val sinkProb = Source(List(1, 2, 3, 4, 5)) - .statefulMap(() => 0)((agg, elem) => { - (agg + elem, (agg, elem)) - }, + .statefulMap(() => 0)((agg, elem) => + (agg + elem, (agg, elem)), _ => { gate.mark() None @@ -108,12 +107,11 @@ class FlowStatefulMapSpec extends StreamSpec { "be able to resume" in { val gate = BeenCalledTimesGate() val testSink = Source(List(1, 2, 3, 4, 5)) - .statefulMap(() => 0)((agg, elem) => { + .statefulMap(() => 0)((agg, elem) => if (elem % 2 == 0) throw ex else - (agg + elem, (agg, elem)) - }, + (agg + elem, (agg, elem)), _ => { gate.mark() None @@ -129,12 +127,11 @@ class FlowStatefulMapSpec extends StreamSpec { "be able to restart" in { val gate = BeenCalledTimesGate(2) val testSink = Source(List(1, 2, 3, 4, 5)) - .statefulMap(() => 0)((agg, elem) => { + .statefulMap(() => 0)((agg, elem) => if (elem % 3 == 0) throw ex else - (agg + elem, (agg, elem)) - }, + (agg + elem, (agg, elem)), _ => { gate.mark() None @@ -150,12 +147,11 @@ class FlowStatefulMapSpec extends StreamSpec { "be able to stop" in { val gate = BeenCalledTimesGate() val testSink = Source(List(1, 2, 3, 4, 5)) - .statefulMap(() => 0)((agg, elem) => { + .statefulMap(() => 0)((agg, elem) => if (elem % 3 == 0) throw ex else - (agg + elem, (agg, elem)) - }, + (agg + elem, (agg, elem)), _ => { gate.mark() None @@ -172,9 +168,8 @@ class FlowStatefulMapSpec extends StreamSpec { val gate = BeenCalledTimesGate() val (testSource, testSink) = TestSource .probe[Int] - .statefulMap(() => 0)((agg, elem) => { - (agg + elem, (agg, elem)) - }, + .statefulMap(() => 0)((agg, elem) => + (agg + elem, (agg, elem)), _ => { gate.mark() None @@ -200,9 +195,8 @@ class FlowStatefulMapSpec extends StreamSpec { val gate = BeenCalledTimesGate() val (testSource, testSink) = TestSource .probe[Int] - .statefulMap(() => 0)((agg, elem) => { - (agg + elem, (agg, elem)) - }, + .statefulMap(() => 0)((agg, elem) => + (agg + elem, (agg, elem)), (state: Int) => { gate.mark() Some((state, -1)) @@ -230,9 +224,8 @@ class FlowStatefulMapSpec extends StreamSpec { val promise = Promise[Done]() val testSource = TestSource .probe[Int] - .statefulMap(() => 100)((agg, elem) => { - (agg + elem, (agg, elem)) - }, + .statefulMap(() => 100)((agg, elem) => + (agg + elem, (agg, elem)), (state: Int) => { gate.mark() promise.complete(Success(Done)) @@ -251,9 +244,8 @@ class FlowStatefulMapSpec extends StreamSpec { val testProb = TestSubscriber.probe[(Int, Int)]() val testSource = TestSource .probe[Int] - .statefulMap(() => 100)((agg, elem) => { - (agg + elem, (agg, elem)) - }, + .statefulMap(() => 100)((agg, elem) => + (agg + elem, (agg, elem)), (state: Int) => { gate.mark() promise.complete(Success(Done)) diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowThrottleSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowThrottleSpec.scala index 62dfe56848d..8aba84eb00a 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowThrottleSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowThrottleSpec.scala @@ -340,7 +340,7 @@ class FlowThrottleSpec extends StreamSpec(""" "handle rate calculation function exception" in { val ex = new RuntimeException with NoStackTrace Source(1 to 5) - .throttle(2, 200.millis, 0, _ => { throw ex }, Shaping) + .throttle(2, 200.millis, 0, _ => throw ex, Shaping) .throttle(1, 100.millis, 5, Enforcing) .runWith(TestSink.probe[Int]) .request(5) diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowWatchTerminationSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowWatchTerminationSpec.scala index 63acd59feb1..66b6d469e33 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowWatchTerminationSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowWatchTerminationSpec.scala @@ -46,7 +46,7 @@ class FlowWatchTerminationSpec extends StreamSpec { val (p, future) = TestSource.probe[Int].watchTermination()(Keep.both).to(Sink.ignore).run() p.sendNext(1) p.sendError(ex) - whenReady(future.failed) { _ shouldBe ex } + whenReady(future.failed)(_ shouldBe ex) } "complete the future for an empty stream" in { diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowWithContextSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowWithContextSpec.scala index 9acee47c76d..25f3b6434c2 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowWithContextSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FlowWithContextSpec.scala @@ -176,7 +176,7 @@ class FlowWithContextSpec extends StreamSpec { val baseFlow = Flow[(String, Int)] .asFlowWithContext[String, Int, Int](collapseContext = Tuple2.apply)(extractContext = _._2) .map(_._1) - .unsafeDataVia(Flow.fromFunction[String, Int] { _.toInt }) + .unsafeDataVia(Flow.fromFunction[String, Int](_.toInt)) SourceWithContext .fromTuples(Source(data)) @@ -198,7 +198,7 @@ class FlowWithContextSpec extends StreamSpec { .fromTuples(Source(data)).via( FlowWithContext.unsafeOptionalDataVia( flow, - Flow.fromFunction { (string: String) => string.toInt } + Flow.fromFunction((string: String) => string.toInt) )(Keep.none) ) .runWith(TestSink.probe[(Option[Int], Int)]) diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/ForComprehensionsCompileSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/ForComprehensionsCompileSpec.scala index 1e6fde98f22..6d0dbc6121c 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/ForComprehensionsCompileSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/ForComprehensionsCompileSpec.scala @@ -57,9 +57,8 @@ class ForComprehensionsCompileSpec extends StreamSpec { "be able to be used in a for comprehension which yield a runnable graph" in { val source = Source(1 to 5) val list = new CopyOnWriteArrayList[String]() - val future = (for (i <- source if i % 2 == 0) { - list.add(i.toString) - }).run() + val future = (for (i <- source if i % 2 == 0) + list.add(i.toString)).run() Await.result(future, 3.seconds) shouldBe Done Util.immutableSeq(list) shouldBe List("2", "4") @@ -107,9 +106,8 @@ class ForComprehensionsCompileSpec extends StreamSpec { "be able to be used in a for comprehension which yield a sink" in { val source = Source(1 to 5) val list = new CopyOnWriteArrayList[String]() - val sink = for (i <- Flow[Int] if i % 2 == 0) { + val sink = for (i <- Flow[Int] if i % 2 == 0) list.add(i.toString) - } val future = source.runWith(sink) Await.result(future, 3.seconds) shouldBe Done Util.immutableSeq(list) shouldBe List("2", "4") diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FramingSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FramingSpec.scala index 043fc32f2e1..a193e055d35 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FramingSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/FramingSpec.scala @@ -47,7 +47,7 @@ class FramingSpec extends StreamSpec { private var rechunkBuffer = ByteString.empty - private def rechunk() = { + private def rechunk() = if (!isClosed(in) && ThreadLocalRandom.current().nextBoolean()) pull(in) else { val nextChunkSize = @@ -60,22 +60,19 @@ class FramingSpec extends StreamSpec { completeStage() } else push(out, newChunk) } - } override def onPush(): Unit = { rechunkBuffer ++= grab(in) rechunk() } - override def onPull(): Unit = { + override def onPull(): Unit = rechunk() - } - override def onUpstreamFinish(): Unit = { + override def onUpstreamFinish(): Unit = if (rechunkBuffer.isEmpty) completeStage() else if (isAvailable(out)) onPull() - } setHandlers(in, out, this) } @@ -183,9 +180,8 @@ class FramingSpec extends StreamSpec { val fieldLengths = List(1, 2, 3, 4) val fieldOffsets = List(0, 1, 2, 3, 15, 16, 31, 32, 44, 107) - def encode(payload: ByteString, fieldOffset: Int, fieldLength: Int, byteOrder: ByteOrder): ByteString = { + def encode(payload: ByteString, fieldOffset: Int, fieldLength: Int, byteOrder: ByteOrder): ByteString = encodeComplexFrame(payload, fieldLength, byteOrder, ByteString(new Array[Byte](fieldOffset)), ByteString.empty) - } def encodeComplexFrame( payload: ByteString, diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/GraphMergePrioritizedNSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/GraphMergePrioritizedNSpec.scala index 7fcc5fba26c..cd0f7f23c04 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/GraphMergePrioritizedNSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/GraphMergePrioritizedNSpec.scala @@ -139,13 +139,11 @@ class GraphMergePrioritizedNSpec extends StreamSpec { private def threeSourceMerge[T]( sourceAndPriorities: immutable.Seq[(Source[T, NotUsed], Int)], - probe: ManualProbe[T]) = { - + probe: ManualProbe[T]) = Source .mergePrioritizedN(sourceAndPriorities, eagerComplete = false) .initialDelay(50.millis) .to(Sink.fromSubscriber(probe)) - } "get Priority from graph" in { val elementCount = 10 diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/GraphMergePrioritizedSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/GraphMergePrioritizedSpec.scala index 6b6e7fc9257..45fd1be8186 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/GraphMergePrioritizedSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/GraphMergePrioritizedSpec.scala @@ -154,7 +154,7 @@ class GraphMergePrioritizedSpec extends TwoStreamsSetup { source2: Source[T, NotUsed], source3: Source[T, NotUsed], priorities: Seq[Int], - probe: ManualProbe[T]) = { + probe: ManualProbe[T]) = RunnableGraph.fromGraph(GraphDSL.createGraph(source1, source2, source3)((_, _, _)) { implicit b => (s1, s2, s3) => val merge = b.add(MergePrioritized[T](priorities)) // introduce a delay on the consuming side making it more likely that @@ -166,5 +166,4 @@ class GraphMergePrioritizedSpec extends TwoStreamsSetup { merge.out ~> delayFirst ~> Sink.fromSubscriber(probe) ClosedShape }) - } } diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/GraphOpsIntegrationSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/GraphOpsIntegrationSpec.scala index 4886b5d7cb8..915ba0d59cb 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/GraphOpsIntegrationSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/GraphOpsIntegrationSpec.scala @@ -36,14 +36,13 @@ object GraphOpsIntegrationSpec { override def deepCopy() = ShufflePorts(in1.carbonCopy(), in2.carbonCopy(), out1.carbonCopy(), out2.carbonCopy()) } - def apply[In, Out](pipeline: Flow[In, Out, _]): Graph[ShufflePorts[In, Out], NotUsed] = { + def apply[In, Out](pipeline: Flow[In, Out, _]): Graph[ShufflePorts[In, Out], NotUsed] = GraphDSL.create() { implicit b => val merge = b.add(Merge[In](2)) val balance = b.add(Balance[Out](2)) merge.out ~> pipeline ~> balance.in ShufflePorts(merge.in(0), merge.in(1), balance.out(0), balance.out(1)) } - } } diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/GraphStageTimersSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/GraphStageTimersSpec.scala index 385b41dc0d3..190b8df5a22 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/GraphStageTimersSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/GraphStageTimersSpec.scala @@ -65,9 +65,8 @@ class GraphStageTimersSpec extends StreamSpec { override def onPull(): Unit = pull(in) }) - override def preStart() = { + override def preStart() = sideChannel.asyncCallback = getAsyncCallback(onTestEvent) - } override protected def onTimer(timerKey: Any): Unit = { val tick = Tick(tickCount.next()) diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/GraphZipLatestSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/GraphZipLatestSpec.scala index fdea832c4ec..99ef05ba0e8 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/GraphZipLatestSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/GraphZipLatestSpec.scala @@ -280,14 +280,13 @@ class GraphZipLatestSpec extends StreamSpec with ScalaCheckPropertyChecks with S } yield (firstDigit, secondDigit) allNumbers.groupBy(_._1).toList.sortBy(_._1).foreach { - case (firstDigit, pairs) => { + case (firstDigit, pairs) => firstDigits.sendNext(firstDigit) pairs.map { case (_, digits) => digits }.foreach { secondDigit => secondDigits.sendNext(secondDigit) probe.request(1) probe.expectNext((firstDigit, secondDigit)) } - } } probe.cancel() diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/GraphZipLatestWithSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/GraphZipLatestWithSpec.scala index 6468d9f43ea..150fdc06180 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/GraphZipLatestWithSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/GraphZipLatestWithSpec.scala @@ -35,9 +35,8 @@ class GraphZipLatestWithSpec extends TwoStreamsSetup { override def out: Outlet[Int] = zip.out } - override def setup(p1: Publisher[Int], p2: Publisher[Int]) = { + override def setup(p1: Publisher[Int], p2: Publisher[Int]) = setup(p1, p2, eagerComplete = true) - } def setup(p1: Publisher[Int], p2: Publisher[Int], eagerComplete: Boolean) = { val subscriber = TestSubscriber.probe[Outputs]() diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/HubSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/HubSpec.scala index ce6c4495b2a..c9013087d64 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/HubSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/HubSpec.scala @@ -316,13 +316,11 @@ class HubSpec extends StreamSpec { val sourceQueue = Source.queue[Int](10) // used to block the source until we say so val (queue, broadcast) = sourceQueue.toMat(BroadcastHub.sink(2, 256))(Keep.both).run() val resultOne = broadcast.runWith(Sink.seq) // nothing happening yet - for (i <- 1 to 5) { + for (i <- 1 to 5) queue.offer(i) - } val resultTwo = broadcast.runWith(Sink.seq) - for (i <- 6 to 10) { + for (i <- 6 to 10) queue.offer(i) - } queue.complete() // only now is the source emptied Await.result(resultOne, 1.second) should be(1 to 10) @@ -591,7 +589,7 @@ class HubSpec extends StreamSpec { var sessions = Map.empty[String, Long] var n = 0L - (info, elem) => { + (info, elem) => sessions.get(elem) match { case Some(id) if info.consumerIds.exists(_ == id) => id case _ => @@ -600,7 +598,6 @@ class HubSpec extends StreamSpec { sessions = sessions.updated(elem, id) id } - } }, startAfterNrOfConsumers = 2, bufferSize = 8)) val result1 = source.runWith(Sink.seq) val result2 = source.runWith(Sink.seq) diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/JsonFramingSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/JsonFramingSpec.scala index 8150274f273..05af694fd23 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/JsonFramingSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/JsonFramingSpec.scala @@ -484,14 +484,14 @@ class JsonFramingSpec extends PekkoSpec { "fail if it's broken from the start" in { val buffer = new JsonObjectParser() buffer.offer(ByteString("""THIS IS NOT VALID { "name": "john"}""")) - a[FramingException] shouldBe thrownBy { buffer.poll() } + a[FramingException] shouldBe thrownBy(buffer.poll()) } "fail if it's broken at the end" in { val buffer = new JsonObjectParser() buffer.offer(ByteString("""{ "name": "john"} THIS IS NOT VALID""")) buffer.poll() // first emitting the valid element - a[FramingException] shouldBe thrownBy { buffer.poll() } + a[FramingException] shouldBe thrownBy(buffer.poll()) } } "maximumObjectLength is near Int.MaxValue" in { diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/LazyFlowSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/LazyFlowSpec.scala index 02f43339007..cf5e44e3198 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/LazyFlowSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/LazyFlowSpec.scala @@ -307,10 +307,10 @@ class LazyFlowSpec extends StreamSpec(""" p.success(Flow[Int]) flowProbe.request(99) flowProbe.expectNext(0) - (1 to 10).foreach(i => { + (1 to 10).foreach { i => sourceSub.sendNext(i) flowProbe.expectNext(i) - }) + } sourceSub.sendComplete() } diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/LazySinkSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/LazySinkSpec.scala index c79e6ff4f7d..697a86a1a0d 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/LazySinkSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/LazySinkSpec.scala @@ -64,16 +64,16 @@ class LazySinkSpec extends StreamSpec(""" sourceSub.sendNext(0) sourceSub.expectRequest(1) sourceProbe.expectNoMessage(200.millis) - a[TimeoutException] shouldBe thrownBy { Await.result(futureProbe, remainingOrDefault) } + a[TimeoutException] shouldBe thrownBy(Await.result(futureProbe, remainingOrDefault)) p.success(TestSink.probe[Int]) val probe = Await.result(futureProbe, remainingOrDefault).get probe.request(100) probe.expectNext(0) - (1 to 10).foreach(i => { + (1 to 10).foreach { i => sourceSub.sendNext(i) probe.expectNext(i) - }) + } sourceSub.sendComplete() } @@ -97,7 +97,7 @@ class LazySinkSpec extends StreamSpec(""" sourceSub.expectRequest(1) sourceSub.sendNext(0) sourceSub.expectCancellation() - a[RuntimeException] shouldBe thrownBy { Await.result(futureProbe, remainingOrDefault) } + a[RuntimeException] shouldBe thrownBy(Await.result(futureProbe, remainingOrDefault)) } "fail gracefully when upstream failed" in { @@ -121,7 +121,7 @@ class LazySinkSpec extends StreamSpec(""" val sourceSub = sourceProbe.expectSubscription() sourceSub.expectRequest(1) sourceSub.sendNext(0) - a[TE] shouldBe thrownBy { Await.result(futureProbe, remainingOrDefault) } + a[TE] shouldBe thrownBy(Await.result(futureProbe, remainingOrDefault)) } "cancel upstream when internal sink is cancelled" in { @@ -150,9 +150,9 @@ class LazySinkSpec extends StreamSpec(""" } } - val result = Source(List("whatever")).runWith(Sink.lazyInitAsync[String, NotUsed](() => { + val result = Source(List("whatever")).runWith(Sink.lazyInitAsync[String, NotUsed] { () => Future.successful(Sink.fromGraph(FailingInnerMat)) - })) + }) result.failed.futureValue should ===(matFail) } diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/LazySourceSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/LazySourceSpec.scala index 8a69f14d287..08216584bf8 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/LazySourceSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/LazySourceSpec.scala @@ -275,13 +275,13 @@ class LazySourceSpec extends StreamSpec with DefaultTimeout with ScalaFutures { "Source.lazyFutureSource" must { "work like a normal source, happy path" in { - val result = Source.lazyFutureSource(() => Future { Source(List(1, 2, 3)) }).runWith(Sink.seq) + val result = Source.lazyFutureSource(() => Future(Source(List(1, 2, 3)))).runWith(Sink.seq) result.futureValue should ===(Seq(1, 2, 3)) } "work like a normal source, happy path, already completed future" in { - val result = Source.lazyFutureSource(() => Future.successful { Source(List(1, 2, 3)) }).runWith(Sink.seq) + val result = Source.lazyFutureSource(() => Future.successful(Source(List(1, 2, 3)))).runWith(Sink.seq) result.futureValue should ===(Seq(1, 2, 3)) } @@ -306,7 +306,7 @@ class LazySourceSpec extends StreamSpec with DefaultTimeout with ScalaFutures { "fail the materialized value when downstream cancels without ever consuming any element" in { val lazyMatVal: Future[NotUsed] = - Source.lazyFutureSource(() => Future { Source(List(1, 2, 3)) }).toMat(Sink.cancelled)(Keep.left).run() + Source.lazyFutureSource(() => Future(Source(List(1, 2, 3)))).toMat(Sink.cancelled)(Keep.left).run() lazyMatVal.failed.futureValue shouldBe a[NeverMaterializedException] } @@ -315,7 +315,7 @@ class LazySourceSpec extends StreamSpec with DefaultTimeout with ScalaFutures { val outProbe = TestSubscriber.probe[Int]() val inProbe = TestPublisher.probe[Int]() - Source.lazyFutureSource(() => Future { Source.fromPublisher(inProbe) }).runWith(Sink.fromSubscriber(outProbe)) + Source.lazyFutureSource(() => Future(Source.fromPublisher(inProbe))).runWith(Sink.fromSubscriber(outProbe)) outProbe.request(1) inProbe.expectRequest() diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/QueueSinkSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/QueueSinkSpec.scala index 89c07f830d6..3e9ba9e977d 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/QueueSinkSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/QueueSinkSpec.scala @@ -52,7 +52,7 @@ class QueueSinkSpec extends StreamSpec { val sub = probe.expectSubscription() val future = queue.pull() val future2 = queue.pull() - an[IllegalStateException] shouldBe thrownBy { Await.result(future2, remainingOrDefault) } + an[IllegalStateException] shouldBe thrownBy(Await.result(future2, remainingOrDefault)) sub.sendNext(1) future.pipeTo(testActor) @@ -70,7 +70,7 @@ class QueueSinkSpec extends StreamSpec { val future1 = queue.pull() val future2 = queue.pull() val future3 = queue.pull() - an[IllegalStateException] shouldBe thrownBy { Await.result(future3, remainingOrDefault) } + an[IllegalStateException] shouldBe thrownBy(Await.result(future3, remainingOrDefault)) sub.sendNext(1) future1.pipeTo(testActor) diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/QueueSourceSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/QueueSourceSpec.scala index 77ee27a341a..1699b3ece4f 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/QueueSourceSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/QueueSourceSpec.scala @@ -42,9 +42,8 @@ class QueueSourceSpec extends StreamSpec { PatienceConfig(testKitSettings.DefaultTimeout.duration.dilated, Span(5, org.scalatest.time.Millis)) } - def assertSuccess(f: Future[QueueOfferResult]): Unit = { + def assertSuccess(f: Future[QueueOfferResult]): Unit = f.futureValue should ===(QueueOfferResult.Enqueued) - } "A QueueSource" must { diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/RestartSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/RestartSpec.scala index 6921d7d9f6c..6594f7acddb 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/RestartSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/RestartSpec.scala @@ -723,9 +723,9 @@ class RestartSpec case other => other } .watchTermination()((_, term) => - term.foreach(_ => { + term.foreach { _ => flowInProbe.ref ! "out complete" - }))) + })) })(Keep.left) .toMat(TestSink.probe[String])(Keep.both) .run() @@ -983,10 +983,10 @@ class RestartSpec val restartOnFailures = RestartFlow .onFailuresWithBackoff( - RestartSettings(1.second, 2.seconds, 0.2).withMaxRestarts(2, 1.second).withLogSettings(logSettings))(() => { + RestartSettings(1.second, 2.seconds, 0.2).withMaxRestarts(2, 1.second).withLogSettings(logSettings)) { () => flowCreations.incrementAndGet() failsSomeTimes - }) + } .addAttributes(Attributes(Delay(100.millis))) val elements = Source(1 to 7).via(restartOnFailures).runWith(Sink.seq).futureValue diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/RetryFlowSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/RetryFlowSpec.scala index adb86de4b6c..cc8386b9fc7 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/RetryFlowSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/RetryFlowSpec.scala @@ -49,12 +49,11 @@ class RetryFlowSpec extends StreamSpec(""" } /** increments the value and the context with every failure */ - def incrementFailedValues[OutData](in: (Int, Int), out: (Try[OutData], Int)): Option[(Int, Int)] = { + def incrementFailedValues[OutData](in: (Int, Int), out: (Try[OutData], Int)): Option[(Int, Int)] = (in, out) match { case ((in, _), (Failure(_), outCtx)) => Some((in + 1, outCtx + 1)) case _ => None } - } "RetryFlow.withBackoff" should { @@ -64,12 +63,11 @@ class RetryFlowSpec extends StreamSpec(""" case i => Success(i) } - def incrementFailedValues[OutData](in: Int, out: Try[OutData]): Option[Int] = { + def incrementFailedValues[OutData](in: Int, out: Try[OutData]): Option[Int] = (in, out) match { case (in, Failure(_)) => Some(in + 1) case _ => None } - } "send elements through" in { val sink = diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/SinkForeachAsyncSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/SinkForeachAsyncSpec.scala index dcb2e62b822..982dc94df75 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/SinkForeachAsyncSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/SinkForeachAsyncSpec.scala @@ -48,14 +48,13 @@ class SinkForeachAsyncSpec extends StreamSpec { val probe = TestProbe() val latch = (1 to 4).map(_ -> TestLatch(1)).toMap - val sink: Sink[Int, Future[Done]] = { + val sink: Sink[Int, Future[Done]] = Sink.foreachAsync(4) { (n: Int) => Future { Await.result(latch(n), remainingOrDefault) probe.ref ! n } } - } val p = Source(1 to 4).runWith(sink) @@ -80,7 +79,7 @@ class SinkForeachAsyncSpec extends StreamSpec { val probe = TestProbe() val latch = (1 to 4).map(_ -> TestLatch(1)).toMap - val sink: Sink[() => Int, Future[Done]] = { + val sink: Sink[() => Int, Future[Done]] = Sink.foreachAsync(1) { (n: () => Int) => Future { Await.result(latch(n()), remainingOrDefault) @@ -88,7 +87,6 @@ class SinkForeachAsyncSpec extends StreamSpec { Thread.sleep(2000) } } - } @volatile var oneCalled = false @volatile var twoCalled = false @@ -156,12 +154,12 @@ class SinkForeachAsyncSpec extends StreamSpec { val probe = TestProbe() val latch = (1 to 4).map(_ -> TestLatch(1)).toMap - val p = Source(1 to 4).runWith(Sink.foreachAsync(4)((n: Int) => { + val p = Source(1 to 4).runWith(Sink.foreachAsync(4) { (n: Int) => Future { Await.ready(latch(n), 5.seconds) probe.ref ! n } - })) + }) latch(2).countDown() probe.expectMsg(2) latch(4).countDown() @@ -184,12 +182,12 @@ class SinkForeachAsyncSpec extends StreamSpec { val probe = TestProbe() val latch = (1 to 5).map(_ -> TestLatch()).toMap - val p = Source(1 to 5).runWith(Sink.foreachAsync(4)((n: Int) => { + val p = Source(1 to 5).runWith(Sink.foreachAsync(4) { (n: Int) => Future { probe.ref ! n Await.ready(latch(n), 5.seconds) } - })) + }) probe.expectMsgAllOf(1, 2, 3, 4) probe.expectNoMessage(200.millis) @@ -213,7 +211,7 @@ class SinkForeachAsyncSpec extends StreamSpec { val p = Source(1 to 5).runWith( Sink - .foreachAsync(4)((n: Int) => { + .foreachAsync(4) { (n: Int) => Future { if (n == 3) throw new RuntimeException("err1") with NoStackTrace else { @@ -221,7 +219,7 @@ class SinkForeachAsyncSpec extends StreamSpec { Await.ready(latch, 10.seconds) } } - }) + } .withAttributes(supervisionStrategy(resumingDecider))) latch.countDown() @@ -241,7 +239,7 @@ class SinkForeachAsyncSpec extends StreamSpec { .fromIterator(() => Iterator.from(1)) .runWith( Sink - .foreachAsync(3)((n: Int) => { + .foreachAsync(3) { (n: Int) => Future { if (n == 3) { // Error will happen only after elements 1, 2 has been processed @@ -253,7 +251,7 @@ class SinkForeachAsyncSpec extends StreamSpec { await(element4Latch) // Block element 4, 5, 6, ... from entering } } - }) + } .withAttributes(supervisionStrategy(stoppingDecider))) // Only the first two messages are guaranteed to arrive due to their enforced ordering related to the time diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/SinkForeachParallelSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/SinkForeachParallelSpec.scala index 4f1310b3ff7..b64ab5506e9 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/SinkForeachParallelSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/SinkForeachParallelSpec.scala @@ -37,10 +37,10 @@ class SinkForeachParallelSpec extends StreamSpec { val probe = TestProbe() val latch = (1 to 4).map(_ -> TestLatch(1)).toMap - val p = Source(1 to 4).runWith(Sink.foreachParallel(4)((n: Int) => { + val p = Source(1 to 4).runWith(Sink.foreachParallel(4) { (n: Int) => Await.ready(latch(n), 5.seconds) probe.ref ! n - })) + }) latch(2).countDown() probe.expectMsg(2) latch(4).countDown() @@ -63,10 +63,10 @@ class SinkForeachParallelSpec extends StreamSpec { val probe = TestProbe() val latch = (1 to 5).map(_ -> TestLatch()).toMap - val p = Source(1 to 5).runWith(Sink.foreachParallel(4)((n: Int) => { + val p = Source(1 to 5).runWith(Sink.foreachParallel(4) { (n: Int) => probe.ref ! n Await.ready(latch(n), 5.seconds) - })) + }) probe.expectMsgAllOf(1, 2, 3, 4) probe.expectNoMessage(200.millis) @@ -90,13 +90,13 @@ class SinkForeachParallelSpec extends StreamSpec { val p = Source(1 to 5).runWith( Sink - .foreachParallel(4)((n: Int) => { + .foreachParallel(4) { (n: Int) => if (n == 3) throw new RuntimeException("err1") with NoStackTrace else { probe.ref ! n Await.ready(latch, 10.seconds) } - }) + } .withAttributes(supervisionStrategy(resumingDecider))) latch.countDown() @@ -116,7 +116,7 @@ class SinkForeachParallelSpec extends StreamSpec { .fromIterator(() => Iterator.from(1)) .runWith( Sink - .foreachParallel(3)((n: Int) => { + .foreachParallel(3) { (n: Int) => if (n == 3) { // Error will happen only after elements 1, 2 has been processed errorLatch.await(5, TimeUnit.SECONDS) @@ -126,7 +126,7 @@ class SinkForeachParallelSpec extends StreamSpec { errorLatch.countDown() element4Latch.await(5, TimeUnit.SECONDS) // Block element 4, 5, 6, ... from entering } - }) + } .withAttributes(supervisionStrategy(stoppingDecider))) // Only the first two messages are guaranteed to arrive due to their enforced ordering related to the time diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/SinkSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/SinkSpec.scala index 8368d7a96c5..0883e417e42 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/SinkSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/SinkSpec.scala @@ -157,13 +157,14 @@ class SinkSpec extends StreamSpec with DefaultTimeout with ScalaFutures { "combine two sinks with combineMat" in { implicit val ex = org.apache.pekko.dispatch.ExecutionContexts.parasitic Source(List(0, 1, 2, 3, 4, 5)) - .toMat(Sink.combineMat(Sink.reduce[Int]((a, b) => a + b), Sink.reduce[Int]((a, b) => a + b))(Broadcast[Int](_))( - (f1, f2) => { + .toMat(Sink.combineMat(Sink.reduce[Int]((a, b) => a + b), Sink.reduce[Int]((a, b) => a + b))( + Broadcast[Int](_)) { + (f1, f2) => for { r1 <- f1 r2 <- f2 } yield r1 + r2 - }))(Keep.right) + })(Keep.right) .run() .futureValue should be(30) } @@ -367,12 +368,12 @@ class SinkSpec extends StreamSpec with DefaultTimeout with ScalaFutures { } "completes with `true` with restart strategy" in { - val sink = Sink.forall[Int](elem => { + val sink = Sink.forall[Int] { elem => if (elem == 2) { throw new RuntimeException("Oops") } elem > 0 - }).withAttributes(supervisionStrategy(Supervision.restartingDecider)) + }.withAttributes(supervisionStrategy(Supervision.restartingDecider)) Source(1 to 2) .runWith(sink) @@ -408,12 +409,12 @@ class SinkSpec extends StreamSpec with DefaultTimeout with ScalaFutures { } "completes with `exists` with restart strategy" in { - val sink = Sink.exists[Int](elem => { + val sink = Sink.exists[Int] { elem => if (elem == 2) { throw new RuntimeException("Oops") } elem > 1 - }).withAttributes(supervisionStrategy(Supervision.restartingDecider)) + }.withAttributes(supervisionStrategy(Supervision.restartingDecider)) Source(1 to 2) .runWith(sink) diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/SourceSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/SourceSpec.scala index a54a17a4c7f..9e35bf629f4 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/SourceSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/SourceSpec.scala @@ -450,7 +450,7 @@ class SourceSpec extends StreamSpec with DefaultTimeout { Source.optionalVia( Source(data), - Flow.fromFunction { (string: String) => string.toInt } + Flow.fromFunction((string: String) => string.toInt) )(Keep.none) .runWith(TestSink.probe[Option[Int]]) .request(4) diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/SourceWithContextSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/SourceWithContextSpec.scala index 06650a7b774..da468067da9 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/SourceWithContextSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/SourceWithContextSpec.scala @@ -230,7 +230,7 @@ class SourceWithContextSpec extends StreamSpec { SourceWithContext .fromTuples(Source(data)) - .unsafeDataVia(Flow.fromFunction[String, Int] { _.toInt }) + .unsafeDataVia(Flow.fromFunction[String, Int](_.toInt)) .runWith(TestSink.probe[(Int, Int)]) .request(4) .expectNext((1, 1), (2, 2), (3, 3), (4, 4)) @@ -244,7 +244,7 @@ class SourceWithContextSpec extends StreamSpec { SourceWithContext.unsafeOptionalDataVia( source, - Flow.fromFunction { (string: String) => string.toInt } + Flow.fromFunction((string: String) => string.toInt) )(Keep.none) .runWith(TestSink.probe[(Option[Int], Int)]) .request(4) diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/StageActorRefSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/StageActorRefSpec.scala index 4f35a4ec3e6..9c8162090bc 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/StageActorRefSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/StageActorRefSpec.scala @@ -214,7 +214,7 @@ object StageActorRefSpec { probe ! getStageActor(behavior).ref } - def behavior(m: (ActorRef, Any)): Unit = { + def behavior(m: (ActorRef, Any)): Unit = m match { case (_, Add(n)) => sum += n case (_, PullNow) => pull(in) @@ -231,7 +231,6 @@ object StageActorRefSpec { sender ! sum case _ => throw new RuntimeException("unexpected: " + m) } - } setHandler( in, diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/StreamRefsSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/StreamRefsSpec.scala index da6f2e9f51c..dd28eaf20f7 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/StreamRefsSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/StreamRefsSpec.scala @@ -177,7 +177,7 @@ object StreamRefsSpec { final case class SinkMsg(dataSink: SinkRef[String]) final case class BulkSinkMsg(dataSink: SinkRef[ByteString]) - def config(): Config = { + def config(): Config = ConfigFactory.parseString(s""" pekko { loglevel = DEBUG @@ -194,7 +194,6 @@ object StreamRefsSpec { } } """).withFallback(ConfigFactory.load()) - } object SnitchActor { def props(probe: ActorRef) = Props(new SnitchActor(probe)) diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/UnfoldResourceAsyncSourceSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/UnfoldResourceAsyncSourceSpec.scala index ac261e039ce..d29040d12c8 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/UnfoldResourceAsyncSourceSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/UnfoldResourceAsyncSourceSpec.scala @@ -380,15 +380,13 @@ class UnfoldResourceAsyncSourceSpec extends StreamSpec(UnboundedMailboxConfig) { "close resource when stream is quickly cancelled reproducer 2" in { val closed = Promise[Done]() Source - .unfoldResourceAsync[String, Iterator[String]]({ () => - Future(Iterator("a", "b", "c")) - }, - { m => - Future(if (m.hasNext) Some(m.next()) else None) - }, - { _ => + .unfoldResourceAsync[String, Iterator[String]](() => + Future(Iterator("a", "b", "c")), + m => + Future(if (m.hasNext) Some(m.next()) else None), + _ => closed.success(Done).future - }) + ) .map(m => println(s"Elem=> $m")) .runWith(Sink.cancelled) diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/UnfoldResourceSourceSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/UnfoldResourceSourceSpec.scala index 6b4fac48cce..a60e9e36827 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/UnfoldResourceSourceSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/UnfoldResourceSourceSpec.scala @@ -42,14 +42,13 @@ class UnfoldResourceSourceSpec extends StreamSpec(UnboundedMailboxConfig) { private val fs = Jimfs.newFileSystem("UnfoldResourceSourceSpec", Configuration.unix()) - private val manyLines = { + private val manyLines = ("a" * 100 + "\n") * 10 + ("b" * 100 + "\n") * 10 + ("c" * 100 + "\n") * 10 + ("d" * 100 + "\n") * 10 + ("e" * 100 + "\n") * 10 + ("f" * 100 + "\n") * 10 - } private val manyLinesArray = manyLines.split("\n") private val manyLinesPath = { @@ -101,10 +100,10 @@ class UnfoldResourceSourceSpec extends StreamSpec(UnboundedMailboxConfig) { p.subscribe(c) val sub = c.expectSubscription() - (0 to 49).foreach(i => { + (0 to 49).foreach { i => sub.request(1) c.expectNext() should ===(if (i < 10) manyLinesArray(i) else manyLinesArray(i + 10)) - }) + } sub.request(1) c.expectComplete() } @@ -123,10 +122,10 @@ class UnfoldResourceSourceSpec extends StreamSpec(UnboundedMailboxConfig) { p.subscribe(c) val sub = c.expectSubscription() - (0 to 19).foreach(_ => { + (0 to 19).foreach { _ => sub.request(1) c.expectNext() should ===(manyLinesArray(0)) - }) + } sub.cancel() } @@ -152,10 +151,10 @@ class UnfoldResourceSourceSpec extends StreamSpec(UnboundedMailboxConfig) { p.subscribe(c) val sub = c.expectSubscription() - (0 to 121).foreach(_ => { + (0 to 121).foreach { _ => sub.request(1) c.expectNext().utf8String should ===(nextChunk().toString) - }) + } sub.request(1) c.expectComplete() } @@ -246,7 +245,6 @@ class UnfoldResourceSourceSpec extends StreamSpec(UnboundedMailboxConfig) { } } - override def afterTermination(): Unit = { + override def afterTermination(): Unit = fs.close() - } } diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/WithContextUsageSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/WithContextUsageSpec.scala index 3a40186bc00..62af046086a 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/WithContextUsageSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/scaladsl/WithContextUsageSpec.scala @@ -184,13 +184,12 @@ class WithContextUsageSpec extends StreamSpec { def commit[Ctx](uninitialized: Ctx): Sink[Ctx, Probe[Ctx]] = { val testSink = TestSink.probe[Ctx] Flow[Ctx] - .statefulMap(() => uninitialized)((prevCtx, ctx) => { + .statefulMap(() => uninitialized)((prevCtx, ctx) => if (prevCtx != uninitialized && ctx != prevCtx) { (ctx, Some(prevCtx)) } else { (ctx, None) - } - }, _ => None) + }, _ => None) .collect { case Some(ctx) => ctx } .toMat(testSink)(Keep.right) } @@ -209,9 +208,8 @@ case class MultiRecord(records: immutable.Seq[Record]) object Consumer { def committableSource( - committableMessages: Vector[CommittableMessage[Record]]): Source[CommittableMessage[Record], NotUsed] = { + committableMessages: Vector[CommittableMessage[Record]]): Source[CommittableMessage[Record], NotUsed] = Source(committableMessages) - } case class CommittableMessage[V](record: V, committableOffset: CommittableOffset) trait Committable { diff --git a/stream-tests/src/test/scala/org/apache/pekko/stream/snapshot/MaterializerStateSpec.scala b/stream-tests/src/test/scala/org/apache/pekko/stream/snapshot/MaterializerStateSpec.scala index f3b5f1362d8..84149006de0 100644 --- a/stream-tests/src/test/scala/org/apache/pekko/stream/snapshot/MaterializerStateSpec.scala +++ b/stream-tests/src/test/scala/org/apache/pekko/stream/snapshot/MaterializerStateSpec.scala @@ -40,9 +40,8 @@ class MaterializerStateSpec extends PekkoSpec() { snapshot.head.activeInterpreters should have size 1 snapshot.head.activeInterpreters.head.logics should have size 4 // all 4 operators }, remainingOrDefault) - } finally { + } finally mat.shutdown() - } } "snapshot a running stream on the default dispatcher" in { @@ -90,9 +89,8 @@ class MaterializerStateSpec extends PekkoSpec() { snapshot.head.activeInterpreters.head.stoppedLogics should have size 2 // Source.single and a detach }, remainingOrDefault) - } finally { + } finally mat.shutdown() - } } "snapshot a more complicated graph" in { @@ -134,9 +132,8 @@ class MaterializerStateSpec extends PekkoSpec() { Thread.sleep(100) // just to give it a bigger chance to cover different states of shutting down MaterializerState.streamSnapshots(mat).futureValue - } finally { + } finally mat.shutdown() - } } } diff --git a/stream-typed-tests/src/test/scala/org/apache/pekko/stream/MapAsyncPartitionedSpec.scala b/stream-typed-tests/src/test/scala/org/apache/pekko/stream/MapAsyncPartitionedSpec.scala index 0b5a01a20ba..36b624d9283 100644 --- a/stream-typed-tests/src/test/scala/org/apache/pekko/stream/MapAsyncPartitionedSpec.scala +++ b/stream-typed-tests/src/test/scala/org/apache/pekko/stream/MapAsyncPartitionedSpec.scala @@ -50,18 +50,14 @@ private object MapAsyncPartitionedSpec { for { totalElements <- Gen.choose(1, 100) totalPartitions <- Gen.choose(1, 8) - } yield { - generateElements(totalPartitions, totalElements) - } + } yield generateElements(totalPartitions, totalElements) } def generateElements(totalPartitions: Int, totalElements: Int): Seq[TestKeyValue] = - for (i <- 1 to totalElements) yield { - TestKeyValue( - key = Random.nextInt(totalPartitions), - delay = DurationInt(Random.nextInt(20) + 10).millis, - value = i.toString) - } + for (i <- 1 to totalElements) yield TestKeyValue( + key = Random.nextInt(totalPartitions), + delay = DurationInt(Random.nextInt(20) + 10).millis, + value = i.toString) val partitioner: TestKeyValue => Int = kv => kv.key diff --git a/stream-typed/src/main/scala/org/apache/pekko/stream/typed/javadsl/ActorFlow.scala b/stream-typed/src/main/scala/org/apache/pekko/stream/typed/javadsl/ActorFlow.scala index e683830b0bd..02a7b317528 100644 --- a/stream-typed/src/main/scala/org/apache/pekko/stream/typed/javadsl/ActorFlow.scala +++ b/stream-typed/src/main/scala/org/apache/pekko/stream/typed/javadsl/ActorFlow.scala @@ -187,7 +187,7 @@ object ActorFlow { parallelism: Int, ref: ActorRef[Q], timeout: java.time.Duration, - makeMessage: BiFunction[I, ActorRef[A], Q]): Flow[Pair[I, Ctx], Pair[A, Ctx], NotUsed] = { + makeMessage: BiFunction[I, ActorRef[A], Q]): Flow[Pair[I, Ctx], Pair[A, Ctx], NotUsed] = org.apache.pekko.stream.scaladsl .Flow[Pair[I, Ctx]] .map(_.toScala) @@ -197,5 +197,4 @@ object ActorFlow { JavaDurationConverters.asFiniteDuration(timeout)) .map { case (a, ctx) => Pair(a, ctx) }) .asJava - } } diff --git a/stream-typed/src/main/scala/org/apache/pekko/stream/typed/javadsl/ActorSource.scala b/stream-typed/src/main/scala/org/apache/pekko/stream/typed/javadsl/ActorSource.scala index 0bb36679313..9efa7211855 100644 --- a/stream-typed/src/main/scala/org/apache/pekko/stream/typed/javadsl/ActorSource.scala +++ b/stream-typed/src/main/scala/org/apache/pekko/stream/typed/javadsl/ActorSource.scala @@ -61,7 +61,7 @@ object ActorSource { completionMatcher: Predicate[T], failureMatcher: pekko.japi.function.Function[T, java.util.Optional[Throwable]], bufferSize: Int, - overflowStrategy: OverflowStrategy): Source[T, ActorRef[T]] = { + overflowStrategy: OverflowStrategy): Source[T, ActorRef[T]] = pekko.stream.typed.scaladsl.ActorSource .actorRef( { case m if completionMatcher.test(m) => }: PartialFunction[T, Unit], @@ -75,7 +75,6 @@ object ActorSource { bufferSize, overflowStrategy) .asJava - } /** * Creates a `Source` that is materialized as an [[pekko.actor.ActorRef]]. diff --git a/stream-typed/src/main/scala/org/apache/pekko/stream/typed/scaladsl/ActorFlow.scala b/stream-typed/src/main/scala/org/apache/pekko/stream/typed/scaladsl/ActorFlow.scala index 1d4ddb99064..a204b437507 100644 --- a/stream-typed/src/main/scala/org/apache/pekko/stream/typed/scaladsl/ActorFlow.scala +++ b/stream-typed/src/main/scala/org/apache/pekko/stream/typed/scaladsl/ActorFlow.scala @@ -157,15 +157,13 @@ object ActorFlow { * failed. */ def askWithStatus[I, Q, A](parallelism: Int)(ref: ActorRef[Q])(makeMessage: (I, ActorRef[StatusReply[A]]) => Q)( - implicit timeout: Timeout): Flow[I, A, NotUsed] = { + implicit timeout: Timeout): Flow[I, A, NotUsed] = ActorFlow.ask(parallelism)(ref)(makeMessage).map { case StatusReply.Success(a) => a.asInstanceOf[A] case StatusReply.Error(err) => throw err case _ => throw new RuntimeException() // compiler exhaustiveness check pleaser } - } - /** * Use the `ask` pattern to send a request-reply message to the target `ref` actor without including the context. */ @@ -199,7 +197,7 @@ object ActorFlow { * failed. */ def askWithStatusAndContext[I, Q, A, Ctx](parallelism: Int)(ref: ActorRef[Q])( - makeMessage: (I, ActorRef[StatusReply[A]]) => Q)(implicit timeout: Timeout): Flow[(I, Ctx), (A, Ctx), NotUsed] = { + makeMessage: (I, ActorRef[StatusReply[A]]) => Q)(implicit timeout: Timeout): Flow[(I, Ctx), (A, Ctx), NotUsed] = askImpl[(I, Ctx), Q, StatusReply[A], (StatusReply[A], Ctx)](parallelism)(ref)( (in, r) => makeMessage(in._1, r), (in, o: Future[StatusReply[A]]) => o.map(a => a -> in._2)(ExecutionContexts.parasitic)).map { @@ -208,6 +206,4 @@ object ActorFlow { case _ => throw new RuntimeException() // compiler exhaustiveness check pleaser } - } - } diff --git a/stream-typed/src/main/scala/org/apache/pekko/stream/typed/scaladsl/PubSub.scala b/stream-typed/src/main/scala/org/apache/pekko/stream/typed/scaladsl/PubSub.scala index a009afaca81..149c52f9609 100644 --- a/stream-typed/src/main/scala/org/apache/pekko/stream/typed/scaladsl/PubSub.scala +++ b/stream-typed/src/main/scala/org/apache/pekko/stream/typed/scaladsl/PubSub.scala @@ -64,11 +64,10 @@ object PubSub { * @tparam T the type of the messages that can be published */ @ApiMayChange - def sink[T](topicActor: ActorRef[Topic.Command[T]]): Sink[T, NotUsed] = { + def sink[T](topicActor: ActorRef[Topic.Command[T]]): Sink[T, NotUsed] = Sink .foreach[T] { message => topicActor ! Topic.Publish(message) } .mapMaterializedValue(_ => NotUsed) - } } diff --git a/stream/src/main/scala-jdk-9/org/apache/pekko/stream/scaladsl/JavaFlowSupport.scala b/stream/src/main/scala-jdk-9/org/apache/pekko/stream/scaladsl/JavaFlowSupport.scala index 969c1d2c2a8..a33b5de1d64 100644 --- a/stream/src/main/scala-jdk-9/org/apache/pekko/stream/scaladsl/JavaFlowSupport.scala +++ b/stream/src/main/scala-jdk-9/org/apache/pekko/stream/scaladsl/JavaFlowSupport.scala @@ -74,9 +74,8 @@ object JavaFlowSupport { /** * Creates a Flow from a Reactive Streams [[org.reactivestreams.Processor]] */ - def fromProcessor[I, O](processorFactory: () => juc.Flow.Processor[I, O]): Flow[I, O, NotUsed] = { + def fromProcessor[I, O](processorFactory: () => juc.Flow.Processor[I, O]): Flow[I, O, NotUsed] = fromProcessorMat(() => (processorFactory(), NotUsed)) - } /** * Creates a Flow from a Reactive Streams [[java.util.concurrent.Flow.Processor]] and returns a materialized value. diff --git a/stream/src/main/scala/com/typesafe/sslconfig/pekko/PekkoSSLConfig.scala b/stream/src/main/scala/com/typesafe/sslconfig/pekko/PekkoSSLConfig.scala index 338d206cfc9..147c68753be 100644 --- a/stream/src/main/scala/com/typesafe/sslconfig/pekko/PekkoSSLConfig.scala +++ b/stream/src/main/scala/com/typesafe/sslconfig/pekko/PekkoSSLConfig.scala @@ -150,10 +150,9 @@ final class PekkoSSLConfig(system: ExtendedActorSystem, val config: SSLConfigSet @deprecated("validateDefaultTrustManager is not doing anything since akka 2.6.19 and should not be used", "Akka 2.6.19") - def validateDefaultTrustManager(@nowarn("msg=never used") sslConfig: SSLConfigSettings): Unit = { + def validateDefaultTrustManager(@nowarn("msg=never used") sslConfig: SSLConfigSettings): Unit = log.warning( "validateDefaultTrustManager is not doing anything since akka 2.6.19, it was useful only in Java 7 and below"); - } def configureProtocols(existingProtocols: Array[String], sslConfig: SSLConfigSettings): Array[String] = { val definedProtocols = sslConfig.enabledProtocols match { diff --git a/stream/src/main/scala/org/apache/pekko/stream/ActorMaterializer.scala b/stream/src/main/scala/org/apache/pekko/stream/ActorMaterializer.scala index 02f6ff4751b..d42495adc37 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/ActorMaterializer.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/ActorMaterializer.scala @@ -78,8 +78,7 @@ object ActorMaterializer { "Use the system wide materializer with stream attributes or configuration settings to change defaults", "Akka 2.6.0") def apply(materializerSettings: ActorMaterializerSettings, namePrefix: String)( - implicit context: ActorRefFactory): ActorMaterializer = { - + implicit context: ActorRefFactory): ActorMaterializer = context match { case system: ActorSystem => // system level materializer, defer to the system materializer extension @@ -94,7 +93,6 @@ object ActorMaterializer { case other => throw new IllegalArgumentException(s"Unexpected type of context: $other") } - } /** * Scala API: Creates an ActorMaterializer that can materialize stream blueprints as running streams. @@ -588,7 +586,7 @@ final class ActorMaterializerSettings @InternalApi private ( syncProcessingLimit: Int = this.syncProcessingLimit, ioSettings: IOSettings = this.ioSettings, streamRefSettings: StreamRefSettings = this.streamRefSettings, - blockingIoDispatcher: String = this.blockingIoDispatcher) = { + blockingIoDispatcher: String = this.blockingIoDispatcher) = new ActorMaterializerSettings( initialInputBufferSize, maxInputBufferSize, @@ -604,7 +602,6 @@ final class ActorMaterializerSettings @InternalApi private ( ioSettings, streamRefSettings, blockingIoDispatcher) - } /** * Each asynchronous piece of a materialized stream topology is executed by one Actor @@ -617,10 +614,9 @@ final class ActorMaterializerSettings @InternalApi private ( * document and or fix if it should not be like that. Search for get[Attributes.InputBuffer] to see how it is used */ @deprecated("Use attribute 'Attributes.InputBuffer' to change setting value", "Akka 2.6.0") - def withInputBuffer(initialSize: Int, maxSize: Int): ActorMaterializerSettings = { + def withInputBuffer(initialSize: Int, maxSize: Int): ActorMaterializerSettings = if (initialSize == this.initialInputBufferSize && maxSize == this.maxInputBufferSize) this else copy(initialInputBufferSize = initialSize, maxInputBufferSize = maxSize) - } /** * This setting configures the default dispatcher to be used by streams materialized @@ -628,10 +624,9 @@ final class ActorMaterializerSettings @InternalApi private ( * stream topology by using [[pekko.stream.Attributes#dispatcher]]. */ @deprecated("Use attribute 'ActorAttributes.Dispatcher' to change setting value", "Akka 2.6.0") - def withDispatcher(dispatcher: String): ActorMaterializerSettings = { + def withDispatcher(dispatcher: String): ActorMaterializerSettings = if (this.dispatcher == dispatcher) this else copy(dispatcher = dispatcher) - } /** * Scala API: Decides how exceptions from application code are to be handled, unless @@ -642,10 +637,9 @@ final class ActorMaterializerSettings @InternalApi private ( * by every operator. */ @deprecated("Use attribute 'ActorAttributes.supervisionStrategy' to change setting value", "Akka 2.6.0") - def withSupervisionStrategy(decider: Supervision.Decider): ActorMaterializerSettings = { + def withSupervisionStrategy(decider: Supervision.Decider): ActorMaterializerSettings = if (decider eq this.supervisionDecider) this else copy(supervisionDecider = decider) - } /** * Java API: Decides how exceptions from application code are to be handled, unless diff --git a/stream/src/main/scala/org/apache/pekko/stream/Attributes.scala b/stream/src/main/scala/org/apache/pekko/stream/Attributes.scala index a547de5ab84..715747a86bf 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/Attributes.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/Attributes.scala @@ -55,13 +55,12 @@ final case class Attributes(attributeList: List[Attributes.Attribute] = Nil) { * as it will then always return true because of the defaults from the ActorMaterializerSettings * INTERNAL API */ - private[stream] def isAsync: Boolean = { + private[stream] def isAsync: Boolean = attributeList.nonEmpty && attributeList.exists { case AsyncBoundary => true case ActorAttributes.Dispatcher(_) => true case _ => false } - } /** * Java API: Get the most specific attribute value for a given Attribute type or subclass thereof. @@ -150,12 +149,11 @@ final case class Attributes(attributeList: List[Attributes.Attribute] = Nil) { * Adds given attributes. Added attributes are considered more specific than * already existing attributes of the same type. */ - def and(other: Attributes): Attributes = { + def and(other: Attributes): Attributes = if (attributeList.isEmpty) other else if (other.attributeList.isEmpty) this else if (other.attributeList.tail.isEmpty) Attributes(other.attributeList.head :: attributeList) else Attributes(other.attributeList ::: attributeList) - } /** * Adds given attribute. Added attribute is considered more specific than @@ -197,13 +195,11 @@ final case class Attributes(attributeList: List[Attributes.Attribute] = Nil) { find(attributeList) } - @InternalApi def nameOrDefault(default: String = "unnamed"): String = { + @InternalApi def nameOrDefault(default: String = "unnamed"): String = getName().getOrElse(default) - } - @InternalApi private[pekko] def nameForActorRef(default: String = "unnamed"): String = { + @InternalApi private[pekko] def nameForActorRef(default: String = "unnamed"): String = getName().map(name => URLEncoder.encode(name, ByteString.UTF_8)).getOrElse(default) - } /** * Test whether the given attribute is contained within this attributes list. @@ -282,12 +278,11 @@ final case class Attributes(attributeList: List[Attributes.Attribute] = Nil) { * If no such attribute exists the `default` value is returned. */ @deprecated("Attributes should always be most specific, use get[T]", "Akka 2.5.7") - def getFirst[T <: Attribute: ClassTag](default: T): T = { + def getFirst[T <: Attribute: ClassTag](default: T): T = getFirst[T] match { case Some(a) => a case None => default } - } /** * Scala API: Get the least specific attribute (added first) of a given type parameter T `Class` or subclass thereof. @@ -720,9 +715,8 @@ object Attributes { * Compute a name by concatenating all Name attributes that the given module * has, returning the given default value if none are found. */ - def extractName(builder: TraversalBuilder, default: String): String = { + def extractName(builder: TraversalBuilder, default: String): String = builder.attributes.nameOrDefault(default) - } } /** diff --git a/stream/src/main/scala/org/apache/pekko/stream/KillSwitch.scala b/stream/src/main/scala/org/apache/pekko/stream/KillSwitch.scala index 2d7f8a19c3d..cacd8981621 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/KillSwitch.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/KillSwitch.scala @@ -64,7 +64,7 @@ object KillSwitches { abstract class KillableGraphStageLogic(val terminationSignal: Future[Done], _shape: Shape) extends GraphStageLogic(_shape) { - override def preStart(): Unit = { + override def preStart(): Unit = terminationSignal.value match { case Some(status) => onSwitch(status) case _ => @@ -72,7 +72,6 @@ object KillSwitches { terminationSignal.onComplete(getAsyncCallback[Try[Done]](onSwitch).invoke)( pekko.dispatch.ExecutionContexts.parasitic) } - } private def onSwitch(mode: Try[Done]): Unit = mode match { case Success(_) => completeStage() @@ -174,11 +173,10 @@ private[stream] final class TerminationSignal { private[this] val _listeners = TrieMap.empty[Listener, NotUsed] private[this] val _completedWith: AtomicReference[Option[Try[Done]]] = new AtomicReference(None) - def tryComplete(result: Try[Done]): Unit = { + def tryComplete(result: Try[Done]): Unit = if (_completedWith.compareAndSet(None, Some(result))) { for ((listener, _) <- _listeners) listener.promise.tryComplete(result) } - } def createListener(): Listener = { val listener = new Listener @@ -192,9 +190,8 @@ private[stream] final class TerminationSignal { listener } - private def removeListener(listener: Listener): Unit = { + private def removeListener(listener: Listener): Unit = _listeners -= listener - } } /** diff --git a/stream/src/main/scala/org/apache/pekko/stream/MapAsyncPartitioned.scala b/stream/src/main/scala/org/apache/pekko/stream/MapAsyncPartitioned.scala index 6bdbccbf8ff..1630df40726 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/MapAsyncPartitioned.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/MapAsyncPartitioned.scala @@ -40,7 +40,7 @@ private[stream] object MapAsyncPartitioned { Try[Out] => Unit) { private var cachedSupervisionDirective: OptionVal[Supervision.Directive] = OptionVal.None - def supervisionDirectiveFor(decider: Supervision.Decider, ex: Throwable): Supervision.Directive = { + def supervisionDirectiveFor(decider: Supervision.Decider, ex: Throwable): Supervision.Directive = cachedSupervisionDirective match { case OptionVal.Some(d) => d case _ => @@ -48,7 +48,6 @@ private[stream] object MapAsyncPartitioned { cachedSupervisionDirective = OptionVal.Some(d) d } - } def setOut(t: Try[Out]): Unit = out = t @@ -250,7 +249,7 @@ private[stream] final class MapAsyncPartitioned[In, Out, Partition]( drainQueue() } - private def drainQueue(): Unit = { + private def drainQueue(): Unit = if (buffer.nonEmpty) { buffer.foreach { case (partition, wrappedInput) => @@ -260,7 +259,6 @@ private[stream] final class MapAsyncPartitioned[In, Out, Partition]( } } } - } private def pullIfNeeded(): Unit = if (isClosed(in) && idle()) completeStage() diff --git a/stream/src/main/scala/org/apache/pekko/stream/Shape.scala b/stream/src/main/scala/org/apache/pekko/stream/Shape.scala index ea63c08cb1e..72a8fce6994 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/Shape.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/Shape.scala @@ -166,12 +166,11 @@ final class Outlet[T] private (val s: String) extends OutPort { * `inlets` and `outlets` can be `Vector` or `List` so this method * checks the size of 1 in an optimized way. */ - def hasOnePort(ports: immutable.Seq[_]): Boolean = { + def hasOnePort(ports: immutable.Seq[_]): Boolean = ports.nonEmpty && (ports match { case l: List[_] => l.tail.isEmpty // assuming List is most common case _ => ports.size == 1 // e.g. Vector }) - } } /** diff --git a/stream/src/main/scala/org/apache/pekko/stream/StreamRefSettings.scala b/stream/src/main/scala/org/apache/pekko/stream/StreamRefSettings.scala index 8c9356eecba..a7e0f448da3 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/StreamRefSettings.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/StreamRefSettings.scala @@ -38,9 +38,8 @@ object StreamRefSettings { @deprecated( "Use attributes on the Runnable graph or change the defaults in configuration, see migration guide for details https://doc.akka.io/docs/akka/2.6/project/migration-guide-2.5.x-2.6.x.html", since = "Akka 2.6.0") - def apply(system: ActorSystem): StreamRefSettings = { + def apply(system: ActorSystem): StreamRefSettings = apply(system.settings.config.getConfig("pekko.stream.materializer.stream-ref")) - } /** Java API */ @deprecated( @@ -52,13 +51,12 @@ object StreamRefSettings { @deprecated( "Use attributes on the Runnable graph or change the defaults in configuration, see migration guide for details https://doc.akka.io/docs/akka/2.6/project/migration-guide-2.5.x-2.6.x.html", since = "Akka 2.6.0") - def apply(c: Config): StreamRefSettings = { + def apply(c: Config): StreamRefSettings = StreamRefSettingsImpl( bufferCapacity = c.getInt("buffer-capacity"), demandRedeliveryInterval = c.getDuration("demand-redelivery-interval", TimeUnit.MILLISECONDS).millis, subscriptionTimeout = c.getDuration("subscription-timeout", TimeUnit.MILLISECONDS).millis, finalTerminationSignalDeadline = c.getDuration("final-termination-signal-deadline", TimeUnit.MILLISECONDS).millis) - } } /** diff --git a/stream/src/main/scala/org/apache/pekko/stream/SystemMaterializer.scala b/stream/src/main/scala/org/apache/pekko/stream/SystemMaterializer.scala index efd829d47d8..5e1bfc853f1 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/SystemMaterializer.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/SystemMaterializer.scala @@ -94,9 +94,8 @@ final class SystemMaterializer(system: ExtendedActorSystem) extends Extension { Await.result(started, materializerTimeout.duration).materializer } - val materializer: Materializer = { + val materializer: Materializer = // block on async creation to make it effectively final Await.result(systemMaterializerPromise.future, materializerTimeout.duration) - } } diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/ActorMaterializerImpl.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/ActorMaterializerImpl.scala index 214f3333455..378e1163ae8 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/ActorMaterializerImpl.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/ActorMaterializerImpl.scala @@ -74,14 +74,13 @@ import pekko.util.OptionVal /** * INTERNAL API */ - @InternalApi private[pekko] def actorOf(props: Props, name: String): ActorRef = { + @InternalApi private[pekko] def actorOf(props: Props, name: String): ActorRef = supervisor match { case ref: LocalActorRef => ref.underlying.attachChild(props, name, systemService = false) case unknown => throw new IllegalStateException(s"Stream supervisor must be a local actor, was [${unknown.getClass.getName}]") } - } /** * INTERNAL API @@ -110,10 +109,9 @@ private[pekko] class SubFusingActorMaterializerImpl( settings: ActorMaterializerSettings, attributes: Attributes, materializer: PhasedFusingActorMaterializer, - islandName: String): PhaseIsland[Any] = { + islandName: String): PhaseIsland[Any] = new GraphStageIsland(attributes, materializer, islandName, OptionVal(registerShell)) .asInstanceOf[PhaseIsland[Any]] - } } override def executionContext: ExecutionContextExecutor = delegate.executionContext @@ -197,12 +195,11 @@ private[pekko] class SubFusingActorMaterializerImpl( * INTERNAL API */ @InternalApi private[pekko] object StreamSupervisor { - def props(attributes: Attributes, haveShutDown: AtomicBoolean): Props = { + def props(attributes: Attributes, haveShutDown: AtomicBoolean): Props = Props(new StreamSupervisor(haveShutDown)) .withDeploy(Deploy.local) .withDispatcher(attributes.mandatoryAttribute[ActorAttributes.Dispatcher].dispatcher) .withMailbox(PhasedFusingActorMaterializer.MailboxConfigName) - } private[stream] val baseName = "StreamSupervisor" private val actorName = SeqActorName(baseName) @@ -307,10 +304,9 @@ private[pekko] final class SnapshotCollector(streamActors: Set[ActorRef], timeou context.stop(self) } - def completeIfDone(): Unit = { + def completeIfDone(): Unit = if (leftToRespond.isEmpty) { replyTo ! StatusReply.Success(StreamSupervisor.ChildrenSnapshots(collected)) context.stop(self) } - } } diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/ActorProcessor.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/ActorProcessor.scala index 486db489eda..b5fdd95e791 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/ActorProcessor.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/ActorProcessor.scala @@ -107,13 +107,12 @@ import org.reactivestreams.{ Processor, Subscriber, Subscription } pump.pump() } - override def cancel(): Unit = { + override def cancel(): Unit = if (!upstreamCompleted) { upstreamCompleted = true if (upstream ne null) upstream.cancel() clear() } - } override def isClosed: Boolean = upstreamCompleted private def clear(): Unit = { @@ -165,9 +164,8 @@ import org.reactivestreams.{ Processor, Subscriber, Subscription } case OnSubscribe(_) => throw new IllegalStateException("onSubscribe called after onError or onComplete") } - protected def inputOnError(@unused e: Throwable): Unit = { + protected def inputOnError(@unused e: Throwable): Unit = clear() - } } @@ -197,28 +195,25 @@ import org.reactivestreams.{ Processor, Subscriber, Subscription } tryOnNext(subscriber, elem) } - override def complete(): Unit = { + override def complete(): Unit = if (!downstreamCompleted) { downstreamCompleted = true if (exposedPublisher ne null) exposedPublisher.shutdown(None) if (subscriber ne null) tryOnComplete(subscriber) } - } - override def cancel(): Unit = { + override def cancel(): Unit = if (!downstreamCompleted) { downstreamCompleted = true if (exposedPublisher ne null) exposedPublisher.shutdown(None) } - } - override def error(e: Throwable): Unit = { + override def error(e: Throwable): Unit = if (!downstreamCompleted) { downstreamCompleted = true if (exposedPublisher ne null) exposedPublisher.shutdown(Some(e)) if ((subscriber ne null) && !e.isInstanceOf[SpecViolation]) tryOnError(subscriber, e) } - } override def isClosed: Boolean = downstreamCompleted && (subscriber ne null) diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/ActorRefBackpressureSinkStage.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/ActorRefBackpressureSinkStage.scala index c5224843c54..55a0a6e65b2 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/ActorRefBackpressureSinkStage.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/ActorRefBackpressureSinkStage.scala @@ -50,7 +50,7 @@ import pekko.stream.stage._ private var completeReceived = false private var completionSignalled = false - private def receive(evt: (ActorRef, Any)): Unit = { + private def receive(evt: (ActorRef, Any)): Unit = evt._2 match { case Terminated(`ref`) => completeStage() case ackMsg if ackMessage.isEmpty || ackMessage.contains(ackMsg) => @@ -65,7 +65,6 @@ import pekko.stream.stage._ } case _ => // ignore all other messages } - } override def preStart(): Unit = { setKeepGoing(true) @@ -74,9 +73,8 @@ import pekko.stream.stage._ pull(in) } - private def dequeueAndSend(): Unit = { + private def dequeueAndSend(): Unit = ref ! messageAdapter(self)(buffer.poll()) - } private def finish(): Unit = { ref ! onCompleteMessage @@ -93,10 +91,9 @@ import pekko.stream.stage._ if (buffer.size() < maxBuffer) pull(in) } - override def onUpstreamFinish(): Unit = { + override def onUpstreamFinish(): Unit = if (buffer.isEmpty) finish() else completeReceived = true - } override def onUpstreamFailure(ex: Throwable): Unit = { ref ! onFailureMessage(ex) @@ -104,11 +101,10 @@ import pekko.stream.stage._ failStage(ex) } - override def postStop(): Unit = { + override def postStop(): Unit = if (!completionSignalled) { ref ! onFailureMessage(new AbruptStageTerminationException(this)) } - } setHandler(in, this) } diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/ActorRefSinkStage.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/ActorRefSinkStage.scala index 94852df9732..37a9f752566 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/ActorRefSinkStage.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/ActorRefSinkStage.scala @@ -73,10 +73,9 @@ final private[pekko] class ActorRefSinkStage[T]( failStage(ex) } - override def postStop(): Unit = { + override def postStop(): Unit = if (!completionSignalled) { ref ! onFailureMessage(new AbruptStageTerminationException(this)) } - } } } diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/Buffers.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/Buffers.scala index 8e377bd4bcc..2d290b612ff 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/Buffers.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/Buffers.scala @@ -198,9 +198,8 @@ private[pekko] object Buffer { override def enqueue(elem: T): Unit = if (tail - head == FixedQueueSize) { val queue = new DynamicQueue[T](capacity) - while (nonEmpty) { + while (nonEmpty) queue.enqueue(dequeue()) - } switchBuffer(queue) queue.enqueue(elem) } else { @@ -219,9 +218,8 @@ private[pekko] object Buffer { if (tail == head) null.asInstanceOf[T] else queue(head & FixedQueueMask).asInstanceOf[T] override def clear(): Unit = - while (nonEmpty) { + while (nonEmpty) dequeue() - } override def dropHead(): Unit = dequeue() override def dropTail(): Unit = { tail -= 1 diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/FailedSource.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/FailedSource.scala index 4ab1c253556..2dd8b2c77be 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/FailedSource.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/FailedSource.scala @@ -33,9 +33,8 @@ import pekko.stream.stage.{ GraphStage, GraphStageLogic, OutHandler } override def onPull(): Unit = () - override def preStart(): Unit = { + override def preStart(): Unit = failStage(failure) - } setHandler(out, this) } diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/FanIn.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/FanIn.scala index d7b5d4fa42b..9c4c43fa549 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/FanIn.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/FanIn.scala @@ -137,23 +137,21 @@ import org.reactivestreams.{ Subscriber, Subscription } def onCompleteWhenNoInput(): Unit = () - def markInput(input: Int): Unit = { + def markInput(input: Int): Unit = if (!marked(input)) { if (depleted(input)) markedDepleted += 1 if (pending(input)) markedPending += 1 marked(input, on = true) markCount += 1 } - } - def unmarkInput(input: Int): Unit = { + def unmarkInput(input: Int): Unit = if (marked(input)) { if (depleted(input)) markedDepleted -= 1 if (pending(input)) markedPending -= 1 marked(input, on = false) markCount -= 1 } - } def markAllInputs(): Unit = { var i = 0 diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/FanOut.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/FanOut.scala index 90a175a07e8..728ba135766 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/FanOut.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/FanOut.scala @@ -121,23 +121,21 @@ import org.reactivestreams.Subscription unmarkOutput(output) } - def markOutput(output: Int): Unit = { + def markOutput(output: Int): Unit = if (!marked(output)) { if (cancelled(output)) markedCancelled += 1 if (pending(output)) markedPending += 1 marked(output) = true markedCount += 1 } - } - def unmarkOutput(output: Int): Unit = { + def unmarkOutput(output: Int): Unit = if (marked(output)) { if (cancelled(output)) markedCancelled -= 1 if (pending(output)) markedPending -= 1 marked(output) = false markedCount -= 1 } - } def markAllOutputs(): Unit = { var i = 0 diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/FanoutProcessor.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/FanoutProcessor.scala index d217f7b873a..6c4a9fb4fc6 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/FanoutProcessor.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/FanoutProcessor.scala @@ -69,13 +69,12 @@ import org.reactivestreams.Subscriber override def cancel(): Unit = complete() - override def error(e: Throwable): Unit = { + override def error(e: Throwable): Unit = if (!downstreamCompleted) { downstreamCompleted = true abortDownstream(e) if (exposedPublisher ne null) exposedPublisher.shutdown(Some(e)) } - } def isClosed: Boolean = downstreamCompleted @@ -94,9 +93,8 @@ import org.reactivestreams.Subscriber afterShutdown() } - override protected def cancelUpstream(): Unit = { + override protected def cancelUpstream(): Unit = downstreamCompleted = true - } protected def waitingExposedPublisher: Actor.Receive = { case ExposedPublisher(publisher) => diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/LazySource.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/LazySource.scala index dc68fc139ff..92ba7424ee0 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/LazySource.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/LazySource.scala @@ -52,9 +52,9 @@ import pekko.stream.stage._ override def onPull(): Unit = { val source = - try { + try sourceFactory() - } catch { + catch { case NonFatal(ex) => matPromise.tryFailure(ex) throw ex @@ -64,9 +64,8 @@ import pekko.stream.stage._ setHandler(out, new OutHandler { - override def onPull(): Unit = { + override def onPull(): Unit = subSink.pull() - } override def onDownstreamFinish(cause: Throwable): Unit = { subSink.cancel(cause) @@ -75,9 +74,8 @@ import pekko.stream.stage._ }) subSink.setHandler(new InHandler { - override def onPush(): Unit = { + override def onPush(): Unit = push(out, subSink.grab()) - } }) try { @@ -93,9 +91,8 @@ import pekko.stream.stage._ setHandler(out, this) - override def postStop() = { + override def postStop() = if (!matPromise.isCompleted) matPromise.tryFailure(new AbruptStageTerminationException(this)) - } } (logic, matPromise.future) diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/MaybeSource.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/MaybeSource.scala index 659b9a580d8..08f95da14c2 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/MaybeSource.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/MaybeSource.scala @@ -42,7 +42,7 @@ import pekko.util.OptionVal private var arrivedEarly: OptionVal[AnyRef] = OptionVal.None - override def preStart(): Unit = { + override def preStart(): Unit = promise.future.value match { case Some(value) => // already completed, shortcut @@ -51,7 +51,6 @@ import pekko.util.OptionVal // callback on future completion promise.future.onComplete(getAsyncCallback(handleCompletion).invoke)(ExecutionContexts.parasitic) } - } override def onPull(): Unit = arrivedEarly match { case OptionVal.Some(value) => @@ -60,7 +59,7 @@ import pekko.util.OptionVal case _ => } - private def handleCompletion(elem: Try[Option[AnyRef]]): Unit = { + private def handleCompletion(elem: Try[Option[AnyRef]]): Unit = elem match { case ScalaSuccess(None) => completeStage() @@ -74,16 +73,13 @@ import pekko.util.OptionVal case ScalaFailure(ex) => failStage(ex) } - } - override def onDownstreamFinish(cause: Throwable): Unit = { + override def onDownstreamFinish(cause: Throwable): Unit = promise.tryComplete(ScalaSuccess(None)) - } - override def postStop(): Unit = { + override def postStop(): Unit = if (!promise.isCompleted) promise.tryFailure(new AbruptStageTerminationException(this)) - } setHandler(out, this) diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/PhasedFusingActorMaterializer.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/PhasedFusingActorMaterializer.scala index 81bd562bc3a..5f617960637 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/PhasedFusingActorMaterializer.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/PhasedFusingActorMaterializer.scala @@ -378,7 +378,7 @@ private final case class SavedIslandData( } - @InternalApi private[pekko] def allNestedIslandsReady(): Unit = { + @InternalApi private[pekko] def allNestedIslandsReady(): Unit = if (activePhases ne null) { var i = 0 while (i < activePhases.size()) { @@ -386,7 +386,6 @@ private final case class SavedIslandData( i += 1 } } - } } @@ -568,9 +567,8 @@ private final case class SavedIslandData( if (Debug) println("--- Finished materialization") matValueStack.peekLast().asInstanceOf[Mat] - } finally { + } finally if (isShutdown) throw shutdownWhileMaterializingFailure - } } @@ -871,11 +869,10 @@ private final case class SavedIslandData( extends PhaseIsland[Publisher[Any]] { override def name: String = s"SourceModule phase" - override def materializeAtomic(mod: AtomicModule[Shape, Any], attributes: Attributes): (Publisher[Any], Any) = { + override def materializeAtomic(mod: AtomicModule[Shape, Any], attributes: Attributes): (Publisher[Any], Any) = mod .asInstanceOf[SourceModule[Any, Any]] .create(MaterializationContext(materializer, attributes, islandName + "-" + attributes.nameOrDefault())) - } override def assignPort(in: InPort, slot: Int, logic: Publisher[Any]): Unit = () @@ -916,17 +913,15 @@ private final case class SavedIslandData( override def assignPort(out: OutPort, slot: Int, logic: AnyRef): Unit = () - override def createPublisher(out: OutPort, logic: AnyRef): Publisher[Any] = { + override def createPublisher(out: OutPort, logic: AnyRef): Publisher[Any] = throw new UnsupportedOperationException("A Sink cannot create a Publisher") - } - override def takePublisher(slot: Int, publisher: Publisher[Any], attributes: Attributes): Unit = { + override def takePublisher(slot: Int, publisher: Publisher[Any], attributes: Attributes): Unit = subscriberOrVirtualPublisher match { case v: VirtualPublisher[_] => v.registerPublisher(publisher) case s: Subscriber[Any] @unchecked => publisher.subscribe(s) case _ => throw new IllegalStateException() // won't happen, compiler exhaustiveness check pleaser } - } override def onIslandReady(): Unit = () } diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/QueueSource.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/QueueSource.scala index 98827879cf3..8da353fef2c 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/QueueSource.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/QueueSource.scala @@ -75,7 +75,7 @@ import pekko.stream.stage._ offer.promise.success(QueueOfferResult.Enqueued) } - private def bufferElem(offer: Offer[T]): Unit = { + private def bufferElem(offer: Offer[T]): Unit = if (!buffer.isFull) { enqueueAndSuccess(offer) } else @@ -125,7 +125,6 @@ import pekko.stream.stage._ "You have to wait for one previous future to be resolved to send another request")) else pendingOffers.enqueue(offer) } - } private val callback = getAsyncCallback[Input[T]] { case Offer(_, promise) if terminating => @@ -197,7 +196,7 @@ import pekko.stream.stage._ completeStage() } - override def onPull(): Unit = { + override def onPull(): Unit = if (maxBuffer == 0) { if (pendingOffers.nonEmpty) { val offer = pendingOffers.dequeue() @@ -216,7 +215,6 @@ import pekko.stream.stage._ completeStage() } } - } override def watchCompletion() = completion.future override def offer(element: T): Future[QueueOfferResult] = { diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/ReactiveStreamsCompliance.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/ReactiveStreamsCompliance.scala index 6541f362c2d..1416a6b0c35 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/ReactiveStreamsCompliance.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/ReactiveStreamsCompliance.scala @@ -61,11 +61,10 @@ import org.reactivestreams.{ Subscriber, Subscription } final def subscriptionMustNotBeNullException: Throwable = new NullPointerException(SubscriptionMustNotBeNullMsg) - final def rejectDuplicateSubscriber[T](subscriber: Subscriber[T]): Unit = { + final def rejectDuplicateSubscriber[T](subscriber: Subscriber[T]): Unit = // since it is already subscribed it has received the subscription first // and we can emit onError immediately tryOnError(subscriber, canNotSubscribeTheSameSubscriberMultipleTimesException) - } final def rejectAdditionalSubscriber[T](subscriber: Subscriber[T], rejector: String): Unit = { tryOnSubscribe(subscriber, CancelledSubscription) @@ -113,19 +112,17 @@ import org.reactivestreams.{ Subscriber, Subscription } } } - final def tryOnSubscribe[T](subscriber: Subscriber[T], subscription: Subscription): Unit = { + final def tryOnSubscribe[T](subscriber: Subscriber[T], subscription: Subscription): Unit = try subscriber.onSubscribe(subscription) catch { case NonFatal(t) => throw new SignalThrewException(s"$subscriber.onSubscribe", t) } - } - final def tryOnComplete[T](subscriber: Subscriber[T]): Unit = { + final def tryOnComplete[T](subscriber: Subscriber[T]): Unit = try subscriber.onComplete() catch { case NonFatal(t) => throw new SignalThrewException(s"$subscriber.onComplete", t) } - } final def tryRequest(subscription: Subscription, demand: Long): Unit = { if (subscription eq null) diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/RetryFlowCoordinator.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/RetryFlowCoordinator.scala index da30ece161b..0a008349602 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/RetryFlowCoordinator.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/RetryFlowCoordinator.scala @@ -84,22 +84,20 @@ import pekko.util.OptionVal internalOut, new OutHandler { - override def onPull(): Unit = { + override def onPull(): Unit = if (elementInProgress.isEmpty) { if (!hasBeenPulled(externalIn) && !isClosed(externalIn)) { pull(externalIn) } } - } - override def onDownstreamFinish(cause: Throwable): Unit = { + override def onDownstreamFinish(cause: Throwable): Unit = if (elementInProgress.isEmpty || !cause.isInstanceOf[NonFailureCancellation]) { super.onDownstreamFinish(cause) } else { // emit elements before finishing setKeepGoing(true) } - } }) setHandler( @@ -129,9 +127,8 @@ import pekko.util.OptionVal if (!hasBeenPulled(internalIn)) pull(internalIn) }) - private def pushInternal(element: In): Unit = { + private def pushInternal(element: In): Unit = push(internalOut, element) - } private def pushExternal(result: Out): Unit = { elementInProgress = OptionVal.none diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/SetupStage.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/SetupStage.scala index b6efde68a1a..bc4e97312e6 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/SetupStage.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/SetupStage.scala @@ -57,7 +57,7 @@ import pekko.stream.stage.OutHandler setHandler(in, delegateToSubOutlet(() => grab(in), subOutlet)) setHandler(out, delegateToSubInlet(subInlet)) - override def preStart(): Unit = { + override def preStart(): Unit = try { val flow = factory(materializer, attributes) @@ -70,7 +70,6 @@ import pekko.stream.stage.OutHandler matPromise.failure(ex) throw ex } - } } } @@ -95,7 +94,7 @@ import pekko.stream.stage.OutHandler subInlet.setHandler(delegateToOutlet(push(out, _: T), () => complete(out), fail(out, _), subInlet)) setHandler(out, delegateToSubInlet(subInlet)) - override def preStart(): Unit = { + override def preStart(): Unit = try { val source = factory(materializer, attributes) @@ -106,7 +105,6 @@ import pekko.stream.stage.OutHandler matPromise.failure(ex) throw ex } - } } } diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/SingleConcat.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/SingleConcat.scala index 7d900f47121..cf68d331f5d 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/SingleConcat.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/SingleConcat.scala @@ -40,15 +40,13 @@ private[pekko] final class SingleConcat[E](singleElem: E) extends GraphStage[Flo override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = new GraphStageLogic(shape) with InHandler with OutHandler { - override def onPush(): Unit = { + override def onPush(): Unit = push(out, grab(in)) - } override def onPull(): Unit = pull(in) - override def onUpstreamFinish(): Unit = { + override def onUpstreamFinish(): Unit = emit(out, singleElem, () => completeStage()) - } setHandlers(in, out, this) } diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/Sinks.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/Sinks.scala index 380b27e2dbd..20083a4aea6 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/Sinks.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/Sinks.scala @@ -231,9 +231,8 @@ import org.reactivestreams.Subscriber failStage(ex) } - override def postStop(): Unit = { + override def postStop(): Unit = if (!p.isCompleted) p.failure(new AbruptStageTerminationException(this)) - } setHandler(in, this) }, p.future) @@ -278,9 +277,8 @@ import org.reactivestreams.Subscriber failStage(ex) } - override def postStop(): Unit = { + override def postStop(): Unit = if (!p.isCompleted) p.failure(new AbruptStageTerminationException(this)) - } setHandler(in, this) } @@ -388,9 +386,8 @@ import org.reactivestreams.Subscriber }(pekko.dispatch.ExecutionContexts.parasitic) p.future } - override def cancel(): Unit = { + override def cancel(): Unit = callback.invoke(QueueSink.Cancel) - } } (stageLogic, stageLogic) @@ -459,10 +456,9 @@ import org.reactivestreams.Subscriber this } - override def finish(): R = { + override def finish(): R = // only called if completed without elements collector.finisher().apply(_accumulated) - } } /** @@ -560,16 +556,16 @@ import org.reactivestreams.Subscriber promise.failure(e) failStage(e) } - try { + try sinkFactory(element).onComplete(cb.invoke)(ExecutionContexts.parasitic) - } catch { + catch { case NonFatal(e) => promise.failure(e) failStage(e) } } - override def onUpstreamFinish(): Unit = { + override def onUpstreamFinish(): Unit = // ignore onUpstreamFinish while the stage is switching but setKeepGoing // if (switching) { @@ -579,7 +575,6 @@ import org.reactivestreams.Subscriber promise.failure(new NeverMaterializedException) super.onUpstreamFinish() } - } override def onUpstreamFailure(ex: Throwable): Unit = { promise.failure(ex) @@ -597,11 +592,10 @@ import org.reactivestreams.Subscriber val matVal = interpreter.subFusingMaterializer .materialize(Source.fromGraph(subOutlet.source).toMat(sink)(Keep.right), inheritedAttributes) - def maybeCompleteStage(): Unit = { + def maybeCompleteStage(): Unit = if (isClosed(in) && subOutlet.isClosed) { completeStage() } - } // The stage must not be shut down automatically; it is completed when maybeCompleteStage decides setKeepGoing(true) @@ -609,15 +603,13 @@ import org.reactivestreams.Subscriber setHandler( in, new InHandler { - override def onPush(): Unit = { + override def onPush(): Unit = subOutlet.push(grab(in)) - } - override def onUpstreamFinish(): Unit = { + override def onUpstreamFinish(): Unit = if (firstElementPushed) { subOutlet.complete() maybeCompleteStage() } - } override def onUpstreamFailure(ex: Throwable): Unit = { // propagate exception irrespective if the cached element has been pushed or not subOutlet.fail(ex) @@ -630,7 +622,7 @@ import org.reactivestreams.Subscriber }) subOutlet.setHandler(new OutHandler { - override def onPull(): Unit = { + override def onPull(): Unit = if (firstElementPushed) { pull(in) } else { @@ -644,7 +636,6 @@ import org.reactivestreams.Subscriber maybeCompleteStage() } } - } override def onDownstreamFinish(cause: Throwable): Unit = { if (!isClosed(in)) cancel(in, cause) diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/StreamLayout.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/StreamLayout.scala index d1b3506f765..e2ad8d740b2 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/StreamLayout.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/StreamLayout.scala @@ -136,7 +136,7 @@ import org.reactivestreams.Subscription if (VirtualProcessor.Debug) println(s"created: $this") override def subscribe(s: Subscriber[_ >: T]): Unit = { - @tailrec def rec(sub: Subscriber[Any]): Unit = { + @tailrec def rec(sub: Subscriber[Any]): Unit = get() match { case null => if (VirtualProcessor.Debug) println(s"VirtualPublisher#$hashCode(null).subscribe.rec($s) -> sub") @@ -156,7 +156,6 @@ import org.reactivestreams.Subscription println(s"VirtualPublisher#$hashCode($other).subscribe.rec($s): rejectAdditionalSubscriber") rejectAdditionalSubscriber(sub, "VirtualProcessor") } - } if (s == null) { val ex = subscriberMustNotBeNullException @@ -166,7 +165,7 @@ import org.reactivestreams.Subscription } override def onSubscribe(s: Subscription): Unit = { - @tailrec def rec(obj: AnyRef): Unit = { + @tailrec def rec(obj: AnyRef): Unit = get() match { case null => if (VirtualProcessor.Debug) @@ -195,7 +194,6 @@ import org.reactivestreams.Subscription // spec violation tryCancel(s, new IllegalStateException(s"VirtualProcessor in wrong state [$state]. Spec violation")) } - } if (s == null) { val ex = subscriptionMustNotBeNullException @@ -296,7 +294,7 @@ import org.reactivestreams.Subscription if (t == null) throw ex } - @tailrec override def onComplete(): Unit = { + @tailrec override def onComplete(): Unit = get() match { case null => if (VirtualProcessor.Debug) println(s"VirtualPublisher#$hashCode(null).onComplete -> EmptyPublisher") @@ -320,7 +318,6 @@ import org.reactivestreams.Subscription if (VirtualProcessor.Debug) println(s"VirtualPublisher#$hashCode($other).onComplete spec violation") // spec violation or cancellation race, but nothing we can do } - } override def onNext(t: T): Unit = if (t == null) { @@ -343,7 +340,7 @@ import org.reactivestreams.Subscription rec() throw ex // must throw NPE, rule 2:13 } else { - @tailrec def rec(): Unit = { + @tailrec def rec(): Unit = get() match { case h: HasActualSubscriber => val s = h.subscriber @@ -378,7 +375,6 @@ import org.reactivestreams.Subscription if (!compareAndSet(other, pub)) rec() else throw pub.t } - } rec() } @@ -409,7 +405,7 @@ import org.reactivestreams.Subscription if (requests > 0) real.request(requests) } - override def request(n: Long): Unit = { + override def request(n: Long): Unit = if (n < 1) { if (VirtualProcessor.Debug) println(s"VirtualPublisher#${VirtualProcessor.this.hashCode}.WrappedSubscription($real).request($n)") @@ -442,7 +438,6 @@ import org.reactivestreams.Subscription } bufferDemand(n) } - } override def cancel(): Unit = { if (VirtualProcessor.Debug) println(s"VirtualPublisher#${VirtualProcessor.this.hashCode}WrappedSubscription.cancel() -> Inert") @@ -477,7 +472,7 @@ import org.reactivestreams.Subscription override def subscribe(subscriber: Subscriber[_ >: T]): Unit = { requireNonNullSubscriber(subscriber) if (VirtualProcessor.Debug) println(s"$this.subscribe: $subscriber") - @tailrec def rec(): Unit = { + @tailrec def rec(): Unit = get() match { case null => if (!compareAndSet(null, subscriber)) rec() // retry @@ -492,7 +487,6 @@ import org.reactivestreams.Subscription case unexpected => throw new IllegalStateException(s"Unexpected state in VirtualPublisher: $unexpected") } - } rec() // return value is boolean only to make the expressions above compile } diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/StreamSubscriptionTimeout.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/StreamSubscriptionTimeout.scala index 9998c1e026e..027f5665cf0 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/StreamSubscriptionTimeout.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/StreamSubscriptionTimeout.scala @@ -113,13 +113,12 @@ import org.reactivestreams._ } } - private def warn(target: Publisher[_], timeout: FiniteDuration): Unit = { + private def warn(target: Publisher[_], timeout: FiniteDuration): Unit = log.warning( "Timed out {} detected (after {} ms)! You should investigate if you either cancel or consume all {} instances", target, timeout.toMillis, target.getClass.getCanonicalName) - } /** * Called by the actor when a subscription has timed out. Expects the actual `Publisher` or `Processor` target. diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/SubscriberManagement.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/SubscriberManagement.scala index 1a4788d9cca..074ba0af1eb 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/SubscriberManagement.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/SubscriberManagement.scala @@ -202,7 +202,7 @@ private[pekko] trait SubscriberManagement[T] extends ResizableMultiReaderRingBuf * this method must be called by the implementing class whenever * it has been determined that no more elements will be produced */ - protected def completeDownstream(): Unit = { + protected def completeDownstream(): Unit = if (endOfStream eq NotReached) { @tailrec def completeDoneSubscriptions(remaining: Subscriptions, result: Subscriptions = Nil): Subscriptions = remaining match { @@ -218,7 +218,6 @@ private[pekko] trait SubscriberManagement[T] extends ResizableMultiReaderRingBuf subscriptions = completeDoneSubscriptions(subscriptions) if (subscriptions.isEmpty) shutdown(completed = true) } // else ignore, we need to be idempotent - } /** * this method must be called by the implementing class to push an error downstream diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/Timers.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/Timers.scala index cdbc42828fb..a5946893cd3 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/Timers.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/Timers.scala @@ -210,10 +210,9 @@ import pekko.stream.stage._ setHandlers(in, out, this) - override def preStart(): Unit = { + override def preStart(): Unit = if (delay == Duration.Zero) open = true else scheduleOnce(GraphStageLogicTimer, delay) - } override def onPush(): Unit = push(out, grab(in)) @@ -259,18 +258,16 @@ import pekko.stream.stage._ } } - override def onUpstreamFinish(): Unit = { + override def onUpstreamFinish(): Unit = if (!isAvailable(in)) completeStage() - } - override def onPull(): Unit = { + override def onPull(): Unit = if (isAvailable(in)) { contextPropagation.resumeContext() push(out, grab(in)) if (isClosed(in)) completeStage() else pull(in) } else emitInjectedElementOrReschedule(onTimer = false) - } private def emitInjectedElementOrReschedule(onTimer: Boolean): Unit = { val now = System.nanoTime() diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/Transfer.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/Transfer.scala index dc187a2f083..fa81e656dc8 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/Transfer.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/Transfer.scala @@ -28,9 +28,8 @@ import pekko.annotation.InternalApi override def isDefinedAt(msg: Any): Boolean = currentReceive.isDefinedAt(msg) override def apply(msg: Any): Unit = currentReceive.apply(msg) - def become(newBehavior: Actor.Receive): Unit = { + def become(newBehavior: Actor.Receive): Unit = currentReceive = newBehavior - } } /** @@ -209,9 +208,8 @@ import pekko.annotation.InternalApi // Exchange input buffer elements and output buffer "requests" until one of them becomes empty. // Generate upstream requestMore for every Nth consumed input element final def pump(): Unit = { - try while (transferState.isExecutable) { + try while (transferState.isExecutable) currentAction() - } catch { case NonFatal(e) => pumpFailed(e) } if (isPumpFinished) pumpFinished() diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/TraversalBuilder.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/TraversalBuilder.scala index 7ff61a2b3a8..342aff781e3 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/TraversalBuilder.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/TraversalBuilder.scala @@ -52,9 +52,8 @@ import pekko.util.unused /** * Concatenates two traversals building a new Traversal which traverses both. */ - def concat(that: Traversal): Traversal = { + def concat(that: Traversal): Traversal = Concat.normalizeConcat(this, that) - } def rewireFirstTo(@unused relativeOffset: Int): Traversal = null } @@ -70,7 +69,7 @@ import pekko.util.unused * and require less stack-space when traversing. This is only a single rotation, otherwise this implementation * would be O(N^2). */ - def normalizeConcat(first: Traversal, second: Traversal): Traversal = { + def normalizeConcat(first: Traversal, second: Traversal): Traversal = if (second eq EmptyTraversal) first else if (first eq PushNotUsed) { // No need to push NotUsed and Pop it immediately @@ -90,7 +89,6 @@ import pekko.util.unused case _ => Concat(first, second) } } - } } @@ -173,12 +171,11 @@ import pekko.util.unused */ @InternalApi private[pekko] final case class Compose(composer: AnyFunction2, reverse: Boolean = false) extends MaterializedValueOp { - def apply(arg1: Any, arg2: Any): Any = { + def apply(arg1: Any, arg2: Any): Any = if (reverse) composer.asInstanceOf[(Any, Any) => Any](arg2, arg1) else composer.asInstanceOf[(Any, Any) => Any](arg1, arg2) - } } /** @@ -252,10 +249,9 @@ import pekko.util.unused /** * INTERNAL API */ - @InternalApi private[pekko] def empty(attributes: Attributes = Attributes.none): TraversalBuilder = { + @InternalApi private[pekko] def empty(attributes: Attributes = Attributes.none): TraversalBuilder = if (attributes eq Attributes.none) cachedEmptyCompleted else CompletedTraversalBuilder(PushNotUsed, 0, Map.empty, attributes) - } /** * INTERNAL API @@ -353,7 +349,7 @@ import pekko.util.unused * Try to find `SingleSource` or wrapped such. This is used as a * performance optimization in FlattenMerge and possibly other places. */ - def getSingleSource[A >: Null](graph: Graph[SourceShape[A], _]): OptionVal[SingleSource[A]] = { + def getSingleSource[A >: Null](graph: Graph[SourceShape[A], _]): OptionVal[SingleSource[A]] = graph match { case single: SingleSource[A] @unchecked => OptionVal.Some(single) case _ => @@ -378,7 +374,6 @@ import pekko.util.unused case _ => OptionVal.None } } - } /** * Test if a Graph is an empty Source. @@ -422,10 +417,9 @@ import pekko.util.unused protected def internalSetAttributes(attributes: Attributes): TraversalBuilder - def setAttributes(attributes: Attributes): TraversalBuilder = { + def setAttributes(attributes: Attributes): TraversalBuilder = if (attributes.isAsync) this.makeIsland(GraphStageTag).internalSetAttributes(attributes) else internalSetAttributes(attributes) - } def attributes: Attributes @@ -579,13 +573,12 @@ import pekko.util.unused attributes: Attributes) extends TraversalBuilder { - override def add(submodule: TraversalBuilder, shape: Shape, combineMat: AnyFunction2): TraversalBuilder = { + override def add(submodule: TraversalBuilder, shape: Shape, combineMat: AnyFunction2): TraversalBuilder = // TODO: Use automatically a linear builder if applicable // Create a composite, add ourselves, then the other. CompositeTraversalBuilder(attributes = attributes) .add(this, module.shape, Keep.right) .add(submodule, shape, combineMat) - } override def transformMat(f: AnyFunction1): TraversalBuilder = TraversalBuilder.empty().add(this, module.shape, Keep.right).transformMat(f) @@ -598,9 +591,8 @@ import pekko.util.unused override def isUnwired(out: OutPort): Boolean = true override def isUnwired(in: InPort): Boolean = true - override def wire(out: OutPort, in: InPort): TraversalBuilder = { + override def wire(out: OutPort, in: InPort): TraversalBuilder = assign(out, offsetOf(in) - offsetOfModule(out)) - } override def assign(out: OutPort, relativeSlot: Int): TraversalBuilder = { // Create a new array, with the output port assigned to its relative slot @@ -682,7 +674,7 @@ import pekko.util.unused attributes) } - def addMatCompose(t: Traversal, matCompose: AnyFunction2): Traversal = { + def addMatCompose(t: Traversal, matCompose: AnyFunction2): Traversal = if (matCompose eq Keep.left) Pop.concat(t) else if (matCompose eq Keep.right) @@ -691,12 +683,11 @@ import pekko.util.unused t.concat(Pop).concat(Pop).concat(PushNotUsed) else t.concat(Compose(matCompose, reverse = true)) - } def fromBuilder( traversalBuilder: TraversalBuilder, shape: Shape, - combine: AnyFunction2 = Keep.right): LinearTraversalBuilder = { + combine: AnyFunction2 = Keep.right): LinearTraversalBuilder = traversalBuilder match { case linear: LinearTraversalBuilder => if (combine eq Keep.right) linear @@ -737,7 +728,6 @@ import pekko.util.unused beforeBuilder = EmptyTraversal) } - } } /** @@ -765,11 +755,10 @@ import pekko.util.unused protected def isEmpty: Boolean = inSlots == 0 && outPort.isEmpty - override def add(submodule: TraversalBuilder, shape: Shape, combineMat: AnyFunction2): TraversalBuilder = { + override def add(submodule: TraversalBuilder, shape: Shape, combineMat: AnyFunction2): TraversalBuilder = throw new UnsupportedOperationException( "LinearTraversal does not support free-form addition. Add it into a" + "composite builder instead and add the second module to that.") - } /** * This builder can always return a traversal. @@ -783,10 +772,9 @@ import pekko.util.unused override def internalSetAttributes(attributes: Attributes): LinearTraversalBuilder = copy(attributes = attributes) - override def setAttributes(attributes: Attributes): LinearTraversalBuilder = { + override def setAttributes(attributes: Attributes): LinearTraversalBuilder = if (attributes.isAsync) this.makeIsland(GraphStageTag).internalSetAttributes(attributes) else internalSetAttributes(attributes) - } private def applyIslandAndAttributes(t: Traversal): Traversal = { val withIslandTag = islandTag match { @@ -804,17 +792,16 @@ import pekko.util.unused * last. This method tears down the traversal until it finds that [[MaterializeAtomic]], changes the mapping, * then rebuilds the Traversal. */ - private def rewireLastOutTo(traversal: Traversal, relativeOffset: Int): Traversal = { + private def rewireLastOutTo(traversal: Traversal, relativeOffset: Int): Traversal = // If, by luck, the offset is the same as it would be in the normal case, no transformation is needed if (relativeOffset == -1) traversal else traversal.rewireFirstTo(relativeOffset) - } /** * Since this is a linear traversal, this should not be called in most of the cases. The only notable * exception is when a Flow is wired to itself. */ - override def wire(out: OutPort, in: InPort): TraversalBuilder = { + override def wire(out: OutPort, in: InPort): TraversalBuilder = if (outPort.contains(out) && inPort.contains(in)) { pendingBuilder match { case OptionVal.Some(composite) => @@ -835,9 +822,8 @@ import pekko.util.unused } } else throw new IllegalArgumentException(s"The ports $in and $out cannot be accessed in this builder.") - } - override def offsetOfModule(out: OutPort): Int = { + override def offsetOfModule(out: OutPort): Int = if (outPort.contains(out)) { pendingBuilder match { case OptionVal.Some(composite) => composite.offsetOfModule(out) @@ -845,18 +831,16 @@ import pekko.util.unused } } else throw new IllegalArgumentException(s"Port $out cannot be accessed in this builder") - } override def isUnwired(out: OutPort): Boolean = outPort.contains(out) override def isUnwired(in: InPort): Boolean = inPort.contains(in) - override def offsetOf(in: InPort): Int = { + override def offsetOf(in: InPort): Int = if (inPort.contains(in)) inOffset else throw new IllegalArgumentException(s"Port $in cannot be accessed in this builder") - } - override def assign(out: OutPort, relativeSlot: Int): TraversalBuilder = { + override def assign(out: OutPort, relativeSlot: Int): TraversalBuilder = if (outPort.contains(out)) { pendingBuilder match { case OptionVal.Some(composite) => @@ -871,7 +855,6 @@ import pekko.util.unused } } else throw new IllegalArgumentException(s"Port $out cannot be assigned in this builder") - } override def isTraversalComplete: Boolean = outPort.isEmpty @@ -1019,10 +1002,9 @@ import pekko.util.unused /* * We have almost finished the traversal for _this_ builder, we only need to apply attributes and islands. */ - val finalTraversalForThis = { + val finalTraversalForThis = // Now add the island tags, attributes, and the opcodes that will compose the materialized values with toAppend LinearTraversalBuilder.addMatCompose(applyIslandAndAttributes(assembledTraversalForThis), matCompose) - } /* * We have finished "this" builder, now we need to construct the new builder as the result of appending. @@ -1108,9 +1090,8 @@ import pekko.util.unused } - override def transformMat(f: AnyFunction1): LinearTraversalBuilder = { + override def transformMat(f: AnyFunction1): LinearTraversalBuilder = copy(traversalSoFar = traversalSoFar.concat(Transform(f))) - } /** * Wraps the builder in an island that can be materialized differently, using async boundaries to bridge @@ -1210,7 +1191,7 @@ import pekko.util.unused /** * Convert this builder to a [[CompletedTraversalBuilder]] if there are no more unwired outputs. */ - def completeIfPossible: TraversalBuilder = { + def completeIfPossible: TraversalBuilder = if (unwiredOuts == 0) { var traversal: Traversal = finalSteps var remaining = reverseBuildSteps @@ -1234,7 +1215,6 @@ import pekko.util.unused // to be embedded in a larger graph, making partial graph reuse much more efficient. CompletedTraversalBuilder(traversalSoFar = finalTraversal, inSlots, inOffsets, attributes) } else this - } /** * Assign an output port a relative slot (relative to the base input slot of its module, see [[MaterializeAtomic]]) @@ -1354,19 +1334,16 @@ import pekko.util.unused added.completeIfPossible } - def wire(out: OutPort, in: InPort): TraversalBuilder = { + def wire(out: OutPort, in: InPort): TraversalBuilder = copy(inOffsets = inOffsets - in).assign(out, offsetOf(in) - offsetOfModule(out)) - } - override def transformMat(f: AnyFunction1): TraversalBuilder = { + override def transformMat(f: AnyFunction1): TraversalBuilder = copy(finalSteps = finalSteps.concat(Transform(f))) - } - override def makeIsland(islandTag: IslandTag): TraversalBuilder = { + override def makeIsland(islandTag: IslandTag): TraversalBuilder = this.islandTag match { case OptionVal.None => copy(islandTag = OptionVal(islandTag)) case _ => this // Wrapping with an island, then immediately re-wrapping makes the second island empty, so can be omitted } - } } diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/Unfold.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/Unfold.scala index b62c8c3ab1c..f73394292d6 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/Unfold.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/Unfold.scala @@ -39,10 +39,9 @@ import pekko.stream.stage.{ GraphStage, GraphStageLogic, OutHandler } private[this] var state = s def onPull(): Unit = f(state) match { - case Some((newState, v)) => { + case Some((newState, v)) => push(out, v) state = newState - } case None => complete(out) } @@ -94,9 +93,8 @@ private[pekko] final class UnfoldJava[S, E](s: S, f: function.Function[S, Option private[this] var state = s private[this] var asyncHandler: Try[Option[(S, E)]] => Unit = _ - override def preStart(): Unit = { + override def preStart(): Unit = asyncHandler = getAsyncCallback[Try[Option[(S, E)]]](handle).invoke - } private def handle(result: Try[Option[(S, E)]]): Unit = result match { case Success(Some((newS, elem))) => @@ -138,16 +136,15 @@ private[pekko] final class UnfoldJava[S, E](s: S, f: function.Function[S, Option private[this] var state = s private[this] var asyncHandler: Try[Optional[Pair[S, E]]] => Unit = _ - override def preStart(): Unit = { + override def preStart(): Unit = asyncHandler = getAsyncCallback[Try[Optional[Pair[S, E]]]](handle).invoke - } private def handle(result: Try[Optional[Pair[S, E]]]): Unit = result match { case Success(maybeValue) => handle(maybeValue) case Failure(ex) => fail(out, ex) } - private def handle(maybeValue: Optional[Pair[S, E]]): Unit = { + private def handle(maybeValue: Optional[Pair[S, E]]): Unit = if (maybeValue.isPresent) { val pair = maybeValue.get() push(out, pair.second) @@ -155,21 +152,20 @@ private[pekko] final class UnfoldJava[S, E](s: S, f: function.Function[S, Option } else { complete(out) } - } def onPull(): Unit = { val future = f.apply(state).toCompletableFuture if (future.isDone && !future.isCompletedExceptionally) { handle(future.getNow(null)) } else { - future.handle((r, ex) => { + future.handle { (r, ex) => if (ex != null) { asyncHandler(Failure(ex)) } else { asyncHandler(Success(r)) } null - }) + } } } setHandler(out, this) diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/UnfoldResourceSource.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/UnfoldResourceSource.scala index da0a6ee32d4..1a3907c1935 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/UnfoldResourceSource.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/UnfoldResourceSource.scala @@ -51,12 +51,12 @@ import pekko.stream.stage._ @tailrec final override def onPull(): Unit = { var resumingMode = false - try { + try readData(resource) match { case Some(data) => push(out, data) case None => closeStage() } - } catch { + catch { case NonFatal(ex) => decider(ex) match { case Supervision.Stop => @@ -91,9 +91,8 @@ import pekko.stream.stage._ case NonFatal(ex) => failStage(ex) } - override def postStop(): Unit = { + override def postStop(): Unit = if (open) close(resource) - } setHandler(out, this) } diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/UnfoldResourceSourceAsync.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/UnfoldResourceSourceAsync.scala index 6f6c1861866..79c243be78f 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/UnfoldResourceSourceAsync.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/UnfoldResourceSourceAsync.scala @@ -61,9 +61,9 @@ import pekko.util.OptionVal case Supervision.Stop => failStage(ex) case Supervision.Restart => - try { + try restartResource() - } catch { + catch { case NonFatal(ex) => failStage(ex) } case Supervision.Resume => onPull() @@ -129,7 +129,7 @@ import pekko.util.OptionVal case _ => createResource() } - private def createResource(): Unit = { + private def createResource(): Unit = create().onComplete { resource => createdCallback(resource).failed.foreach { case _: StreamDetachedException => @@ -144,7 +144,6 @@ import pekko.util.OptionVal case _ => // we don't care here } }(parasitic) - } setHandler(out, this) } diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/ActorGraphInterpreter.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/ActorGraphInterpreter.scala index ad5f3b325ab..d2f2dcab05a 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/ActorGraphInterpreter.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/ActorGraphInterpreter.scala @@ -154,7 +154,7 @@ import org.reactivestreams.Subscription def setActor(actor: ActorRef): Unit = this.actor = actor - override def preStart(): Unit = { + override def preStart(): Unit = publisher.subscribe(new Subscriber[Any] { override def onError(t: Throwable): Unit = { ReactiveStreamsCompliance.requireNonNullException(t) @@ -166,16 +166,14 @@ import org.reactivestreams.Subscription actor ! OnSubscribe(shell, s) } - override def onComplete(): Unit = { + override def onComplete(): Unit = actor ! OnComplete(shell) - } override def onNext(t: Any): Unit = { ReactiveStreamsCompliance.requireNonNullElement(t) actor ! OnNext(shell, t) } }) - } @InternalStableApi private def dequeue(): Any = { @@ -210,14 +208,13 @@ import org.reactivestreams.Subscription } @InternalStableApi - def onNext(elem: Any): Unit = { + def onNext(elem: Any): Unit = if (!upstreamCompleted) { if (inputBufferElements == size) throw new IllegalStateException("Input buffer overrun") inputBuffer((nextInputElementCursor + inputBufferElements) & IndexMask) = elem.asInstanceOf[AnyRef] inputBufferElements += 1 if (isAvailable(out)) push(out, dequeue()) } - } def onError(e: Throwable): Unit = if (!upstreamCompleted || downstreamCanceled.isEmpty) { @@ -260,8 +257,8 @@ import org.reactivestreams.Subscription setHandler(out, this) - override def onPull(): Unit = { - try { + override def onPull(): Unit = + try if (inputBufferElements > 1) push(out, dequeue()) else if (inputBufferElements == 1) { if (upstreamCompleted) { @@ -271,10 +268,9 @@ import org.reactivestreams.Subscription } else if (upstreamCompleted) { complete(out) } - } catch { + catch { case s: SpecViolation => shell.tryAbort(s) } - } override def onDownstreamFinish(cause: Throwable): Unit = try cancel(cause) @@ -410,27 +406,25 @@ import org.reactivestreams.Subscription tryOnNext(subscriber, elem) } - private def complete(): Unit = { + private def complete(): Unit = // No need to complete if had already been cancelled, or we closed earlier if (!(upstreamCompleted || downstreamCompleted)) { upstreamCompleted = true publisher.shutdown(None) if (subscriber ne null) tryOnComplete(subscriber) } - } - def fail(e: Throwable): Unit = { + def fail(e: Throwable): Unit = // No need to fail if had already been cancelled, or we closed earlier if (!(downstreamCompleted || upstreamCompleted)) { upstreamCompleted = true publisher.shutdown(Some(e)) if ((subscriber ne null) && !e.isInstanceOf[SpecViolation]) tryOnError(subscriber, e) } - } setHandler(in, this) - override def onPush(): Unit = { + override def onPush(): Unit = try { onNext(grab(in)) if (downstreamCompleted) cancel(in, downstreamCompletionCause.get) @@ -438,7 +432,6 @@ import org.reactivestreams.Subscription } catch { case s: SpecViolation => shell.tryAbort(s) } - } override def onUpstreamFinish(): Unit = try complete() @@ -470,7 +463,7 @@ import org.reactivestreams.Subscription rejectAdditionalSubscriber(subscriber, s"${Logging.simpleName(this)}") } - def requestMore(elements: Long): Unit = { + def requestMore(elements: Long): Unit = if (elements < 1) { cancel(in, ReactiveStreamsCompliance.numberOfElementsInRequestMustBePositiveException) fail(ReactiveStreamsCompliance.numberOfElementsInRequestMustBePositiveException) @@ -480,7 +473,6 @@ import org.reactivestreams.Subscription downstreamDemand = Long.MaxValue // Long overflow, Reactive Streams Spec 3:17: effectively unbounded if (!hasBeenPulled(in) && !isClosed(in)) pull(in) } - } def cancel(cause: Throwable): Unit = { downstreamCompletionCause = Some(cause) @@ -523,7 +515,7 @@ import org.reactivestreams.Subscription extends BoundaryEvent { @InternalStableApi - override def execute(eventLimit: Int): Int = { + override def execute(eventLimit: Int): Int = if (!waitingForShutdown) { interpreter.runAsyncInput(logic, evt, promise, handler) if (eventLimit == 1 && interpreter.isSuspended) { @@ -533,7 +525,6 @@ import org.reactivestreams.Subscription } else { eventLimit } - } override def cancel(): Unit = () } @@ -642,9 +633,8 @@ import org.reactivestreams.Subscription private def canShutDown: Boolean = subscribesPending == 0 - def subscribeArrived(): Unit = { + def subscribeArrived(): Unit = subscribesPending -= 1 - } private var waitingForShutdown: Boolean = false @@ -656,7 +646,7 @@ import org.reactivestreams.Subscription else enqueueToShortCircuit(resume) } - def runBatch(actorEventLimit: Int): Int = { + def runBatch(actorEventLimit: Int): Int = try { val usingShellLimit = shellEventLimit < actorEventLimit val remainingQuota = interpreter.execute(Math.min(actorEventLimit, shellEventLimit)) @@ -679,7 +669,6 @@ import org.reactivestreams.Subscription tryAbort(e) actorEventLimit - 1 } - } /** * Attempts to abort execution, by first propagating the reason given until either @@ -713,14 +702,13 @@ import org.reactivestreams.Subscription } } - def toSnapshot: InterpreterSnapshot = { + def toSnapshot: InterpreterSnapshot = if (!isInitialized) UninitializedInterpreterImpl(logics.zipWithIndex.map { case (logic, idx) => LogicSnapshotImpl(idx, logic.toString, logic.attributes) }.toVector) else interpreter.toSnapshot - } } /** @@ -791,7 +779,7 @@ import org.reactivestreams.Subscription else if (shortCircuitBuffer != null) shortCircuitBatch() } - @tailrec private def shortCircuitBatch(): Unit = { + @tailrec private def shortCircuitBatch(): Unit = if (shortCircuitBuffer.isEmpty) () else if (currentLimit == 0) { self ! Resume @@ -804,7 +792,6 @@ import org.reactivestreams.Subscription } shortCircuitBatch() } - } private def processEvent(b: BoundaryEvent): Unit = { val shell = b.shell @@ -844,14 +831,13 @@ import org.reactivestreams.Subscription override def postStop(): Unit = { if (shortCircuitBuffer ne null) { - while (!shortCircuitBuffer.isEmpty) { + while (!shortCircuitBuffer.isEmpty) shortCircuitBuffer.poll() match { case b: BoundaryEvent => // signal to telemetry that this event won't be processed b.cancel() case _ => // ignore } - } } // avoid creating exception in happy case since it uses self.toString which is somewhat slow if (activeInterpreters.nonEmpty || newShells.nonEmpty) { diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/AggregateWithBoundary.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/AggregateWithBoundary.scala index 79b547c4db4..b7d8f707238 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/AggregateWithBoundary.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/AggregateWithBoundary.scala @@ -44,17 +44,15 @@ private[pekko] final case class AggregateWithBoundary[In, Agg, Out]( private[this] var aggregated: Agg = null.asInstanceOf[Agg] - override def preStart(): Unit = { + override def preStart(): Unit = emitOnTimer.foreach { case (_, interval) => scheduleWithFixedDelay(s"${this.getClass.getSimpleName}Timer", interval, interval) } - } - override protected def onTimer(timerKey: Any): Unit = { + override protected def onTimer(timerKey: Any): Unit = emitOnTimer.foreach { case (isReadyOnTimer, _) => if (aggregated != null && isReadyOnTimer(aggregated)) harvestAndEmit() } - } // at onPush, isAvailable(in)=true hasBeenPulled(in)=false, isAvailable(out) could be true or false due to timer triggered emit override def onPush(): Unit = { diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/ArraySource.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/ArraySource.scala index afbbbf2b3db..f99b3f35a09 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/ArraySource.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/ArraySource.scala @@ -36,7 +36,7 @@ private[pekko] final class ArraySource[T](elements: Array[T]) extends GraphStage override def preStart(): Unit = if (elements.isEmpty) completeStage() - override def onPull(): Unit = { + override def onPull(): Unit = if (index < elements.length) { push(out, elements(index)) index += 1 @@ -46,7 +46,6 @@ private[pekko] final class ArraySource[T](elements: Array[T]) extends GraphStage } else { complete(out) } - } setHandler(out, this) } diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/CollectFirst.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/CollectFirst.scala index 0f58a65bc46..b76f19ae893 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/CollectFirst.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/CollectFirst.scala @@ -46,7 +46,7 @@ private[pekko] final class CollectFirst[In, Out](pf: PartialFunction[In, Out]) e @nowarn("msg=Any") override final def onPush(): Unit = - try { + try // 1. `applyOrElse` is faster than (`pf.isDefinedAt` and then `pf.apply`) // 2. using reference comparing here instead of pattern matching can generate less and quicker bytecode, // eg: just a simple `IF_ACMPNE`, and you can find the same trick in `CollectWhile` operator. @@ -58,7 +58,7 @@ private[pekko] final class CollectFirst[In, Out](pf: PartialFunction[In, Out]) e push(out, elem) completeStage() } - } catch { + catch { case NonFatal(ex) => decider(ex) match { case Supervision.Stop => failStage(ex) diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/CollectWhile.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/CollectWhile.scala index 91ff94fb569..f9583732adb 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/CollectWhile.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/CollectWhile.scala @@ -46,7 +46,7 @@ private[pekko] final class CollectWhile[In, Out](pf: PartialFunction[In, Out]) e @nowarn("msg=Any") override final def onPush(): Unit = - try { + try // 1. `applyOrElse` is faster than (`pf.isDefinedAt` and then `pf.apply`) // 2. using reference comparing here instead of pattern matching can generate less and quicker bytecode, // eg: just a simple `IF_ACMPNE`, and you can find the same trick in `Collect` operator. @@ -56,7 +56,7 @@ private[pekko] final class CollectWhile[In, Out](pf: PartialFunction[In, Out]) e case _: NotApplied.type => completeStage() case elem: Out @unchecked => push(out, elem) } - } catch { + catch { case NonFatal(ex) => decider(ex) match { case Supervision.Stop => failStage(ex) diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/FlatMapPrefix.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/FlatMapPrefix.scala index c3672ae1eaa..63e3ad886b3 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/FlatMapPrefix.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/FlatMapPrefix.scala @@ -61,7 +61,7 @@ import pekko.util.OptionVal super.postStop() } - override def onPush(): Unit = { + override def onPush(): Unit = subSource match { case OptionVal.Some(s) => s.push(grab(in)) case _ => @@ -73,16 +73,14 @@ import pekko.util.OptionVal pull(in) } } - } - override def onUpstreamFinish(): Unit = { + override def onUpstreamFinish(): Unit = subSource match { case OptionVal.Some(s) => s.complete() case _ => materializeFlow() } - } - override def onUpstreamFailure(ex: Throwable): Unit = { + override def onUpstreamFailure(ex: Throwable): Unit = subSource match { case OptionVal.Some(s) => s.fail(ex) case _ => @@ -90,9 +88,8 @@ import pekko.util.OptionVal matPromise.failure(new NeverMaterializedException(ex)) super.onUpstreamFailure(ex) } - } - override def onPull(): Unit = { + override def onPull(): Unit = subSink match { case OptionVal.Some(s) => // delegate to subSink @@ -106,7 +103,6 @@ import pekko.util.OptionVal throw new IllegalStateException(s"Unexpected accumulated size: ${accumulated.size} (n: $n)") } } - } override def onDownstreamFinish(cause: Throwable): Unit = subSink match { @@ -135,29 +131,24 @@ import pekko.util.OptionVal subSink = OptionVal.Some(new SubSinkInlet[Out]("FlatMapPrefix.subSink")) val theSubSink = subSink.get val handler = new InHandler with OutHandler { - override def onPush(): Unit = { + override def onPush(): Unit = push(out, theSubSink.grab()) - } - override def onUpstreamFinish(): Unit = { + override def onUpstreamFinish(): Unit = complete(out) - } - override def onUpstreamFailure(ex: Throwable): Unit = { + override def onUpstreamFailure(ex: Throwable): Unit = fail(out, ex) - } - override def onPull(): Unit = { + override def onPull(): Unit = if (!isClosed(in) && !hasBeenPulled(in)) { pull(in) } - } - override def onDownstreamFinish(cause: Throwable): Unit = { + override def onDownstreamFinish(cause: Throwable): Unit = if (!isClosed(in)) { cancel(in, cause) } - } } theSubSource.setHandler(handler) diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/FutureFlow.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/FutureFlow.scala index 6535747d977..fc05120ccdc 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/FutureFlow.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/FutureFlow.scala @@ -56,7 +56,7 @@ import pekko.util.OptionVal // seems like we must set handlers BEFORE preStart setHandlers(in, out, Initializing) - override def preStart(): Unit = { + override def preStart(): Unit = futureFlow.value match { case Some(tryFlow) => Initializing.onFuture(tryFlow) @@ -66,12 +66,10 @@ import pekko.util.OptionVal // in case both ports are closed before future completion setKeepGoing(true) } - } - override def postStop(): Unit = { + override def postStop(): Unit = if (!innerMatValue.isCompleted) innerMatValue.failure(new AbruptStageTerminationException(this)) - } object Initializing extends InHandler with OutHandler { // we don't expect a push since we bever pull upstream during initialization @@ -79,9 +77,8 @@ import pekko.util.OptionVal var upstreamFailure = OptionVal.none[Throwable] - override def onUpstreamFailure(ex: Throwable): Unit = { + override def onUpstreamFailure(ex: Throwable): Unit = upstreamFailure = OptionVal.Some(ex) - } // will later be propagated to the materialized flow (by examining isClosed(in)) override def onUpstreamFinish(): Unit = {} diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/GraphInterpreter.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/GraphInterpreter.scala index b3be4fbe5bd..55311434c30 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/GraphInterpreter.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/GraphInterpreter.scala @@ -255,10 +255,10 @@ import pekko.stream.stage._ private[this] var chasedPull: Connection = NoEvent private def queueStatus: String = { - val contents = (queueHead until queueTail).map(idx => { + val contents = (queueHead until queueTail).map { idx => val conn = eventQueue(idx & mask) conn - }) + } s"(${eventQueue.length}, $queueHead, $queueTail)(${contents.mkString(", ")})" } private[this] var _Name: String = _ @@ -369,7 +369,7 @@ import pekko.stream.stage._ eventsRemaining -= 1 chaseCounter = math.min(ChaseLimit, eventsRemaining) - def reportStageError(e: Throwable): Unit = { + def reportStageError(e: Throwable): Unit = if (activeStage == null) throw e else { val loggingEnabled = activeStage.attributes.get[LogLevels] match { @@ -391,7 +391,6 @@ import pekko.stream.stage._ chasedPull = NoEvent } } - } /* * This is the "normal" event processing code which dequeues directly from the internal event queue. Since @@ -457,9 +456,8 @@ import pekko.stream.stage._ } // Event *must* be enqueued while not in the execute loop (events enqueued from external, possibly async events) chaseCounter = 0 - } finally { + } finally currentInterpreterHolder(0) = previousInterpreter - } if (Debug) println(s"$Name ---------------- $queueStatus (running=$runningStages, shutdown=$shutdownCounters)") // TODO: deadlock detection eventsRemaining @@ -610,7 +608,7 @@ import pekko.stream.stage._ else shutdownCounter(logic.stageId) &= KeepGoingMask @InternalStableApi - private[stream] def finalizeStage(logic: GraphStageLogic): Unit = { + private[stream] def finalizeStage(logic: GraphStageLogic): Unit = try { logic.postStop() logic.afterPostStop() @@ -618,21 +616,18 @@ import pekko.stream.stage._ case NonFatal(e) => log.error(e, s"Error during postStop in [{}]: {}", logic.toString, e.getMessage) } - } - private[stream] def chasePush(connection: Connection): Unit = { + private[stream] def chasePush(connection: Connection): Unit = if (chaseCounter > 0 && chasedPush == NoEvent) { chaseCounter -= 1 chasedPush = connection } else enqueue(connection) - } - private[stream] def chasePull(connection: Connection): Unit = { + private[stream] def chasePull(connection: Connection): Unit = if (chaseCounter > 0 && chasedPull == NoEvent) { chaseCounter -= 1 chasedPull = connection } else enqueue(connection) - } private[stream] def complete(connection: Connection): Unit = { val currentState = connection.portState diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/GraphStages.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/GraphStages.scala index f3319b0a7e4..03406be15b7 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/GraphStages.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/GraphStages.scala @@ -94,27 +94,24 @@ import pekko.stream.stage._ new GraphStageLogic(shape) with InHandler with OutHandler { private val contextPropagation = ContextPropagation() - def onPush(): Unit = { + def onPush(): Unit = if (isAvailable(out)) { push(out, grab(in)) tryPull(in) } else { contextPropagation.suspendContext() } - } - override def onUpstreamFinish(): Unit = { + override def onUpstreamFinish(): Unit = if (!isAvailable(in)) completeStage() - } - def onPull(): Unit = { + def onPull(): Unit = if (isAvailable(in)) { contextPropagation.resumeContext() push(out, grab(in)) if (isClosed(in)) completeStage() else pull(in) } - } setHandlers(in, out, this) @@ -160,9 +157,8 @@ import pekko.stream.stage._ cancelStage(cause) } - override def postStop(): Unit = { + override def postStop(): Unit = if (!finishPromise.isCompleted) finishPromise.failure(new AbruptStageTerminationException(this)) - } setHandlers(in, out, this) }, finishPromise.future) @@ -214,12 +210,11 @@ import pekko.stream.stage._ monitor.set(Finished) } - override def postStop(): Unit = { + override def postStop(): Unit = monitor.state match { case Finished | _: Failed => case _ => monitor.set(Failed(new AbruptStageTerminationException(this))) } - } setHandler(in, this) setHandler(out, this) @@ -353,7 +348,7 @@ import pekko.stream.stage._ super.onDownstreamFinish(cause) } - def onFutureSourceCompleted(result: Try[Graph[SourceShape[T], M]]): Unit = { + def onFutureSourceCompleted(result: Try[Graph[SourceShape[T], M]]): Unit = result .map { graph => val runnable = Source.fromGraph(graph).toMat(sinkIn.sink)(Keep.left) @@ -374,7 +369,6 @@ import pekko.stream.stage._ materialized.failure(t) failStage(t) } - } } (logic, materialized.future) @@ -390,7 +384,7 @@ import pekko.stream.stage._ override def initialAttributes: Attributes = DefaultAttributes.futureSource override def createLogic(attr: Attributes) = new GraphStageLogic(shape) with OutHandler { - override def preStart(): Unit = { + override def preStart(): Unit = future.value match { case Some(completed) => // optimization if the future is already completed @@ -399,7 +393,6 @@ import pekko.stream.stage._ val cb = getAsyncCallback[Try[T]](handle).invoke _ future.onComplete(cb)(ExecutionContexts.parasitic) } - } private def handle(result: Try[T]): Unit = result match { case scala.util.Success(null) => completeStage() @@ -443,9 +436,8 @@ import pekko.stream.stage._ promise.tryFailure(ex) } - override def postStop(): Unit = { + override def postStop(): Unit = if (!promise.isCompleted) promise.tryFailure(new AbruptStageTerminationException(this)) - } setHandler(in, this) @@ -494,9 +486,8 @@ import pekko.stream.stage._ promise.tryFailure(ex) } - override def postStop(): Unit = { + override def postStop(): Unit = if (!promise.isCompleted) promise.tryFailure(new AbruptStageTerminationException(this)) - } setHandler(in, this) } diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/MapConcat.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/MapConcat.scala index d77f02dee46..b7fc9f5e580 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/MapConcat.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/MapConcat.scala @@ -59,7 +59,7 @@ private[pekko] final class MapConcat[In, Out](f: In => IterableOnce[Out]) } catch handleException private def tryPushAndPull(): Unit = - try { + try if (hasNext) { push(out, currentIterator.next()) if (!hasNext && isClosed(in)) { @@ -67,7 +67,7 @@ private[pekko] final class MapConcat[In, Out](f: In => IterableOnce[Out]) } } else if (isClosed(in)) completeStage() else pull(in) - } catch handleException + catch handleException private def handleException: Catcher[Unit] = { case NonFatal(ex) => diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/Ops.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/Ops.scala index d892a049526..952039ca27e 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/Ops.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/Ops.scala @@ -59,17 +59,16 @@ import pekko.util.ccompat._ private def decider = inheritedAttributes.mandatoryAttribute[SupervisionStrategy].decider - override def onPush(): Unit = { - try { + override def onPush(): Unit = + try push(out, f(grab(in))) - } catch { + catch { case NonFatal(ex) => decider(ex) match { case Supervision.Stop => failStage(ex) case _ => pull(in) } } - } override def onPull(): Unit = pull(in) @@ -147,7 +146,7 @@ import pekko.util.ccompat._ def decider = inheritedAttributes.mandatoryAttribute[SupervisionStrategy].decider - override def onPush(): Unit = { + override def onPush(): Unit = try { val elem = grab(in) if (p(elem)) { @@ -163,7 +162,6 @@ import pekko.util.ccompat._ case _ => pull(in) } } - } override def onPull(): Unit = pull(in) @@ -214,9 +212,9 @@ import pekko.util.ccompat._ private lazy val decider = inheritedAttributes.mandatoryAttribute[SupervisionStrategy].decider def withSupervision[T](f: () => T): Option[T] = - try { + try Some(f()) - } catch { + catch { case NonFatal(ex) => decider(ex) match { case Supervision.Stop => onStop(ex) @@ -260,7 +258,7 @@ private[stream] object Collect { @nowarn("msg=Any") override def onPush(): Unit = - try { + try // 1. `applyOrElse` is faster than (`pf.isDefinedAt` and then `pf.apply`) // 2. using reference comparing here instead of pattern matching can generate less and quicker bytecode, // eg: just a simple `IF_ACMPNE`, and you can find the same trick in `CollectWhile` operator. @@ -270,7 +268,7 @@ private[stream] object Collect { case _: NotApplied.type => pull(in) case elem: Out @unchecked => push(out, elem) } - } catch { + catch { case NonFatal(ex) => decider(ex) match { case Supervision.Stop => failStage(ex) @@ -316,14 +314,13 @@ private[stream] object Collect { override def onUpstreamFailure(ex: Throwable): Unit = try pf.applyOrElse(ex, NotApplied) match { case _: NotApplied.type => failStage(ex) - case result: T @unchecked => { + case result: T @unchecked => if (isAvailable(out)) { push(out, result) completeStage() } else { recovered = OptionVal.Some(result) } - } case _ => throw new RuntimeException() // won't happen, compiler exhaustiveness check pleaser } catch { @@ -382,10 +379,9 @@ private[stream] object Collect { if (left <= 0) completeStage() } - override def onPull(): Unit = { + override def onPull(): Unit = if (left > 0) pull(in) else completeStage() - } setHandlers(in, out, this) } @@ -403,12 +399,11 @@ private[stream] object Collect { new GraphStageLogic(shape) with InHandler with OutHandler { private var left: Long = count - override def onPush(): Unit = { + override def onPush(): Unit = if (left > 0) { left -= 1 pull(in) } else push(out, grab(in)) - } override def onPull(): Unit = pull(in) @@ -461,7 +456,7 @@ private[stream] object Collect { override def onPull(): Unit = pull(in) - override def onPush(): Unit = { + override def onPush(): Unit = try { aggregator = f(aggregator, grab(in)) push(out, aggregator) @@ -475,7 +470,6 @@ private[stream] object Collect { push(out, aggregator) } } - } } } @@ -527,7 +521,7 @@ private[stream] object Collect { elementHandled = false } - private def safePull(): Unit = { + private def safePull(): Unit = if (isClosed(in)) { completeStage() } else if (isAvailable(out)) { @@ -535,7 +529,6 @@ private[stream] object Collect { tryPull(in) } } - } private def pushAndPullOrFinish(update: Out): Unit = { push(out, update) @@ -569,7 +562,7 @@ private[stream] object Collect { def onPull(): Unit = safePull() - def onPush(): Unit = { + def onPush(): Unit = try { elementHandled = false @@ -589,13 +582,11 @@ private[stream] object Collect { tryPull(in) elementHandled = true } - } - override def onUpstreamFinish(): Unit = { + override def onUpstreamFinish(): Unit = if (elementHandled) { completeStage() } - } override val toString: String = s"ScanAsync.Logic(completed=$elementHandled)" } @@ -644,26 +635,23 @@ private[stream] object Collect { case Supervision.Restart => aggregator = zero case _ => () } - } finally { + } finally if (!isClosed(in)) pull(in) - } } - override def onPull(): Unit = { + override def onPull(): Unit = if (isClosed(in)) { push(out, aggregator) completeStage() } else { pull(in) } - } - override def onUpstreamFinish(): Unit = { + override def onUpstreamFinish(): Unit = if (isAvailable(out)) { push(out, aggregator) completeStage() } - } setHandlers(in, out, this) } @@ -694,9 +682,8 @@ private[stream] object Collect { private var aggregator: Out = zero private var aggregating: Future[Out] = Future.successful(aggregator) - private def onRestart(@unused t: Throwable): Unit = { + private def onRestart(@unused t: Throwable): Unit = aggregator = zero - } private val futureCB = getAsyncCallback[Try[Out]] { case Success(update) if update != null => @@ -728,7 +715,7 @@ private[stream] object Collect { } }.invoke _ - def onPush(): Unit = { + def onPush(): Unit = try { aggregating = f(aggregator, grab(in)) handleAggregatingValue() @@ -736,30 +723,26 @@ private[stream] object Collect { case NonFatal(ex) => decider(ex) match { case Supervision.Stop => failStage(ex) - case supervision => { + case supervision => supervision match { case Supervision.Restart => onRestart(ex) case _ => () // just ignore on Resume } tryPull(in) - } } } - } - override def onUpstreamFinish(): Unit = { + override def onUpstreamFinish(): Unit = handleAggregatingValue() - } def onPull(): Unit = if (!hasBeenPulled(in)) tryPull(in) - private def handleAggregatingValue(): Unit = { + private def handleAggregatingValue(): Unit = aggregating.value match { case Some(result) => futureCB(result) // already completed case _ => aggregating.onComplete(futureCB)(ExecutionContexts.parasitic) } - } setHandlers(in, out, this) @@ -845,9 +828,8 @@ private[stream] object Collect { } } - override def onPull(): Unit = { + override def onPull(): Unit = pull(in) - } override def onUpstreamFinish(): Unit = { // Since the upstream has finished we have to push any buffered elements downstream. @@ -938,9 +920,8 @@ private[stream] object Collect { } } - override def onPull(): Unit = { + override def onPull(): Unit = pull(in) - } override def onUpstreamFinish(): Unit = { @@ -1041,9 +1022,8 @@ private[stream] object Collect { } } - override def preStart(): Unit = { + override def preStart(): Unit = pull(in) - } override def onPush(): Unit = { val elem = grab(in) @@ -1067,9 +1047,8 @@ private[stream] object Collect { } } - override def onUpstreamFinish(): Unit = { + override def onUpstreamFinish(): Unit = if (buffer.isEmpty) completeStage() - } setHandlers(in, out, this) } @@ -1166,11 +1145,10 @@ private[stream] object Collect { if (pending == null) pull(in) } - override def onUpstreamFinish(): Unit = { + override def onUpstreamFinish(): Unit = if (agg == null) completeStage() - } - def onPull(): Unit = { + def onPull(): Unit = if (agg == null) { if (isClosed(in)) completeStage() else if (!hasBeenPulled(in)) pull(in) @@ -1179,9 +1157,9 @@ private[stream] object Collect { push(out, agg) if (pending == null) completeStage() else { - try { + try agg = seed(pending) - } catch { + catch { case NonFatal(ex) => decider(ex) match { case Supervision.Stop => failStage(ex) @@ -1199,8 +1177,6 @@ private[stream] object Collect { if (!hasBeenPulled(in)) pull(in) } - } - private def restartState(): Unit = { agg = null.asInstanceOf[Out] left = max @@ -1242,12 +1218,11 @@ private[stream] object Collect { } else pull(in) } - override def onUpstreamFinish(): Unit = { + override def onUpstreamFinish(): Unit = if (iterator.hasNext && !expanded) () // need to wait else completeStage() - } - def onPull(): Unit = { + def onPull(): Unit = if (iterator.hasNext) { contextPropagation.resumeContext() if (!expanded) { @@ -1262,7 +1237,6 @@ private[stream] object Collect { } } else push(out, iterator.next()) } - } setHandler(in, this) setHandler(out, this) @@ -1280,7 +1254,7 @@ private[stream] object Collect { // and not calling the decider multiple times (#23888) we need to cache the decider result and re-use that private var cachedSupervisionDirective: OptionVal[Supervision.Directive] = OptionVal.None - def supervisionDirectiveFor(decider: Supervision.Decider, ex: Throwable): Supervision.Directive = { + def supervisionDirectiveFor(decider: Supervision.Decider, ex: Throwable): Supervision.Directive = cachedSupervisionDirective match { case OptionVal.Some(d) => d case _ => @@ -1288,11 +1262,9 @@ private[stream] object Collect { cachedSupervisionDirective = OptionVal.Some(d) d } - } - def setElem(t: Try[T]): Unit = { + def setElem(t: Try[T]): Unit = elem = t - } override def apply(t: Try[T]): Unit = { setElem(t) @@ -1400,11 +1372,10 @@ private[stream] object Collect { } } - private def pullIfNeeded(): Unit = { + private def pullIfNeeded(): Unit = if (isClosed(in) && buffer.isEmpty) completeStage() else if (buffer.used < parallelism && !hasBeenPulled(in)) tryPull(in) - // else already pulled and waiting for next element - } + // else already pulled and waiting for next element setHandlers(in, out, this) } @@ -1471,9 +1442,8 @@ private[stream] object Collect { if (todo < parallelism && !hasBeenPulled(in)) tryPull(in) } - override def onUpstreamFinish(): Unit = { + override def onUpstreamFinish(): Unit = if (todo == 0) completeStage() - } override def onPull(): Unit = { if (!buffer.isEmpty) push(out, buffer.dequeue()) @@ -1542,7 +1512,7 @@ private[stream] object Collect { } } - override def onPush(): Unit = { + override def onPush(): Unit = try { val elem = grab(in) if (isEnabled(logLevels.onElement)) @@ -1556,7 +1526,6 @@ private[stream] object Collect { case _ => pull(in) } } - } override def onPull(): Unit = pull(in) @@ -1615,12 +1584,11 @@ private[stream] object Collect { // do not expose private context classes (of OneBoundedInterpreter) override def getClazz(t: Materializer): Class[_] = classOf[Materializer] - override def genString(t: Materializer): String = { + override def genString(t: Materializer): String = try s"$DefaultLoggerName(${t.supervisor.path})" catch { case _: Exception => LogSource.fromString.genString(DefaultLoggerName) } - } } @@ -1662,7 +1630,7 @@ private[stream] object Collect { } } - override def onPush(): Unit = { + override def onPush(): Unit = try { val elem = grab(in) if (isEnabled(logLevels.onElement)) @@ -1676,7 +1644,6 @@ private[stream] object Collect { case _ => pull(in) } } - } override def onPull(): Unit = pull(in) @@ -1735,12 +1702,11 @@ private[stream] object Collect { // do not expose private context classes (of OneBoundedInterpreter) override def getClazz(t: Materializer): Class[_] = classOf[Materializer] - override def genString(t: Materializer): String = { + override def genString(t: Materializer): String = try s"$DefaultLoggerName(${t.supervisor.path})" catch { case _: Exception => LogSource.fromString.genString(DefaultLoggerName) } - } } @@ -1848,10 +1814,9 @@ private[stream] object Collect { } } - private def tryCloseGroup(): Unit = { + private def tryCloseGroup(): Unit = if (isAvailable(out)) emitGroup() else if (pending != null || finished) pushEagerly = true - } private def emitGroup(): Unit = { groupEmitted = true @@ -1934,7 +1899,7 @@ private[stream] object Collect { private[this] val onPushWhenBufferFull: () => Unit = overflowStrategy match { case EmitEarly => - () => { + () => if (isAvailable(out)) { if (isTimerActive(TimerName)) { cancelTimer(TimerName) @@ -1947,7 +1912,6 @@ private[stream] object Collect { throw new IllegalStateException( "Was configured to emitEarly and got element when out is not ready and buffer is full, should not be possible.") } - } case _: DropHead => () => { buffer.dropHead() @@ -1969,16 +1933,14 @@ private[stream] object Collect { grabAndPull() } case _: Fail => - () => { + () => failStage(new BufferOverflowException(s"Buffer overflow for delay operator (max capacity was: $size)!")) - } case _: Backpressure => - () => { + () => throw new IllegalStateException("Delay buffer must never overflow in Backpressure mode") - } } - def onPush(): Unit = { + def onPush(): Unit = if (buffer.isFull) onPushWhenBufferFull() else { @@ -1992,7 +1954,6 @@ private[stream] object Collect { scheduleOnce(TimerName, waitTime.millis) } } - } private def shouldPull: Boolean = buffer.used < size || !overflowStrategy.isBackpressure || @@ -2028,9 +1989,8 @@ private[stream] object Collect { def completeIfReady(): Unit = if (isClosed(in) && buffer.isEmpty) completeStage() - private def nextElementWaitTime(): Long = { + private def nextElementWaitTime(): Long = NANOSECONDS.toMillis(buffer.peek()._1 - System.nanoTime()) - } final override protected def onTimer(key: Any): Unit = { if (isAvailable(out)) @@ -2082,7 +2042,7 @@ private[pekko] object TakeWithin { private val startNanoTime = System.nanoTime() private val timeoutInNano = timeout.toNanos - def onPush(): Unit = { + def onPush(): Unit = if (System.nanoTime() - startNanoTime <= timeoutInNano) { pull(in) } else { @@ -2093,7 +2053,6 @@ private[pekko] object TakeWithin { def onPush() = push(out, grab(in)) }) } - } def onPull(): Unit = pull(in) @@ -2120,7 +2079,7 @@ private[pekko] object TakeWithin { private def decider = inheritedAttributes.mandatoryAttribute[SupervisionStrategy].decider - def setInitialInHandler(): Unit = { + def setInitialInHandler(): Unit = // Initial input handler setHandler(in, new InHandler { @@ -2133,14 +2092,13 @@ private[pekko] object TakeWithin { override def onUpstreamFinish(): Unit = failStage(new NoSuchElementException("reduce over empty stream")) }) - } @nowarn // compiler complaining about aggregator = _: T override def onPush(): Unit = { val elem = grab(in) - try { + try aggregator = f(aggregator, elem) - } catch { + catch { case NonFatal(ex) => decider(ex) match { case Supervision.Stop => failStage(ex) @@ -2150,9 +2108,8 @@ private[pekko] object TakeWithin { case _ => () } - } finally { + } finally if (!isClosed(in)) pull(in) - } } override def onPull(): Unit = pull(in) @@ -2315,11 +2272,10 @@ private[pekko] final class StatefulMap[S, In, Out](create: () => S, f: (S, In) = override def onPull(): Unit = pull(in) - override def postStop(): Unit = { + override def postStop(): Unit = if (needInvokeOnCompleteCallback) { onComplete(state) } - } setHandlers(in, out, this) } diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/StreamOfStreams.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/StreamOfStreams.scala index dc84291b2ef..64a4249e7ed 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/StreamOfStreams.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/fusing/StreamOfStreams.scala @@ -64,7 +64,7 @@ import pekko.util.ccompat.JavaConverters._ override def preStart(): Unit = queue = BufferImpl(breadth, enclosingAttributes) - def pushOut(): Unit = { + def pushOut(): Unit = queue.dequeue() match { case src: SubSinkInlet[T] @unchecked => push(out, src.grab()) @@ -76,7 +76,6 @@ import pekko.util.ccompat.JavaConverters._ case other => throw new IllegalStateException(s"Unexpected source type in queue: '${other.getClass}'") } - } override def onPush(): Unit = { val source = grab(in) @@ -89,16 +88,15 @@ import pekko.util.ccompat.JavaConverters._ pull(in) setHandler(out, new OutHandler { - override def onPull(): Unit = { + override def onPull(): Unit = // could be unavailable due to async input having been executed before this notification if (queue.nonEmpty && isAvailable(out)) pushOut() - } }) } setHandlers(in, out, this) - def addSource(source: Graph[SourceShape[T], M]): Unit = { + def addSource(source: Graph[SourceShape[T], M]): Unit = // If it's a SingleSource or wrapped such we can push the element directly instead of materializing it. // Have to use AnyRef because of OptionVal null value. TraversalBuilder.getSingleSource(source.asInstanceOf[Graph[SourceShape[AnyRef], M]]) match { @@ -112,14 +110,13 @@ import pekko.util.ccompat.JavaConverters._ case _ => val sinkIn = new SubSinkInlet[T]("FlattenMergeSink") sinkIn.setHandler(new InHandler { - override def onPush(): Unit = { + override def onPush(): Unit = if (isAvailable(out)) { push(out, sinkIn.grab()) sinkIn.pull() } else { queue.enqueue(sinkIn) } - } override def onUpstreamFinish(): Unit = if (!sinkIn.isAvailable) removeSource(sinkIn) }) sinkIn.pull() @@ -127,7 +124,6 @@ import pekko.util.ccompat.JavaConverters._ val graph = Source.fromGraph(source).to(sinkIn.sink) interpreter.subFusingMaterializer.materialize(graph, defaultAttributes = enclosingAttributes) } - } def removeSource(src: AnyRef): Unit = { val pullSuppressed = activeSources == breadth @@ -215,7 +211,7 @@ import pekko.util.ccompat.JavaConverters._ Source.fromGraph(tailSource.source) } - override def onPush(): Unit = { + override def onPush(): Unit = if (prefixComplete) { tailSource.push(grab(in)) } else { @@ -226,15 +222,13 @@ import pekko.util.ccompat.JavaConverters._ complete(out) } else pull(in) } - } - override def onPull(): Unit = { + override def onPull(): Unit = if (left == 0) { push(out, (Nil, openSubstream())) complete(out) } else pull(in) - } - override def onUpstreamFinish(): Unit = { + override def onUpstreamFinish(): Unit = if (!prefixComplete) { // This handles the unpulled out case as well emit(out, (builder.result(), Source.empty), () => completeStage()) @@ -242,19 +236,16 @@ import pekko.util.ccompat.JavaConverters._ if (!tailSource.isClosed) tailSource.complete() completeStage() } - } - override def onUpstreamFailure(ex: Throwable): Unit = { + override def onUpstreamFailure(ex: Throwable): Unit = if (prefixComplete) { if (!tailSource.isClosed) tailSource.fail(ex) completeStage() } else failStage(ex) - } - override def onDownstreamFinish(cause: Throwable): Unit = { + override def onDownstreamFinish(cause: Throwable): Unit = if (!prefixComplete) cancelStage(cause) - // Otherwise substream is open, ignore - } + // Otherwise substream is open, ignore setHandlers(in, out, this) } @@ -328,7 +319,7 @@ import pekko.util.ccompat.JavaConverters._ private def needToPull: Boolean = !(hasBeenPulled(in) || isClosed(in) || hasNextElement || substreamWaitingToBePushed.nonEmpty) - override def onPull(): Unit = { + override def onPull(): Unit = substreamWaitingToBePushed match { case Some(substreamSource) => push(out, Source.fromGraph(substreamSource.source)) @@ -343,7 +334,6 @@ import pekko.util.ccompat.JavaConverters._ } } else if (!hasBeenPulled(in)) tryPull(in) } - } override def onUpstreamFailure(ex: Throwable): Unit = fail(ex) @@ -420,12 +410,11 @@ import pekko.util.ccompat.JavaConverters._ } } - private def tryCompleteHandler(): Unit = { + private def tryCompleteHandler(): Unit = if (parent.isClosed(in) && !hasNextForSubSource) { completeSubStream() tryCompleteAll() } - } override def onPull(): Unit = { cancelTimer(key) @@ -478,9 +467,8 @@ import pekko.util.ccompat.JavaConverters._ case SubstreamCancelStrategies.Drain => Supervision.resumingDecider } - def when[T](p: T => Boolean): Graph[FlowShape[T, Source[T, NotUsed]], NotUsed] = { + def when[T](p: T => Boolean): Graph[FlowShape[T, Source[T, NotUsed]], NotUsed] = new Split(Split.SplitBefore, p) - } def after[T](p: T => Boolean): Graph[FlowShape[T, Source[T, NotUsed]], NotUsed] = new Split(Split.SplitAfter, p) @@ -520,17 +508,15 @@ import pekko.util.ccompat.JavaConverters._ case Supervision.Restart => false } - override def onPull(): Unit = { + override def onPull(): Unit = if (substreamSource eq null) { // can be already pulled from substream in case split after if (!hasBeenPulled(in)) pull(in) } else if (substreamWaitingToBePushed) pushSubstreamSource() - } - override def onDownstreamFinish(cause: Throwable): Unit = { + override def onDownstreamFinish(cause: Throwable): Unit = // If the substream is already cancelled or it has not been handed out, we can go away if ((substreamSource eq null) || substreamWaitingToBePushed || substreamCancelled) cancelStage(cause) - } override def onPush(): Unit = { val handler = new SubstreamHandler @@ -552,7 +538,7 @@ import pekko.util.ccompat.JavaConverters._ // initial input handler setHandlers(in, out, this) - private def handOver(handler: SubstreamHandler): Unit = { + private def handOver(handler: SubstreamHandler): Unit = if (isClosed(out)) completeStage() else { substreamSource = new SubSourceOutlet[T]("SplitSource") @@ -565,7 +551,6 @@ import pekko.util.ccompat.JavaConverters._ if (decision == SplitBefore || handler.hasInitialElement) pushSubstreamSource() else pull(in) } else substreamWaitingToBePushed = true } - } private def pushSubstreamSource(): Unit = { push(out, Source.fromGraph(substreamSource.source)) @@ -583,7 +568,7 @@ import pekko.util.ccompat.JavaConverters._ private var willCompleteAfterInitialElement = false // Substreams are always assumed to be pushable position when we enter this method - private def closeThis(handler: SubstreamHandler, currentElem: T): Unit = { + private def closeThis(handler: SubstreamHandler, currentElem: T): Unit = decision match { case SplitAfter => if (!substreamCancelled) { @@ -594,7 +579,6 @@ import pekko.util.ccompat.JavaConverters._ handler.firstElem = currentElem if (!substreamCancelled) substreamSource.complete() } - } override def onPull(): Unit = { cancelTimer(SubscriptionTimer) @@ -621,7 +605,7 @@ import pekko.util.ccompat.JavaConverters._ override def onPush(): Unit = { val elem = grab(in) - try { + try if (p(elem)) { val handler = new SubstreamHandler closeThis(handler, elem) @@ -636,7 +620,7 @@ import pekko.util.ccompat.JavaConverters._ if (substreamCancelled) pull(in) else substreamSource.push(elem) } - } catch { + catch { case NonFatal(ex) => decider(ex) match { case Supervision.Resume => pull(in) @@ -839,7 +823,7 @@ import pekko.util.ccompat.JavaConverters._ setHandler(out, this) - @tailrec private def setCB(cb: AsyncCallback[ActorSubscriberMessage]): Unit = { + @tailrec private def setCB(cb: AsyncCallback[ActorSubscriberMessage]): Unit = status.get match { case null => if (!status.compareAndSet(null, cb)) setCB(cb) case ActorSubscriberMessage.OnComplete => completeStage() @@ -848,7 +832,6 @@ import pekko.util.ccompat.JavaConverters._ failStage(materializationException.getOrElse(createMaterializedTwiceException())) case _ => throw new RuntimeException() // won't happen, compiler exhaustiveness check pleaser } - } override def preStart(): Unit = { val ourOwnCallback = getAsyncCallback[ActorSubscriberMessage] { diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/io/ByteStringParser.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/io/ByteStringParser.scala index c21088f8479..895df032066 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/io/ByteStringParser.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/io/ByteStringParser.scala @@ -137,7 +137,7 @@ import pekko.util.ByteString doParse() } - override def onUpstreamFinish(): Unit = { + override def onUpstreamFinish(): Unit = // If we have no a pending pull from downstream, attempt to invoke the parser again. This will handle // truncation if necessary, or complete the stage (and maybe a final emit). if (isAvailable(objOut)) doParse() @@ -146,7 +146,6 @@ import pekko.util.ByteString if (acceptUpstreamFinish) completeStage() else current.onTruncation() } - } setHandlers(bytesIn, objOut, this) } diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/io/FileOutputStage.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/io/FileOutputStage.scala index 6b29d68f84f..f5de487ac8f 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/io/FileOutputStage.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/io/FileOutputStage.scala @@ -53,7 +53,7 @@ private[pekko] final class FileOutputStage(path: Path, startPosition: Long, open private var chan: FileChannel = _ private var bytesWritten: Long = 0 - override def preStart(): Unit = { + override def preStart(): Unit = try { chan = FileChannel.open(path, openOptions.asJava) if (startPosition > 0) { @@ -65,7 +65,6 @@ private[pekko] final class FileOutputStage(path: Path, startPosition: Long, open closeFile(Some(new IOOperationIncompleteException(bytesWritten, t))) failStage(t) } - } override def onPush(): Unit = { val next = grab(in) @@ -89,15 +88,14 @@ private[pekko] final class FileOutputStage(path: Path, startPosition: Long, open completeStage() } - override def postStop(): Unit = { + override def postStop(): Unit = if (!mat.isCompleted) { val failure = new AbruptStageTerminationException(this) closeFile(Some(failure)) mat.tryFailure(failure) } - } - private def closeFile(failed: Option[Throwable]): Unit = { + private def closeFile(failed: Option[Throwable]): Unit = try { if (chan ne null) chan.close() failed match { @@ -108,7 +106,6 @@ private[pekko] final class FileOutputStage(path: Path, startPosition: Long, open case NonFatal(t) => mat.tryFailure(failed.getOrElse(t)) } - } setHandler(in, this) } diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/io/IOSources.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/io/IOSources.scala index 4a0cd6bdef1..71ebda0ca4d 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/io/IOSources.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/io/IOSources.scala @@ -36,13 +36,11 @@ private[pekko] object FileSource { val completionHandler = new CompletionHandler[Integer, Try[Int] => Unit] { - override def completed(result: Integer, attachment: Try[Int] => Unit): Unit = { + override def completed(result: Integer, attachment: Try[Int] => Unit): Unit = attachment(Success(result)) - } - override def failed(ex: Throwable, attachment: Try[Int] => Unit): Unit = { + override def failed(ex: Throwable, attachment: Try[Int] => Unit): Unit = attachment(Failure(ex)) - } } } @@ -72,7 +70,7 @@ private[pekko] final class FileSource(path: Path, chunkSize: Int, startPosition: setHandler(out, this) - override def preStart(): Unit = { + override def preStart(): Unit = try { // this is a bit weird but required to keep existing semantics if (!Files.exists(path)) throw new NoSuchFileException(path.toString) @@ -87,7 +85,6 @@ private[pekko] final class FileSource(path: Path, chunkSize: Int, startPosition: ioResultPromise.trySuccess(IOResult(position, Failure(ex))) throw ex } - } override def onPull(): Unit = { if (availableChunks.size < maxReadAhead && !eofEncountered) @@ -132,7 +129,7 @@ private[pekko] final class FileSource(path: Path, chunkSize: Int, startPosition: } } else chunks - override def onDownstreamFinish(cause: Throwable): Unit = { + override def onDownstreamFinish(cause: Throwable): Unit = cause match { case _: SubscriptionWithCancelException.NonFailureCancellation => success() @@ -141,7 +138,6 @@ private[pekko] final class FileSource(path: Path, chunkSize: Int, startPosition: new IOOperationIncompleteException("Downstream failed before reaching file end", position, ex)) completeStage() } - } override def postStop(): Unit = { ioResultPromise.trySuccess(IOResult(position, Success(Done))) diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/io/InputStreamSinkStage.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/io/InputStreamSinkStage.scala index 5e6be230fdd..34990b41899 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/io/InputStreamSinkStage.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/io/InputStreamSinkStage.scala @@ -106,9 +106,8 @@ private[stream] object InputStreamSinkStage { failStage(ex) } - override def postStop(): Unit = { + override def postStop(): Unit = if (!completionSignalled) dataQueue.add(Failed(new AbruptStageTerminationException(this))) - } setHandler(in, this) @@ -167,7 +166,7 @@ private[stream] object InputStreamSinkStage { if (isStageAlive) { detachedChunk match { case None => - try { + try sharedBuffer.poll(readTimeout.toMillis, TimeUnit.MILLISECONDS) match { case Data(data) => detachedChunk = Some(data) @@ -181,7 +180,7 @@ private[stream] object InputStreamSinkStage { case null => throw new IOException("Timeout on waiting for new data") case Initialized => throw new IllegalStateException("message 'Initialized' must come first") } - } catch { + catch { case ex: InterruptedException => throw new IOException(ex) } case Some(_) => @@ -199,15 +198,14 @@ private[stream] object InputStreamSinkStage { } @scala.throws(classOf[IOException]) - override def close(): Unit = { + override def close(): Unit = if (isActive.getAndSet(false)) { // at this point Subscriber may be already terminated if (isStageAlive) sendToStage(Close) } - } @tailrec - private[this] def getData(arr: Array[Byte], begin: Int, length: Int, gotBytes: Int): Int = { + private[this] def getData(arr: Array[Byte], begin: Int, length: Int, gotBytes: Int): Int = grabDataChunk() match { case Some(data) => val size = data.size @@ -225,9 +223,8 @@ private[stream] object InputStreamSinkStage { } case None => gotBytes } - } - private[this] def waitIfNotInitialized(): Unit = { + private[this] def waitIfNotInitialized(): Unit = if (!isInitialized) { sharedBuffer.poll(readTimeout.toMillis, TimeUnit.MILLISECONDS) match { case Initialized => isInitialized = true @@ -235,9 +232,8 @@ private[stream] object InputStreamSinkStage { case entry => require(false, s"First message must be Initialized notification, got $entry") } } - } - private[this] def grabDataChunk(): Option[ByteString] = { + private[this] def grabDataChunk(): Option[ByteString] = detachedChunk match { case None => sharedBuffer.poll() match { @@ -252,5 +248,4 @@ private[stream] object InputStreamSinkStage { } case Some(_) => detachedChunk } - } } diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/io/InputStreamSource.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/io/InputStreamSource.scala index a4f0917a8a8..1c41043019a 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/io/InputStreamSource.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/io/InputStreamSource.scala @@ -58,18 +58,17 @@ private[pekko] final class InputStreamSource(factory: () => InputStream, chunkSi override protected def logSource: Class[_] = classOf[InputStreamSource] - override def preStart(): Unit = { - try { + override def preStart(): Unit = + try inputStream = factory() - } catch { + catch { case NonFatal(t) => mat.failure(new IOOperationIncompleteException(0, t)) failStage(t) } - } override def onPull(): Unit = - try { + try inputStream.read(buffer) match { case -1 => closeStage() @@ -77,13 +76,13 @@ private[pekko] final class InputStreamSource(factory: () => InputStream, chunkSi readBytesTotal += readBytes push(out, ByteString.fromArray(buffer, 0, readBytes)) } - } catch { + catch { case NonFatal(t) => failStream(t) failStage(t) } - override def onDownstreamFinish(cause: Throwable): Unit = { + override def onDownstreamFinish(cause: Throwable): Unit = if (!isClosed) { closeInputStream() cause match { @@ -97,13 +96,11 @@ private[pekko] final class InputStreamSource(factory: () => InputStream, chunkSi ex)) } } - } - override def postStop(): Unit = { + override def postStop(): Unit = if (!isClosed) { mat.tryFailure(new AbruptStageTerminationException(this)) } - } private def closeStage(): Unit = { closeInputStream() @@ -116,16 +113,15 @@ private[pekko] final class InputStreamSource(factory: () => InputStream, chunkSi mat.tryFailure(new IOOperationIncompleteException(readBytesTotal, reason)) } - private def closeInputStream(): Unit = { - try { + private def closeInputStream(): Unit = + try if (inputStream != null) inputStream.close() - } catch { + catch { case NonFatal(ex) => mat.tryFailure(new IOOperationIncompleteException(readBytesTotal, ex)) failStage(ex) } - } setHandler(out, this) } diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/io/OutputStreamGraphStage.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/io/OutputStreamGraphStage.scala index 10ec0d545b7..d4c582af012 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/io/OutputStreamGraphStage.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/io/OutputStreamGraphStage.scala @@ -46,7 +46,7 @@ private[pekko] final class OutputStreamGraphStage(factory: () => OutputStream, a override protected def logSource: Class[_] = classOf[OutputStreamGraphStage] - override def preStart(): Unit = { + override def preStart(): Unit = try { outputStream = factory() pull(in) @@ -55,7 +55,6 @@ private[pekko] final class OutputStreamGraphStage(factory: () => OutputStream, a mat.tryFailure(new IOOperationIncompleteException(bytesWritten, t)) failStage(t) } - } override def onPush(): Unit = { val next = grab(in) @@ -72,20 +71,18 @@ private[pekko] final class OutputStreamGraphStage(factory: () => OutputStream, a } } - override def onUpstreamFailure(ex: Throwable): Unit = { + override def onUpstreamFailure(ex: Throwable): Unit = mat.tryFailure(new IOOperationIncompleteException(bytesWritten, ex)) - } - override def onUpstreamFinish(): Unit = { - try { + override def onUpstreamFinish(): Unit = + try outputStream.flush() - } catch { + catch { case NonFatal(t) => mat.tryFailure(new IOOperationIncompleteException(bytesWritten, t)) } - } - override def postStop(): Unit = { + override def postStop(): Unit = try { if (outputStream != null) { outputStream.flush() @@ -96,7 +93,6 @@ private[pekko] final class OutputStreamGraphStage(factory: () => OutputStream, a case NonFatal(t) => mat.tryFailure(new IOOperationIncompleteException(bytesWritten, t)) } - } setHandler(in, this) } diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/io/OutputStreamSourceStage.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/io/OutputStreamSourceStage.scala index d0dbb81c27e..270b7f2ba5a 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/io/OutputStreamSourceStage.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/io/OutputStreamSourceStage.scala @@ -57,14 +57,13 @@ final private[stream] class OutputStreamSourceStage(writeTimeout: FiniteDuration val upstreamCallback: AsyncCallback[AdapterToStageMessage] = getAsyncCallback(onAsyncMessage) - private def onAsyncMessage(event: AdapterToStageMessage): Unit = { + private def onAsyncMessage(event: AdapterToStageMessage): Unit = event match { case Send(data) => emit(out, data, () => semaphore.release()) case Close => completeStage() } - } setHandler(out, GraphStageLogic.EagerTerminateOutput) } @@ -86,24 +85,22 @@ private[pekko] class OutputStreamAdapter( throw new IOException("Timed out trying to write data to stream") } - try { + try Await.result(sendToStage.invokeWithFeedback(Send(data)), writeTimeout) - } catch { + catch { case NonFatal(e) => throw new IOException(e) } } @scala.throws(classOf[IOException]) - override def write(b: Int): Unit = { + override def write(b: Int): Unit = sendData(ByteString(b)) - } @scala.throws(classOf[IOException]) - override def write(b: Array[Byte], off: Int, len: Int): Unit = { + override def write(b: Array[Byte], off: Int, len: Int): Unit = if (b.nonEmpty) { sendData(ByteString.fromArray(b, off, len)) } - } @scala.throws(classOf[IOException]) override def flush(): Unit = @@ -113,11 +110,10 @@ private[pekko] class OutputStreamAdapter( () @scala.throws(classOf[IOException]) - override def close(): Unit = { - try { + override def close(): Unit = + try Await.result(sendToStage.invokeWithFeedback(Close), writeTimeout) - } catch { + catch { case NonFatal(e) => throw new IOException(e) } - } } diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/io/TcpStages.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/io/TcpStages.scala index 2054d5392fc..a909aeeccf2 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/io/TcpStages.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/io/TcpStages.scala @@ -133,10 +133,9 @@ import pekko.util.ByteString setHandler( out, new OutHandler { - override def onPull(): Unit = { + override def onPull(): Unit = // Ignore if still binding if (listener ne null) listener ! ResumeAccepting(1) - } override def onDownstreamFinish(cause: Throwable): Unit = { if (log.isDebugEnabled) { @@ -180,13 +179,12 @@ import pekko.util.ByteString StreamTcp.IncomingConnection(connected.localAddress, connected.remoteAddress, handler) } - private def tryUnbind(): Unit = { + private def tryUnbind(): Unit = if ((listener ne null) && !unbindStarted) { unbindStarted = true setKeepGoing(true) listener ! Unbind } - } private def unbindCompleted(): Unit = { stageActor.unwatch(listener) @@ -393,7 +391,7 @@ private[stream] object ConnectionSourceStage { } } - private def closeConnectionUpstreamFinished(): Unit = { + private def closeConnectionUpstreamFinished(): Unit = if (isClosed(bytesOut) || !role.halfClose) { // Reading has stopped before, either because of cancel, or PeerClosed, so just Close now // (or half-close is turned off) @@ -408,12 +406,11 @@ private[stream] object ConnectionSourceStage { else connection ! ConfirmedClose } - // Otherwise, this is an outbound connection with half-close enabled for which upstream finished - // before the connection was even established. - // In that case we half-close the connection as soon as it's connected - } + // Otherwise, this is an outbound connection with half-close enabled for which upstream finished + // before the connection was even established. + // In that case we half-close the connection as soon as it's connected - private def closeConnectionDownstreamFinished(): Unit = { + private def closeConnectionDownstreamFinished(): Unit = if (connection == null) { // This is an outbound connection for which downstream finished // before the connection was even established. @@ -428,14 +425,12 @@ private[stream] object ConnectionSourceStage { connection ! Close } } - } val readHandler = new OutHandler { - override def onPull(): Unit = { + override def onPull(): Unit = connection ! ResumeReading - } - override def onDownstreamFinish(cause: Throwable): Unit = { + override def onDownstreamFinish(cause: Throwable): Unit = cause match { case _: SubscriptionWithCancelException.NonFailureCancellation => log.debug( @@ -452,7 +447,6 @@ private[stream] object ConnectionSourceStage { connection ! Abort failStage(cause) } - } } setHandler( @@ -478,7 +472,7 @@ private[stream] object ConnectionSourceStage { override def onUpstreamFinish(): Unit = closeConnectionUpstreamFinished() - override def onUpstreamFailure(ex: Throwable): Unit = { + override def onUpstreamFailure(ex: Throwable): Unit = if (connection != null) { if (interpreter.log.isDebugEnabled) { val msg = "Aborting tcp connection to {} because of upstream failure: {}" @@ -488,7 +482,6 @@ private[stream] object ConnectionSourceStage { } connection ! Abort } else fail(ex) - } }) /** Fail stage and report to localAddressPromise if still possible */ diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/io/compression/DeflateCompressor.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/io/compression/DeflateCompressor.scala index 999f2e51a02..4bc911bd1f1 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/io/compression/DeflateCompressor.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/io/compression/DeflateCompressor.scala @@ -60,7 +60,7 @@ import pekko.util.{ ByteString, ByteStringBuilder } def close(): Unit = deflater.end() - private def newTempBuffer(size: Int = 65536): Array[Byte] = { + private def newTempBuffer(size: Int = 65536): Array[Byte] = // The default size is somewhat arbitrary, we'd like to guess a better value but Deflater/zlib // is buffering in an unpredictable manner. // `compress` will only return any data if the buffered compressed data has some size in @@ -71,7 +71,6 @@ import pekko.util.{ ByteString, ByteStringBuilder } // We also make sure that buffer size stays within a reasonable range, to avoid // draining deflator with too small buffer. new Array[Byte](math.max(size, MinBufferSize)) - } } /** INTERNAL API */ diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/streamref/SinkRefImpl.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/streamref/SinkRefImpl.scala index 4da744409d5..f217e30651d 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/streamref/SinkRefImpl.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/streamref/SinkRefImpl.scala @@ -110,7 +110,7 @@ private[stream] final class SinkRefStageImpl[In] private[pekko] (val initialPart // Complete/Fail message does, which can happen on transports such as Artery which use a dedicated lane for system messages (Terminated) private[this] var finishedWithAwaitingPartnerTermination: OptionVal[Try[Done]] = OptionVal.None - override def preStart(): Unit = { + override def preStart(): Unit = initialPartnerRef match { case OptionVal.Some(ref) => log.debug( @@ -135,8 +135,6 @@ private[stream] final class SinkRefStageImpl[In] private[pekko] (val initialPart scheduleOnce(SubscriptionTimeoutTimerKey, subscriptionTimeout.timeout) } - } - def initialReceive: ((ActorRef, Any)) => Unit = { case (_, Terminated(ref)) => log.debug( @@ -259,7 +257,7 @@ private[stream] final class SinkRefStageImpl[In] private[pekko] (val initialPart } @throws[InvalidPartnerActorException] - def observeAndValidateSender(partner: ActorRef, failureMsg: String): Unit = { + def observeAndValidateSender(partner: ActorRef, failureMsg: String): Unit = if (partnerRef.isEmpty) { partnerRef = OptionVal(partner) partner ! StreamRefsProtocol.OnSubscribeHandshake(self.ref) @@ -290,7 +288,6 @@ private[stream] final class SinkRefStageImpl[In] private[pekko] (val initialPart } // else { ref is valid } } } - } setHandler(in, this) } diff --git a/stream/src/main/scala/org/apache/pekko/stream/impl/streamref/SourceRefImpl.scala b/stream/src/main/scala/org/apache/pekko/stream/impl/streamref/SourceRefImpl.scala index 98a494de53e..5816cdc7af1 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/impl/streamref/SourceRefImpl.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/impl/streamref/SourceRefImpl.scala @@ -408,7 +408,7 @@ private[stream] final class SourceRefStageImpl[Out](val initialPartnerRef: Optio case other => throw new IllegalArgumentException(s"Unknown timer key: $other") } - override def onDownstreamFinish(cause: Throwable): Unit = { + override def onDownstreamFinish(cause: Throwable): Unit = state match { case Running(ref) => triggerCancellationExchange(ref, cause) @@ -447,7 +447,6 @@ private[stream] final class SourceRefStageImpl[Out](val initialPartnerRef: Optio // if there are elements left in the buffer we try to emit those tryPush() } - } private def triggerCancellationExchange(partner: ActorRef, cause: Throwable): Unit = { if (receiveBuffer.nonEmpty) @@ -527,14 +526,13 @@ private[stream] final class SourceRefStageImpl[Out](val initialPartnerRef: Optio } } - private def verifyPartner(sender: ActorRef, partner: ActorRef): Unit = { + private def verifyPartner(sender: ActorRef, partner: ActorRef): Unit = if (sender != partner) throw InvalidPartnerActorException( partner, sender, s"[$stageActorName] Received message from UNEXPECTED sender [$sender]! " + s"This actor is NOT our trusted remote partner, which is [$partner]. Tearing down.") - } /** @throws InvalidSequenceNumberException when sequence number is invalid */ private def observeAndValidateSequenceNr(seqNr: Long, msg: String): Unit = diff --git a/stream/src/main/scala/org/apache/pekko/stream/javadsl/BidiFlow.scala b/stream/src/main/scala/org/apache/pekko/stream/javadsl/BidiFlow.scala index 98dd59fcbb4..44fe833f96e 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/javadsl/BidiFlow.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/javadsl/BidiFlow.scala @@ -59,9 +59,8 @@ object BidiFlow { def fromFlowsMat[I1, O1, I2, O2, M1, M2, M]( flow1: Graph[FlowShape[I1, O1], M1], flow2: Graph[FlowShape[I2, O2], M2], - combine: function.Function2[M1, M2, M]): BidiFlow[I1, O1, I2, O2, M] = { + combine: function.Function2[M1, M2, M]): BidiFlow[I1, O1, I2, O2, M] = new BidiFlow(scaladsl.BidiFlow.fromFlowsMat(flow1, flow2)(combinerToScala(combine))) - } /** * Wraps two Flows to create a ''BidiFlow''. The materialized value of the resulting BidiFlow is NotUsed. diff --git a/stream/src/main/scala/org/apache/pekko/stream/javadsl/Flow.scala b/stream/src/main/scala/org/apache/pekko/stream/javadsl/Flow.scala index 245d7a2d1ed..748b9d24d64 100755 --- a/stream/src/main/scala/org/apache/pekko/stream/javadsl/Flow.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/javadsl/Flow.scala @@ -455,9 +455,8 @@ final class Flow[In, Out, Mat](delegate: scaladsl.Flow[In, Out, Mat]) extends Gr * Materializes this [[Flow]], immediately returning (1) its materialized value, and (2) a newly materialized [[Flow]]. */ def preMaterialize( - systemProvider: ClassicActorSystemProvider): pekko.japi.Pair[Mat @uncheckedVariance, Flow[In, Out, NotUsed]] = { + systemProvider: ClassicActorSystemProvider): pekko.japi.Pair[Mat @uncheckedVariance, Flow[In, Out, NotUsed]] = preMaterialize(SystemMaterializer(systemProvider.classicSystem).materializer) - } /** * Materializes this [[Flow]], immediately returning (1) its materialized value, and (2) a newly materialized [[Flow]]. @@ -1337,9 +1336,8 @@ final class Flow[In, Out, Mat](delegate: scaladsl.Flow[In, Out, Mat]) extends Gr * * See also [[Flow.take]], [[Flow.takeWithin]], [[Flow.takeWhile]] */ - def limitWeighted(n: Long, costFn: function.Function[Out, java.lang.Long]): javadsl.Flow[In, Out, Mat] = { + def limitWeighted(n: Long, costFn: function.Function[Out, java.lang.Long]): javadsl.Flow[In, Out, Mat] = new Flow(delegate.limitWeighted(n)(costFn.apply)) - } /** * Apply a sliding window over the stream and return the windows as groups of elements, with the last group @@ -4496,9 +4494,8 @@ final class Flow[In, Out, Mat](delegate: scaladsl.Flow[In, Out, Mat]) extends Gr * * @return A [[RunnableGraph]] that materializes to a Processor when run() is called on it. */ - def toProcessor: RunnableGraph[Processor[In, Out]] = { + def toProcessor: RunnableGraph[Processor[In, Out]] = RunnableGraph.fromGraph(delegate.toProcessor) - } /** * Turns a Flow into a FlowWithContext which manages a context per element along a stream. @@ -4593,9 +4590,8 @@ abstract class RunnableGraph[+Mat] extends Graph[ClosedShape, Mat] { * * Uses the system materializer. */ - def run(systemProvider: ClassicActorSystemProvider): Mat = { + def run(systemProvider: ClassicActorSystemProvider): Mat = run(SystemMaterializer(systemProvider.classicSystem).materializer) - } /** * Run this flow using a special materializer and return the materialized values of the flow. diff --git a/stream/src/main/scala/org/apache/pekko/stream/javadsl/FlowWithContext.scala b/stream/src/main/scala/org/apache/pekko/stream/javadsl/FlowWithContext.scala index f4f88063404..44aa95f8757 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/javadsl/FlowWithContext.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/javadsl/FlowWithContext.scala @@ -226,9 +226,8 @@ final class FlowWithContext[In, CtxIn, Out, CtxOut, +Mat]( def mapAsyncPartitioned[Out2, P]( parallelism: Int, partitioner: function.Function[Out, P], - f: function.Function2[Out, P, CompletionStage[Out2]]): FlowWithContext[In, CtxIn, Out2, CtxOut, Mat] = { + f: function.Function2[Out, P, CompletionStage[Out2]]): FlowWithContext[In, CtxIn, Out2, CtxOut, Mat] = viaScala(_.mapAsyncPartitioned(parallelism)(partitioner(_))(f(_, _).asScala)) - } /** * Context-preserving variant of [[pekko.stream.javadsl.Flow.mapAsyncPartitionedUnordered]]. @@ -239,9 +238,8 @@ final class FlowWithContext[In, CtxIn, Out, CtxOut, +Mat]( def mapAsyncPartitionedUnordered[Out2, P]( parallelism: Int, partitioner: function.Function[Out, P], - f: function.Function2[Out, P, CompletionStage[Out2]]): FlowWithContext[In, CtxIn, Out2, CtxOut, Mat] = { + f: function.Function2[Out, P, CompletionStage[Out2]]): FlowWithContext[In, CtxIn, Out2, CtxOut, Mat] = viaScala(_.mapAsyncPartitionedUnordered(parallelism)(partitioner(_))(f(_, _).asScala)) - } /** * Context-preserving variant of [[pekko.stream.javadsl.Flow.mapConcat]]. @@ -279,9 +277,8 @@ final class FlowWithContext[In, CtxIn, Out, CtxOut, +Mat]( * Apply the given function to each context element (leaving the data elements unchanged). */ def mapContext[CtxOut2]( - extractContext: function.Function[CtxOut, CtxOut2]): FlowWithContext[In, CtxIn, Out, CtxOut2, Mat] = { + extractContext: function.Function[CtxOut, CtxOut2]): FlowWithContext[In, CtxIn, Out, CtxOut2, Mat] = viaScala(_.mapContext(extractContext.apply)) - } /** * Context-preserving variant of [[pekko.stream.javadsl.Flow.sliding]]. diff --git a/stream/src/main/scala/org/apache/pekko/stream/javadsl/Framing.scala b/stream/src/main/scala/org/apache/pekko/stream/javadsl/Framing.scala index 6de4eeb2f31..e14679093b6 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/javadsl/Framing.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/javadsl/Framing.scala @@ -38,9 +38,8 @@ object Framing { * @param maximumFrameLength The maximum length of allowed frames while decoding. If the maximum length is * exceeded this Flow will fail the stream. */ - def delimiter(delimiter: ByteString, maximumFrameLength: Int): Flow[ByteString, ByteString, NotUsed] = { + def delimiter(delimiter: ByteString, maximumFrameLength: Int): Flow[ByteString, ByteString, NotUsed] = scaladsl.Framing.delimiter(delimiter, maximumFrameLength).asJava - } /** * Creates a Flow that handles decoding a stream of unstructured byte chunks into a stream of frames where the diff --git a/stream/src/main/scala/org/apache/pekko/stream/javadsl/Graph.scala b/stream/src/main/scala/org/apache/pekko/stream/javadsl/Graph.scala index b486112c416..ffcd99bb4cd 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/javadsl/Graph.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/javadsl/Graph.scala @@ -524,9 +524,8 @@ object ZipLatest { * '''Cancels when''' downstream cancels */ object ZipN { - def create[A](n: Int): Graph[UniformFanInShape[A, java.util.List[A]], NotUsed] = { + def create[A](n: Int): Graph[UniformFanInShape[A, java.util.List[A]], NotUsed] = ZipWithN.create(ConstantFun.javaIdentityFunction[java.util.List[A]], n) - } } /** diff --git a/stream/src/main/scala/org/apache/pekko/stream/javadsl/Hub.scala b/stream/src/main/scala/org/apache/pekko/stream/javadsl/Hub.scala index be492a1dc98..65dc285767d 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/javadsl/Hub.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/javadsl/Hub.scala @@ -63,9 +63,8 @@ object MergeHub { * @param clazz Type of elements this hub emits and consumes * @param perProducerBufferSize Buffer space used per producer. */ - def of[T](@unused clazz: Class[T], perProducerBufferSize: Int): Source[T, Sink[T, NotUsed]] = { + def of[T](@unused clazz: Class[T], perProducerBufferSize: Int): Source[T, Sink[T, NotUsed]] = pekko.stream.scaladsl.MergeHub.source[T](perProducerBufferSize).mapMaterializedValue(_.asJava[T]).asJava - } /** * Creates a [[Source]] that emits elements merged from a dynamic set of producers. After the [[Source]] returned @@ -86,7 +85,7 @@ object MergeHub { */ def withDraining[T]( @unused clazz: Class[T], - perProducerBufferSize: Int): Source[T, pekko.japi.Pair[Sink[T, NotUsed], DrainingControl]] = { + perProducerBufferSize: Int): Source[T, pekko.japi.Pair[Sink[T, NotUsed], DrainingControl]] = pekko.stream.scaladsl.MergeHub .sourceWithDraining[T](perProducerBufferSize) .mapMaterializedValue { @@ -94,7 +93,6 @@ object MergeHub { pekko.japi.Pair(sink.asJava[T], new DrainingControlImpl(draining): DrainingControl) } .asJava - } /** * Creates a [[Source]] that emits elements merged from a dynamic set of producers. After the [[Source]] returned @@ -161,9 +159,8 @@ object BroadcastHub { * concurrent consumers can be in terms of element. If the buffer is full, the producer * is backpressured. Must be a power of two and less than 4096. */ - def of[T](@unused clazz: Class[T], bufferSize: Int): Sink[T, Source[T, NotUsed]] = { + def of[T](@unused clazz: Class[T], bufferSize: Int): Sink[T, Source[T, NotUsed]] = pekko.stream.scaladsl.BroadcastHub.sink[T](bufferSize).mapMaterializedValue(_.asJava).asJava - } /** * Creates a [[Sink]] that receives elements from its upstream producer and broadcasts them to a dynamic set @@ -189,10 +186,9 @@ object BroadcastHub { * is backpressured. Must be a power of two and less than 4096. * @since 1.1.0 */ - def of[T](@unused clazz: Class[T], startAfterNrOfConsumers: Int, bufferSize: Int): Sink[T, Source[T, NotUsed]] = { + def of[T](@unused clazz: Class[T], startAfterNrOfConsumers: Int, bufferSize: Int): Sink[T, Source[T, NotUsed]] = pekko.stream.scaladsl.BroadcastHub.sink[T](startAfterNrOfConsumers, bufferSize).mapMaterializedValue( _.asJava).asJava - } /** * Creates a [[Sink]] with default buffer size 256 that receives elements from its upstream producer and broadcasts them to a dynamic set diff --git a/stream/src/main/scala/org/apache/pekko/stream/javadsl/Queue.scala b/stream/src/main/scala/org/apache/pekko/stream/javadsl/Queue.scala index 87a8dccbb7f..9407b17ec72 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/javadsl/Queue.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/javadsl/Queue.scala @@ -89,7 +89,7 @@ object SourceQueueWithComplete { /** * Converts the queue into a `scaladsl.SourceQueueWithComplete` */ - def asScala[T](queue: SourceQueueWithComplete[T]): pekko.stream.scaladsl.SourceQueueWithComplete[T] = { + def asScala[T](queue: SourceQueueWithComplete[T]): pekko.stream.scaladsl.SourceQueueWithComplete[T] = // would have been better to add `asScala` in SourceQueueWithComplete trait, but not doing // that for backwards compatibility reasons new pekko.stream.scaladsl.SourceQueueWithComplete[T] { @@ -101,7 +101,6 @@ object SourceQueueWithComplete { def fail(ex: Throwable): Unit = queue.fail(ex) } - } } /** @@ -135,7 +134,7 @@ object SinkQueueWithCancel { /** * Converts the queue into a `scaladsl.SinkQueueWithCancel` */ - def asScala[T](queue: SinkQueueWithCancel[T]): pekko.stream.scaladsl.SinkQueueWithCancel[T] = { + def asScala[T](queue: SinkQueueWithCancel[T]): pekko.stream.scaladsl.SinkQueueWithCancel[T] = // would have been better to add `asScala` in SinkQueueWithCancel trait, but not doing // that for backwards compatibility reasons new pekko.stream.scaladsl.SinkQueueWithCancel[T] { @@ -145,5 +144,4 @@ object SinkQueueWithCancel { override def cancel(): Unit = queue.cancel() } - } } diff --git a/stream/src/main/scala/org/apache/pekko/stream/javadsl/Sink.scala b/stream/src/main/scala/org/apache/pekko/stream/javadsl/Sink.scala index 4bd056d358d..14d9971761c 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/javadsl/Sink.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/javadsl/Sink.scala @@ -447,10 +447,9 @@ object Sink { first: Sink[U, M1], second: Sink[U, M2], fanOutStrategy: function.Function[java.lang.Integer, Graph[UniformFanOutShape[T, U], NotUsed]], - matF: function.Function2[M1, M2, M]): Sink[T, M] = { + matF: function.Function2[M1, M2, M]): Sink[T, M] = new Sink( scaladsl.Sink.combineMat(first.asScala, second.asScala)(size => fanOutStrategy(size))(combinerToScala(matF))) - } /** * Combine several sinks with fan-out strategy like `Broadcast` or `Balance` and returns `Sink`. diff --git a/stream/src/main/scala/org/apache/pekko/stream/javadsl/Source.scala b/stream/src/main/scala/org/apache/pekko/stream/javadsl/Source.scala index 5fdefb5081b..a186f2e7ebe 100755 --- a/stream/src/main/scala/org/apache/pekko/stream/javadsl/Source.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/javadsl/Source.scala @@ -70,7 +70,7 @@ object Source { * If the downstream of this source cancels or fails before the promise has been completed, then the promise will be completed * with an empty Optional. */ - def maybe[T]: Source[T, CompletableFuture[Optional[T]]] = { + def maybe[T]: Source[T, CompletableFuture[Optional[T]]] = new Source(scaladsl.Source.maybe[T].mapMaterializedValue { (scalaOptionPromise: Promise[Option[T]]) => val javaOptionPromise = new CompletableFuture[Optional[T]]() scalaOptionPromise.completeWith( @@ -78,7 +78,6 @@ object Source { javaOptionPromise }) - } /** * Helper to create [[Source]] from `Publisher`. @@ -731,11 +730,10 @@ object Source { @nowarn @deprecatedName(Symbol("strategy")) fanInStrategy: function.Function[java.lang.Integer, _ <: Graph[UniformFanInShape[T, U], NotUsed]], - combine: function.Function2[M1, M2, M]): Source[U, M] = { + combine: function.Function2[M1, M2, M]): Source[U, M] = new Source( scaladsl.Source.combineMat(first.asScala, second.asScala)(num => fanInStrategy.apply(num))( combinerToScala(combine))) - } /** * Combines several sources with fan-in strategy like [[Merge]] or [[Concat]] into a single [[Source]]. diff --git a/stream/src/main/scala/org/apache/pekko/stream/javadsl/SourceWithContext.scala b/stream/src/main/scala/org/apache/pekko/stream/javadsl/SourceWithContext.scala index 8478835b52f..68fd0d2e838 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/javadsl/SourceWithContext.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/javadsl/SourceWithContext.scala @@ -37,9 +37,8 @@ object SourceWithContext { /** * Creates a SourceWithContext from a regular flow that operates on `Pair` elements. */ - def fromPairs[Out, CtxOut, Mat](under: Source[Pair[Out, CtxOut], Mat]): SourceWithContext[Out, CtxOut, Mat] = { + def fromPairs[Out, CtxOut, Mat](under: Source[Pair[Out, CtxOut], Mat]): SourceWithContext[Out, CtxOut, Mat] = new SourceWithContext(scaladsl.SourceWithContext.fromTuples(under.asScala.map(_.toScala))) - } /** * Creates a SourceWithContext from an existing base SourceWithContext outputting an optional element @@ -222,9 +221,8 @@ final class SourceWithContext[+Out, +Ctx, +Mat](delegate: scaladsl.SourceWithCon def mapAsyncPartitioned[Out2, P]( parallelism: Int, partitioner: function.Function[Out, P], - f: function.Function2[Out, P, CompletionStage[Out2]]): SourceWithContext[Out2, Ctx, Mat] = { + f: function.Function2[Out, P, CompletionStage[Out2]]): SourceWithContext[Out2, Ctx, Mat] = viaScala(_.mapAsyncPartitioned(parallelism)(partitioner(_))(f(_, _).asScala)) - } /** * Context-preserving variant of [[pekko.stream.javadsl.Source.mapAsyncPartitionedUnordered]]. diff --git a/stream/src/main/scala/org/apache/pekko/stream/javadsl/SubFlow.scala b/stream/src/main/scala/org/apache/pekko/stream/javadsl/SubFlow.scala index addcc8b07b4..b385ec6e932 100755 --- a/stream/src/main/scala/org/apache/pekko/stream/javadsl/SubFlow.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/javadsl/SubFlow.scala @@ -691,9 +691,8 @@ class SubFlow[In, Out, Mat]( * * See also [[Flow.take]], [[Flow.takeWithin]], [[Flow.takeWhile]] */ - def limitWeighted(n: Long, costFn: function.Function[Out, java.lang.Long]): javadsl.SubFlow[In, Out, Mat] = { + def limitWeighted(n: Long, costFn: function.Function[Out, java.lang.Long]): javadsl.SubFlow[In, Out, Mat] = new SubFlow(delegate.limitWeighted(n)(costFn.apply)) - } /** * Apply a sliding window over the stream and return the windows as groups of elements, with the last group diff --git a/stream/src/main/scala/org/apache/pekko/stream/javadsl/SubSource.scala b/stream/src/main/scala/org/apache/pekko/stream/javadsl/SubSource.scala index ad68e3579e6..778fd4ed4f3 100755 --- a/stream/src/main/scala/org/apache/pekko/stream/javadsl/SubSource.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/javadsl/SubSource.scala @@ -697,9 +697,8 @@ class SubSource[Out, Mat]( * * See also [[Flow.take]], [[Flow.takeWithin]], [[Flow.takeWhile]] */ - def limitWeighted(n: Long, costFn: function.Function[Out, java.lang.Long]): javadsl.SubSource[Out, Mat] = { + def limitWeighted(n: Long, costFn: function.Function[Out, java.lang.Long]): javadsl.SubSource[Out, Mat] = new SubSource(delegate.limitWeighted(n)(costFn.apply)) - } def sliding(n: Int, step: Int = 1): SubSource[java.util.List[Out @uncheckedVariance], Mat] = new SubSource(delegate.sliding(n, step).map(_.asJava)) // TODO optimize to one step diff --git a/stream/src/main/scala/org/apache/pekko/stream/javadsl/Tcp.scala b/stream/src/main/scala/org/apache/pekko/stream/javadsl/Tcp.scala index 3a82dd001c7..860ab078809 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/javadsl/Tcp.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/javadsl/Tcp.scala @@ -410,7 +410,7 @@ class Tcp(system: ExtendedActorSystem) extends pekko.actor.Extension { connectTimeout: Optional[java.time.Duration], idleTimeout: Optional[java.time.Duration], verifySession: JFunction[SSLSession, Optional[Throwable]], - closing: TLSClosing): Flow[ByteString, ByteString, CompletionStage[OutgoingConnection]] = { + closing: TLSClosing): Flow[ByteString, ByteString, CompletionStage[OutgoingConnection]] = Flow.fromGraph( delegate .outgoingConnectionWithTls( @@ -427,7 +427,6 @@ class Tcp(system: ExtendedActorSystem) extends pekko.actor.Extension { }, closing) .mapMaterializedValue(_.map(new OutgoingConnection(_))(parasitic).asJava)) - } /** * Creates a [[Tcp.ServerBinding]] instance which represents a prospective TCP server binding on the given `endpoint` @@ -488,13 +487,12 @@ class Tcp(system: ExtendedActorSystem) extends pekko.actor.Extension { def bindWithTls( interface: String, port: Int, - createSSLEngine: Supplier[SSLEngine]): Source[IncomingConnection, CompletionStage[ServerBinding]] = { + createSSLEngine: Supplier[SSLEngine]): Source[IncomingConnection, CompletionStage[ServerBinding]] = Source.fromGraph( delegate .bindWithTls(interface, port, createSSLEngine = () => createSSLEngine.get()) .map(new IncomingConnection(_)) .mapMaterializedValue(_.map(new ServerBinding(_))(parasitic).asJava)) - } /** * Creates a [[Tcp.ServerBinding]] instance which represents a prospective TCP server binding on the given `endpoint` @@ -510,7 +508,7 @@ class Tcp(system: ExtendedActorSystem) extends pekko.actor.Extension { options: JIterable[SocketOption], idleTimeout: Optional[java.time.Duration], verifySession: JFunction[SSLSession, Optional[Throwable]], - closing: TLSClosing): Source[IncomingConnection, CompletionStage[ServerBinding]] = { + closing: TLSClosing): Source[IncomingConnection, CompletionStage[ServerBinding]] = Source.fromGraph( delegate .bindWithTls( @@ -528,13 +526,10 @@ class Tcp(system: ExtendedActorSystem) extends pekko.actor.Extension { closing) .map(new IncomingConnection(_)) .mapMaterializedValue(_.map(new ServerBinding(_))(parasitic).asJava)) - } - private def optionalDurationToScala(duration: Optional[java.time.Duration]) = { + private def optionalDurationToScala(duration: Optional[java.time.Duration]) = if (duration.isPresent) duration.get.asScala else Duration.Inf - } - private def durationToJavaOptional(duration: Duration): Optional[java.time.Duration] = { + private def durationToJavaOptional(duration: Duration): Optional[java.time.Duration] = if (duration.isFinite) Optional.ofNullable(duration.asJava) else Optional.empty() - } } diff --git a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Flow.scala b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Flow.scala index 372378d42b9..76608a1a8f0 100755 --- a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Flow.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Flow.scala @@ -77,7 +77,7 @@ final class Flow[-In, +Out, +Mat]( override def via[T, Mat2](flow: Graph[FlowShape[Out, T], Mat2]): Repr[T] = viaMat(flow)(Keep.left) override def viaMat[T, Mat2, Mat3](flow: Graph[FlowShape[Out, T], Mat2])( - combine: (Mat, Mat2) => Mat3): Flow[In, T, Mat3] = { + combine: (Mat, Mat2) => Mat3): Flow[In, T, Mat3] = if (this.isIdentity) { // optimization by returning flow if possible since we know Mat2 == Mat3 from flow if (combine == Keep.right) Flow.fromGraph(flow).asInstanceOf[Flow[In, T, Mat3]] @@ -106,7 +106,6 @@ final class Flow[-In, +Out, +Mat]( traversalBuilder.append(flow.traversalBuilder, flow.shape, combine), FlowShape[In, T](shape.in, flow.shape.out)) } - } /** * Connect this [[Flow]] to a [[Sink]], concatenating the processing steps of both. @@ -148,14 +147,13 @@ final class Flow[-In, +Out, +Mat]( * It is recommended to use the internally optimized `Keep.left` and `Keep.right` combiners * where appropriate instead of manually writing functions that pass through one of the values. */ - def toMat[Mat2, Mat3](sink: Graph[SinkShape[Out], Mat2])(combine: (Mat, Mat2) => Mat3): Sink[In, Mat3] = { + def toMat[Mat2, Mat3](sink: Graph[SinkShape[Out], Mat2])(combine: (Mat, Mat2) => Mat3): Sink[In, Mat3] = if (isIdentity) { new Sink(LinearTraversalBuilder.fromBuilder(sink.traversalBuilder, sink.shape, combine), SinkShape(sink.shape.in)) .asInstanceOf[Sink[In, Mat3]] } else { new Sink(traversalBuilder.append(sink.traversalBuilder, sink.shape, combine), SinkShape(shape.in)) } - } /** * Transform the materialized value of this Flow, leaving all other properties as they were. @@ -407,9 +405,8 @@ object Flow { /** * Creates a Flow from a Reactive Streams [[org.reactivestreams.Processor]] */ - def fromProcessor[I, O](processorFactory: () => Processor[I, O]): Flow[I, O, NotUsed] = { + def fromProcessor[I, O](processorFactory: () => Processor[I, O]): Flow[I, O, NotUsed] = fromProcessorMat(() => (processorFactory(), NotUsed)) - } /** * Creates a Flow from a Reactive Streams [[org.reactivestreams.Processor]] and returns a materialized value. @@ -1357,14 +1354,13 @@ trait FlowOps[+Out, +Mat] { */ def mapAsyncPartitioned[T, P](parallelism: Int)( partitioner: Out => P)( - f: (Out, P) => Future[T]): Repr[T] = { + f: (Out, P) => Future[T]): Repr[T] = (if (parallelism == 1) { via(MapAsyncUnordered(1, elem => f(elem, partitioner(elem)))) } else { via(new MapAsyncPartitioned(parallelism, orderedOutput = true, partitioner, f)) }) .withAttributes(DefaultAttributes.mapAsyncPartition and SourceLocation.forLambda(f)) - } /** * Transforms this stream. Works very similarly to [[#mapAsyncUnordered]] but with an additional @@ -1395,13 +1391,12 @@ trait FlowOps[+Out, +Mat] { */ def mapAsyncPartitionedUnordered[T, P](parallelism: Int)( partitioner: Out => P)( - f: (Out, P) => Future[T]): Repr[T] = { + f: (Out, P) => Future[T]): Repr[T] = (if (parallelism == 1) { via(MapAsyncUnordered(1, elem => f(elem, partitioner(elem)))) } else { via(new MapAsyncPartitioned(parallelism, orderedOutput = false, partitioner, f)) }).withAttributes(DefaultAttributes.mapAsyncPartitionUnordered and SourceLocation.forLambda(f)) - } /** * Use the `ask` pattern to send a request-reply message to the target `ref` actor. @@ -2456,9 +2451,8 @@ trait FlowOps[+Out, +Mat] { * @param n the number of elements to accumulate before materializing the downstream flow. * @param f a function that produces the downstream flow based on the upstream's prefix. */ - def flatMapPrefix[Out2, Mat2](n: Int)(f: immutable.Seq[Out] => Flow[Out, Out2, Mat2]): Repr[Out2] = { + def flatMapPrefix[Out2, Mat2](n: Int)(f: immutable.Seq[Out] => Flow[Out, Out2, Mat2]): Repr[Out2] = via(new FlatMapPrefix(n, f)) - } /** * This operation demultiplexes the incoming stream into separate output @@ -3157,9 +3151,8 @@ trait FlowOps[+Out, +Mat] { * * '''Cancels when''' downstream cancels */ - def zipAll[U, A >: Out](that: Graph[SourceShape[U], _], thisElem: A, thatElem: U): Repr[(A, U)] = { + def zipAll[U, A >: Out](that: Graph[SourceShape[U], _], thisElem: A, thatElem: U): Repr[(A, U)] = via(zipAllFlow(that, thisElem, thatElem)) - } protected def zipAllFlow[U, A >: Out, Mat2]( that: Graph[SourceShape[U], Mat2], @@ -4013,9 +4006,8 @@ trait FlowOpsMat[+Out, +Mat] extends FlowOps[Out, Mat] { * see [[#flatMapPrefix]] for details. */ def flatMapPrefixMat[Out2, Mat2, Mat3](n: Int)(f: immutable.Seq[Out] => Flow[Out, Out2, Mat2])( - matF: (Mat, Future[Mat2]) => Mat3): ReprMat[Out2, Mat3] = { + matF: (Mat, Future[Mat2]) => Mat3): ReprMat[Out2, Mat3] = viaMat(new FlatMapPrefix(n, f))(matF) - } /** * Combine the elements of current flow and the given [[Source]] into a stream of tuples. @@ -4042,9 +4034,8 @@ trait FlowOpsMat[+Out, +Mat] extends FlowOps[Out, Mat] { * '''Cancels when''' downstream cancels */ def zipAllMat[U, Mat2, Mat3, A >: Out](that: Graph[SourceShape[U], Mat2], thisElem: A, thatElem: U)( - matF: (Mat, Mat2) => Mat3): ReprMat[(A, U), Mat3] = { + matF: (Mat, Mat2) => Mat3): ReprMat[(A, U), Mat3] = viaMat(zipAllFlow(that, thisElem, thatElem))(matF) - } /** * Put together the elements of current flow and the given [[Source]] diff --git a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/FlowWithContextOps.scala b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/FlowWithContextOps.scala index 88848d2fca2..e32801f6a05 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/FlowWithContextOps.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/FlowWithContextOps.scala @@ -154,12 +154,11 @@ trait FlowWithContextOps[+Out, +Ctx, +Mat] { */ def mapAsyncPartitioned[Out2, P](parallelism: Int)( partitioner: Out => P)( - f: (Out, P) => Future[Out2]): Repr[Out2, Ctx] = { + f: (Out, P) => Future[Out2]): Repr[Out2, Ctx] = via(flow[Out, Ctx].mapAsyncPartitioned(parallelism)(pair => partitioner(pair._1)) { (pair, partition) => f(pair._1, partition).map((_, pair._2))(ExecutionContexts.parasitic) }) - } /** * Context-preserving variant of [[pekko.stream.scaladsl.FlowOps.mapAsyncPartitionedUnordered]]. @@ -169,12 +168,11 @@ trait FlowWithContextOps[+Out, +Ctx, +Mat] { */ def mapAsyncPartitionedUnordered[Out2, P](parallelism: Int)( partitioner: Out => P)( - f: (Out, P) => Future[Out2]): Repr[Out2, Ctx] = { + f: (Out, P) => Future[Out2]): Repr[Out2, Ctx] = via(flow[Out, Ctx].mapAsyncPartitionedUnordered(parallelism)(pair => partitioner(pair._1)) { (pair, partition) => f(pair._1, partition).map((_, pair._2))(ExecutionContexts.parasitic) }) - } /** * Context-preserving variant of [[pekko.stream.scaladsl.FlowOps.collect]]. diff --git a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Framing.scala b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Framing.scala index 18ac5f33d6f..7f6f77b95f1 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Framing.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Framing.scala @@ -138,11 +138,10 @@ object Framing { * included in this limit. */ def simpleFramingProtocol( - maximumMessageLength: Int): BidiFlow[ByteString, ByteString, ByteString, ByteString, NotUsed] = { + maximumMessageLength: Int): BidiFlow[ByteString, ByteString, ByteString, ByteString, NotUsed] = BidiFlow.fromFlowsMat( simpleFramingProtocolEncoder(maximumMessageLength), simpleFramingProtocolDecoder(maximumMessageLength))(Keep.left) - } /** * Protocol decoder that is used by [[Framing#simpleFramingProtocol]] @@ -239,15 +238,14 @@ object Framing { override def onPull(): Unit = searchIndices() - override def onUpstreamFinish(): Unit = { + override def onUpstreamFinish(): Unit = if (buffer.isEmpty) { completeStage() } else if (isAvailable(out)) { searchIndices() } // else swallow the termination and wait for pull - } - private def tryPull(): Unit = { + private def tryPull(): Unit = if (isClosed(in)) { if (allowTruncation) { push(out, buffer) @@ -255,7 +253,6 @@ object Framing { } else failStage(new FramingException("Stream finished but there was a truncated final frame in the buffer")) } else pull(in) - } @tailrec private def searchIndices(): Unit = { @@ -442,11 +439,10 @@ object Framing { } else tryPull() } - private def tryPull() = { + private def tryPull() = if (isClosed(in)) { failStage(new FramingException("Stream finished but there was a truncated final frame in the buffer")) } else pull(in) - } override def onPush(): Unit = { buffer ++= grab(in) @@ -455,13 +451,12 @@ object Framing { override def onPull() = tryPushFrame() - override def onUpstreamFinish(): Unit = { + override def onUpstreamFinish(): Unit = if (buffer.isEmpty) { completeStage() } else if (isAvailable(out)) { tryPushFrame() } // else swallow the termination and wait for pull - } setHandlers(in, out, this) } diff --git a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Graph.scala b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Graph.scala index bf28108523e..49fd8bb516e 100755 --- a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Graph.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Graph.scala @@ -147,14 +147,13 @@ final class Merge[T](val inputPorts: Int, val eagerComplete: Boolean) extends Gr setHandler( i, new InHandler { - override def onPush(): Unit = { + override def onPush(): Unit = if (isAvailable(out)) { // isAvailable(out) implies !pending // -> grab and push immediately push(out, grab(i)) tryPull(i) } else pendingQueue.enqueue(i) - } override def onUpstreamFinish() = if (eagerComplete) { @@ -172,10 +171,9 @@ final class Merge[T](val inputPorts: Int, val eagerComplete: Boolean) extends Gr }) } - override def onPull(): Unit = { + override def onPull(): Unit = if (pending) dequeueAndDispatch() - } setHandler(out, this) } @@ -238,17 +236,16 @@ final class MergePreferred[T](val secondaryPorts: Int, val eagerComplete: Boolea if (eagerComplete || openInputs == 0) completeStage() } - override def preStart(): Unit = { + override def preStart(): Unit = // while initializing this `MergePreferredShape`, the `preferred` port gets added to `inlets` by side-effect. shape.inlets.foreach(tryPull) - } setHandler(out, eagerTerminateOutput) - val pullMe = Array.tabulate(secondaryPorts)(i => { + val pullMe = Array.tabulate(secondaryPorts) { i => val port = in(i) () => tryPull(port) - }) + } /* * This determines the unfairness of the merge: @@ -296,12 +293,11 @@ final class MergePreferred[T](val secondaryPorts: Int, val eagerComplete: Boolea setHandler( port, new InHandler { - override def onPush(): Unit = { + override def onPush(): Unit = if (preferredEmitting > 0) () // blocked else { emit(out, grab(port), pullPort) } - } override def onUpstreamFinish(): Unit = onComplete() }) i += 1 @@ -358,14 +354,13 @@ final class MergePrioritized[T] private (val priorities: Seq[Int], val eagerComp setHandler( inlet, new InHandler { - override def onPush(): Unit = { + override def onPush(): Unit = if (isAvailable(out) && !hasOtherInletAvailable(inlet)) { push(out, grab(inlet)) tryPull(inlet) } - } - override def onUpstreamFinish(): Unit = { + override def onUpstreamFinish(): Unit = if (eagerComplete) { in.foreach(cancel(_)) runningUpstreams = 0 @@ -374,7 +369,6 @@ final class MergePrioritized[T] private (val priorities: Seq[Int], val eagerComp runningUpstreams -= 1 if (upstreamsClosed && !hasPending) completeStage() } - } }) } @@ -509,7 +503,7 @@ final class Interleave[T](val inputPorts: Int, val segmentSize: Int, val eagerCl if (counter == segmentSize) switchToNextInput() } - override def onUpstreamFinish(): Unit = { + override def onUpstreamFinish(): Unit = if (!eagerClose) { runningUpstreams -= 1 if (!upstreamsClosed) { @@ -519,7 +513,6 @@ final class Interleave[T](val inputPorts: Int, val segmentSize: Int, val eagerCl } } else completeStage() } else completeStage() - } }) } @@ -667,7 +660,7 @@ final class Broadcast[T](val outputPorts: Int, val eagerCancel: Boolean) extends tryPull() } - override def onDownstreamFinish(cause: Throwable) = { + override def onDownstreamFinish(cause: Throwable) = if (eagerCancel) cancelStage(cause) else { downstreamsRunning -= 1 @@ -678,7 +671,6 @@ final class Broadcast[T](val outputPorts: Int, val eagerCancel: Boolean) extends tryPull() } } - } }) idx += 1 } @@ -734,33 +726,29 @@ private[stream] final class WireTap[T] extends GraphStage[FanOutShape2[T, T, T]] pendingTap = Some(elem) } } - override def onPull(): Unit = { + override def onPull(): Unit = pull(in) - } - override def onDownstreamFinish(cause: Throwable): Unit = { + override def onDownstreamFinish(cause: Throwable): Unit = cancelStage(cause) - } // The 'tap' output can neither backpressure, nor cancel, the stage. setHandler( outTap, new OutHandler { - override def onPull() = { + override def onPull() = pendingTap match { case Some(elem) => push(outTap, elem) pendingTap = None case None => // no pending element to emit } - } override def onDownstreamFinish(cause: Throwable): Unit = { setHandler(in, new InHandler { - override def onPush() = { + override def onPush() = push(outMain, grab(in)) - } }) // Allow any outstanding element to be garbage-collected pendingTap = None @@ -858,14 +846,12 @@ final class Partition[T](val outputPorts: Int, val partitioner: T => Int, val ea } } - private def pullIfAnyOutIsAvailable(): Unit = { + private def pullIfAnyOutIsAvailable(): Unit = if (out.exists(isAvailable(_))) pull(in) - } - override def onUpstreamFinish(): Unit = { + override def onUpstreamFinish(): Unit = if (outPendingElem == null) completeStage() - } setHandler(in, this) @@ -874,7 +860,7 @@ final class Partition[T](val outputPorts: Int, val partitioner: T => Int, val ea setHandler( o, new OutHandler { - override def onPull() = { + override def onPull() = if (outPendingElem != null) { val elem = outPendingElem.asInstanceOf[T] if (idx == outPendingIdx) { @@ -887,7 +873,6 @@ final class Partition[T](val outputPorts: Int, val partitioner: T => Int, val ea } } else if (!hasBeenPulled(in)) pull(in) - } override def onDownstreamFinish(cause: Throwable) = if (eagerCancel) cancelStage(cause) @@ -1006,7 +991,7 @@ final class Balance[T](val outputPorts: Int, val waitForAllDownstreams: Boolean, } else pendingQueue.enqueue(o) } - override def onDownstreamFinish(cause: Throwable) = { + override def onDownstreamFinish(cause: Throwable) = if (eagerCancel) cancelStage(cause) else { downstreamsRunning -= 1 @@ -1016,7 +1001,6 @@ final class Balance[T](val outputPorts: Int, val waitForAllDownstreams: Boolean, if (needDownstreamPulls == 0 && !hasBeenPulled(in)) pull(in) } } - } }) } } @@ -1245,9 +1229,8 @@ class ZipWithN[A, O](zipper: immutable.Seq[A] => O)(n: Int) extends GraphStage[U else shape.inlets.foreach(pullInlet) } - override def preStart(): Unit = { + override def preStart(): Unit = shape.inlets.foreach(pullInlet) - } shape.inlets.zipWithIndex.foreach { case (in, i) => @@ -1299,10 +1282,9 @@ object Concat { * @return */ def apply[T](inputPorts: Int, detachedInputs: Boolean): Graph[UniformFanInShape[T, T], NotUsed] = { - val concat = { + val concat = if (inputPorts == 2) concatTwo[T] else new Concat[T](inputPorts) - } if (detachedInputs) GraphStages.withDetachedInputs(concat) else concat @@ -1344,11 +1326,10 @@ final class Concat[T](val inputPorts: Int) extends GraphStage[UniformFanInShape[ setHandler( i, new InHandler { - override def onPush() = { + override def onPush() = push(out, grab(i)) - } - override def onUpstreamFinish() = { + override def onUpstreamFinish() = if (idx == activeStream) { activeStream += 1 // Skip closed inputs @@ -1356,7 +1337,6 @@ final class Concat[T](val inputPorts: Int) extends GraphStage[UniformFanInShape[ if (activeStream == inputPorts) completeStage() else if (isAvailable(out)) pull(in(activeStream)) } - } }) idxx += 1 } @@ -1413,9 +1393,8 @@ private[stream] final class OrElse[T] extends GraphStage[UniformFanInShape[T, T] private[this] var currentIn = primary private[this] var primaryPushed = false - override def onPull(): Unit = { + override def onPull(): Unit = pull(currentIn) - } // for the primary inHandler override def onPush(): Unit = { @@ -1428,24 +1407,21 @@ private[stream] final class OrElse[T] extends GraphStage[UniformFanInShape[T, T] } // for the primary inHandler - override def onUpstreamFinish(): Unit = { + override def onUpstreamFinish(): Unit = if (!primaryPushed && !isClosed(secondary)) { currentIn = secondary if (isAvailable(out)) pull(secondary) } else { completeStage() } - } setHandler(secondary, new InHandler { - override def onPush(): Unit = { + override def onPush(): Unit = push(out, grab(secondary)) - } - override def onUpstreamFinish(): Unit = { + override def onUpstreamFinish(): Unit = if (isClosed(primary)) completeStage() - } }) setHandlers(primary, out, this) @@ -1733,20 +1709,18 @@ object GraphDSL extends GraphApply { object Implicits { @tailrec - private[stream] def findOut[I, O](b: Builder[_], junction: UniformFanOutShape[I, O], n: Int): Outlet[O] = { + private[stream] def findOut[I, O](b: Builder[_], junction: UniformFanOutShape[I, O], n: Int): Outlet[O] = if (n == junction.outlets.length) throw new IllegalArgumentException(s"no more outlets free on $junction") else if (!b.traversalBuilder.isUnwired(junction.out(n))) findOut(b, junction, n + 1) else junction.out(n) - } @tailrec - private[stream] def findIn[I, O](b: Builder[_], junction: UniformFanInShape[I, O], n: Int): Inlet[I] = { + private[stream] def findIn[I, O](b: Builder[_], junction: UniformFanInShape[I, O], n: Int): Inlet[I] = if (n == junction.inlets.length) throw new IllegalArgumentException(s"no more inlets free on $junction") else if (!b.traversalBuilder.isUnwired(junction.in(n))) findIn(b, junction, n + 1) else junction.in(n) - } sealed trait CombinerBase[+T] extends Any { def importAndGetPort(b: Builder[_]): Outlet[T @uncheckedVariance] @@ -1761,12 +1735,11 @@ object GraphDSL extends GraphApply { } def ~>[Out](junction: UniformFanInShape[T, Out])(implicit b: Builder[_]): PortOps[Out] = { - def bind(n: Int): Unit = { + def bind(n: Int): Unit = if (n == junction.inlets.length) throw new IllegalArgumentException(s"no more inlets free on $junction") else if (!b.traversalBuilder.isUnwired(junction.in(n))) bind(n + 1) else b.addEdge(importAndGetPort(b), junction.in(n)) - } bind(0) junction.out } @@ -1804,12 +1777,11 @@ object GraphDSL extends GraphApply { } def <~[In](junction: UniformFanOutShape[In, T])(implicit b: Builder[_]): ReversePortOps[In] = { - def bind(n: Int): Unit = { + def bind(n: Int): Unit = if (n == junction.outlets.length) throw new IllegalArgumentException(s"no more outlets free on $junction") else if (!b.traversalBuilder.isUnwired(junction.out(n))) bind(n + 1) else b.addEdge(junction.out(n), importAndGetPortReverse(b)) - } bind(0) junction.in } @@ -1858,9 +1830,8 @@ object GraphDSL extends GraphApply { override def via[T, Mat2](flow: Graph[FlowShape[Out, T], Mat2]): Repr[T] = super.~>(flow)(b) - def to[Mat2](sink: Graph[SinkShape[Out], Mat2]): Closed = { + def to[Mat2](sink: Graph[SinkShape[Out], Mat2]): Closed = super.~>(sink)(b) - } } private class DisabledPortOps[Out](msg: String) extends PortOpsImpl[Out](null, null) { diff --git a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Hub.scala b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Hub.scala index cf3a9710e86..83a744837d1 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Hub.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Hub.scala @@ -131,9 +131,8 @@ object MergeHub { */ @InternalApi private[pekko] final class MergeHubDrainingControlImpl(drainAction: () => Unit) extends MergeHub.DrainingControl { - override def drainAndComplete(): Unit = { + override def drainAndComplete(): Unit = drainAction() - } } private[pekko] class MergeHub[T](perProducerBufferSize: Int, drainingEnabled: Boolean = false) @@ -187,7 +186,7 @@ private[pekko] class MergeHub[T](perProducerBufferSize: Int, drainingEnabled: Bo // We are only allowed to dequeue if we are not backpressured. See comment in tryProcessNext() for details. if (isAvailable(out)) tryProcessNext(firstAttempt = true)) - private[MergeHub] val drainingCallback: Option[AsyncCallback[NotUsed]] = { + private[MergeHub] val drainingCallback: Option[AsyncCallback[NotUsed]] = // Only create an async callback if the draining support is enabled in order to avoid book-keeping costs. if (drainingEnabled) { Some(getAsyncCallback[NotUsed] { _ => @@ -195,7 +194,6 @@ private[pekko] class MergeHub[T](perProducerBufferSize: Int, drainingEnabled: Bo tryCompleteOnDraining() }) } else None - } setHandler(out, this) @@ -214,11 +212,10 @@ private[pekko] class MergeHub[T](perProducerBufferSize: Int, drainingEnabled: Bo true } - private def tryCompleteOnDraining(): Unit = { + private def tryCompleteOnDraining(): Unit = if (demands.isEmpty && (queue.peek() eq null)) { completeStage() } - } override def onPull(): Unit = tryProcessNext(firstAttempt = true) @@ -300,9 +297,8 @@ private[pekko] class MergeHub[T](perProducerBufferSize: Int, drainingEnabled: Bo // Kill everyone else val states = demands.valuesIterator - while (states.hasNext) { + while (states.hasNext) states.next().close() - } } } @@ -323,7 +319,7 @@ private[pekko] class MergeHub[T](perProducerBufferSize: Int, drainingEnabled: Bo private[this] var demand: Long = perProducerBufferSize private[this] val id = idCounter.getAndIncrement() - override def preStart(): Unit = { + override def preStart(): Unit = if (!logic.isDraining && !logic.isShuttingDown) { logic.enqueue(Register(id, getAsyncCallback(onDemand))) @@ -338,11 +334,9 @@ private[pekko] class MergeHub[T](perProducerBufferSize: Int, drainingEnabled: Bo } else { completeStage() } - } - override def postStop(): Unit = { + override def postStop(): Unit = // Unlike in the case of preStart, we don't care about the Hub no longer looking at the queue. if (!logic.isShuttingDown) logic.enqueue(Deregister(id)) - } override def onPush(): Unit = { logic.enqueue(Element(id, grab(in))) @@ -355,20 +349,18 @@ private[pekko] class MergeHub[T](perProducerBufferSize: Int, drainingEnabled: Bo } // Make some noise - override def onUpstreamFailure(ex: Throwable): Unit = { + override def onUpstreamFailure(ex: Throwable): Unit = throw new MergeHub.ProducerFailed( "Upstream producer failed with exception, " + "removing from MergeHub now", ex) - } - private def onDemand(moreDemand: Long): Unit = { + private def onDemand(moreDemand: Long): Unit = if (moreDemand == MergeHub.Cancel) completeStage() else { demand += moreDemand if (!hasBeenPulled(in)) pullWithDemand() } - } setHandler(in, this) } @@ -555,13 +547,12 @@ private[pekko] class BroadcastHub[T](startAfterNrOfConsumers: Int, bufferSize: I if (!isFull) pull(in) } - private def tryPull(): Unit = { + private def tryPull(): Unit = if (initialized && !isClosed(in) && !hasBeenPulled(in) && !isFull) { pull(in) } - } - private def onEvent(ev: HubEvent): Unit = { + private def onEvent(ev: HubEvent): Unit = ev match { case Advance(id, previousOffset) => val newOffset = previousOffset + DemandThreshold @@ -615,7 +606,6 @@ private[pekko] class BroadcastHub[T](startAfterNrOfConsumers: Int, bufferSize: I } else checkUnblock(previousOffset) } - } // Producer API // We are full if the distance between the slowest (known) consumer and the fastest (known) consumer is @@ -665,12 +655,11 @@ private[pekko] class BroadcastHub[T](startAfterNrOfConsumers: Int, bufferSize: I * After removing a Consumer from a wheel slot (because it cancelled, or we moved it because it advanced) * we need to check if it was blocking us from advancing (being the slowest). */ - private def checkUnblock(offsetOfConsumerRemoved: Int): Unit = { + private def checkUnblock(offsetOfConsumerRemoved: Int): Unit = if (unblockIfPossible(offsetOfConsumerRemoved)) { if (isClosed(in)) complete() else tryPull() } - } private def unblockIfPossible(offsetOfConsumerRemoved: Int): Boolean = { var unblocked = false @@ -739,10 +728,9 @@ private[pekko] class BroadcastHub[T](startAfterNrOfConsumers: Int, bufferSize: I } // Consumer API - def poll(offset: Int): AnyRef = { + def poll(offset: Int): AnyRef = if (offset == tail) null else queue(offset & Mask) - } setHandler(in, this) @@ -792,7 +780,7 @@ private[pekko] class BroadcastHub[T](startAfterNrOfConsumers: Int, bufferSize: I failStage(ex) } - @tailrec def register(): Unit = { + @tailrec def register(): Unit = logic.state.get() match { case Closed(Some(ex)) => failStage(ex) case Closed(None) => completeStage() @@ -802,7 +790,6 @@ private[pekko] class BroadcastHub[T](startAfterNrOfConsumers: Int, bufferSize: I callbackFuture.onComplete(getAsyncCallback(onHubReady).invoke)(materializer.executionContext) } else register() } - } /* * Note that there is a potential race here. First we add ourselves to the pending registrations, then @@ -815,7 +802,7 @@ private[pekko] class BroadcastHub[T](startAfterNrOfConsumers: Int, bufferSize: I } - override def onPull(): Unit = { + override def onPull(): Unit = if (offsetInitialized && (hubCallback ne null)) { val elem = logic.poll(offset) @@ -838,12 +825,10 @@ private[pekko] class BroadcastHub[T](startAfterNrOfConsumers: Int, bufferSize: I } } } - } - override def postStop(): Unit = { + override def postStop(): Unit = if (hubCallback ne null) hubCallback.invoke(UnRegister(id, previousPublishedOffset, offset)) - } private def onCommand(cmd: ConsumerEvent): Unit = cmd match { case HubCompleted(Some(ex)) => failStage(ex) @@ -1051,12 +1036,11 @@ object PartitionHub { private val queues2 = new ConcurrentHashMap[Long, ConsumerQueue] private val _totalSize = new AtomicInteger - override def init(id: Long): Unit = { + override def init(id: Long): Unit = if (id < FixedQueues) queues1.set(id.toInt, ConsumerQueue.empty) else queues2.put(id, ConsumerQueue.empty) - } override def totalSize: Int = _totalSize.get @@ -1130,13 +1114,12 @@ object PartitionHub { if (id < FixedQueues) poll1() else poll2() } - override def remove(id: Long): Unit = { + override def remove(id: Long): Unit = (if (id < FixedQueues) queues1.getAndSet(id.toInt, null) else queues2.remove(id)) match { case null => case queue => _totalSize.addAndGet(-queue.size) } - } } } @@ -1214,11 +1197,10 @@ object PartitionHub { if (!isFull) pull(in) } - private def isFull: Boolean = { + private def isFull: Boolean = (queue.totalSize + pending.size) >= bufferSize - } - private def publish(elem: T): Unit = { + private def publish(elem: T): Unit = if (!initialized || consumerInfo.consumers.isEmpty) { // will be published when first consumers are registered pending :+= elem @@ -1229,34 +1211,30 @@ object PartitionHub { wakeup(id) } } - } - private def wakeup(id: Long): Unit = { + private def wakeup(id: Long): Unit = needWakeup.get(id) match { case None => // ignore case Some(consumer) => needWakeup -= id consumer.callback.invoke(Wakeup) } - } - override def onUpstreamFinish(): Unit = { + override def onUpstreamFinish(): Unit = if (consumerInfo.consumers.isEmpty) completeStage() else { consumerInfo.consumers.foreach(c => complete(c.id)) } - } private def complete(id: Long): Unit = { queue.offer(id, Completed) wakeup(id) } - private def tryPull(): Unit = { + private def tryPull(): Unit = if (initialized && !isClosed(in) && !hasBeenPulled(in) && !isFull) pull(in) - } private def onEvent(ev: HubEvent): Unit = { callbackCount += 1 @@ -1377,7 +1355,7 @@ object PartitionHub { failStage(ex) } - @tailrec def register(): Unit = { + @tailrec def register(): Unit = logic.state.get() match { case Closed(Some(ex)) => failStage(ex) case Closed(None) => completeStage() @@ -1387,13 +1365,12 @@ object PartitionHub { callbackFuture.onComplete(getAsyncCallback(onHubReady).invoke)(materializer.executionContext) } else register() } - } register() } - override def onPull(): Unit = { + override def onPull(): Unit = if (hubCallback ne null) { val elem = logic.poll(id, hubCallback) @@ -1406,12 +1383,10 @@ object PartitionHub { push(out, elem.asInstanceOf[T]) } } - } - override def postStop(): Unit = { + override def postStop(): Unit = if (hubCallback ne null) hubCallback.invoke(UnRegister(id)) - } private def onCommand(cmd: ConsumerEvent): Unit = { callbackCount += 1 diff --git a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/JsonFraming.scala b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/JsonFraming.scala index b77470ff70c..cab64098672 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/JsonFraming.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/JsonFraming.scala @@ -76,14 +76,13 @@ object JsonFraming { override def onPull(): Unit = tryPopBuffer() - override def onUpstreamFinish(): Unit = { + override def onUpstreamFinish(): Unit = buffer.poll() match { case Some(json) => emit(out, json) case _ => complete() } - } - def tryPopBuffer(): Unit = { + def tryPopBuffer(): Unit = try buffer.poll() match { case Some(json) => push(out, json) case _ => if (isClosed(in)) complete() else pull(in) @@ -91,7 +90,6 @@ object JsonFraming { catch { case NonFatal(ex) => failStage(ex) } - } def complete(): Unit = if (buffer.canComplete) completeStage() diff --git a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/MergeLatest.scala b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/MergeLatest.scala index 93ec3597f8d..21bf9334410 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/MergeLatest.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/MergeLatest.scala @@ -74,12 +74,11 @@ final class MergeLatest[T, M](val inputPorts: Int, val eagerClose: Boolean)(buil tryPull(input) } - override def onUpstreamFinish(): Unit = { + override def onUpstreamFinish(): Unit = if (!eagerClose) { runningUpstreams -= 1 if (upstreamsClosed) completeStage() } else completeStage() - } }) } diff --git a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/RestartFlow.scala b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/RestartFlow.scala index a257876d85e..a2aa4db4140 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/RestartFlow.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/RestartFlow.scala @@ -284,7 +284,7 @@ private abstract class RestartWithBackoffLogic[S <: Shape]( sinkIn.setHandler(new InHandler { override def onPush() = push(out, sinkIn.grab()) - override def onUpstreamFinish() = { + override def onUpstreamFinish() = if (finishing || maxRestartsReached() || onlyOnFailures) { complete(out) } else { @@ -294,19 +294,17 @@ private abstract class RestartWithBackoffLogic[S <: Shape]( minLogLevel = Logging.InfoLevel) scheduleRestartTimer() } - } /* * Upstream in this context is the wrapped stage. */ - override def onUpstreamFailure(ex: Throwable) = { + override def onUpstreamFailure(ex: Throwable) = if (finishing || maxRestartsReached() || !settings.restartOn(ex)) { fail(out, ex) } else { logIt(s"Restarting stream due to failure [${restartCount + 1}]: $ex", OptionVal.Some(ex)) scheduleRestartTimer() } - } }) setHandler(out, @@ -329,7 +327,7 @@ private abstract class RestartWithBackoffLogic[S <: Shape]( private def logIt( message: String, exc: OptionVal[Throwable], - minLogLevel: Logging.LogLevel = Logging.ErrorLevel): Unit = { + minLogLevel: Logging.LogLevel = Logging.ErrorLevel): Unit = if (loggingEnabled) { logLevel(minLogLevel) match { case Logging.ErrorLevel => @@ -351,7 +349,6 @@ private abstract class RestartWithBackoffLogic[S <: Shape]( case _ => // off } } - } /** * @param in The permanent inlet for this operator @@ -376,13 +373,12 @@ private abstract class RestartWithBackoffLogic[S <: Shape]( * Can either be a failure or a cancel in the wrapped state. * onlyOnFailures is thus racy so a delay to cancellation is added in the case of a flow. */ - override def onDownstreamFinish(cause: Throwable) = { + override def onDownstreamFinish(cause: Throwable) = if (finishing || maxRestartsReached() || onlyOnFailures || !settings.restartOn(cause)) { cancel(in, cause) } else { scheduleRestartTimer() } - } }) setHandler( diff --git a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/RestartSink.scala b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/RestartSink.scala index 02743ce1ef6..15fae8d95ee 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/RestartSink.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/RestartSink.scala @@ -133,9 +133,8 @@ private final class RestartWithBackoffSink[T](sinkFactory: () => Sink[T, _], res subFusingMaterializer.materialize(Source.fromGraph(sourceOut.source).to(sinkFactory()), inheritedAttributes) } - override protected def backoff() = { + override protected def backoff() = setHandler(in, GraphStageLogic.EagerTerminateInput) - } backoff() } diff --git a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/RestartSource.scala b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/RestartSource.scala index aba594accd0..549194604db 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/RestartSource.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/RestartSource.scala @@ -209,9 +209,8 @@ private final class RestartWithBackoffSource[T]( } } - override protected def backoff() = { + override protected def backoff() = setHandler(out, GraphStageLogic.EagerTerminateOutput) - } backoff() } diff --git a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Sink.scala b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Sink.scala index cf8b7151d12..c1e072569f1 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Sink.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Sink.scala @@ -231,12 +231,11 @@ object Sink { * * See also [[lastOption]], [[takeLast]]. */ - def last[T]: Sink[T, Future[T]] = { + def last[T]: Sink[T, Future[T]] = Sink.fromGraph(new TakeLastStage[T](1)).withAttributes(DefaultAttributes.lastSink).mapMaterializedValue { e => e.map(_.headOption.getOrElse(throw new NoSuchElementException("last of empty stream")))( ExecutionContexts.parasitic) } - } /** * A `Sink` that materializes into a `Future` of the optional last value received. @@ -245,11 +244,10 @@ object Sink { * * See also [[last]], [[takeLast]]. */ - def lastOption[T]: Sink[T, Future[Option[T]]] = { + def lastOption[T]: Sink[T, Future[Option[T]]] = Sink.fromGraph(new TakeLastStage[T](1)).withAttributes(DefaultAttributes.lastOptionSink).mapMaterializedValue { e => e.map(_.headOption)(ExecutionContexts.parasitic) } - } /** * A `Sink` that materializes into a `Future` of `immutable.Seq[T]` containing the last `n` collected elements. @@ -359,7 +357,7 @@ object Sink { * @since 1.1.0 */ def combineMat[T, U, M1, M2, M](first: Sink[U, M1], second: Sink[U, M2])( - fanOutStrategy: Int => Graph[UniformFanOutShape[T, U], NotUsed])(matF: (M1, M2) => M): Sink[T, M] = { + fanOutStrategy: Int => Graph[UniformFanOutShape[T, U], NotUsed])(matF: (M1, M2) => M): Sink[T, M] = Sink.fromGraph(GraphDSL.createGraph(first, second)(matF) { implicit b => (shape1, shape2) => import GraphDSL.Implicits._ val d = b.add(fanOutStrategy(2)) @@ -367,7 +365,6 @@ object Sink { d.out(1) ~> shape2 new SinkShape[T](d.in) }) - } /** * Combine several sinks with fan-out strategy like `Broadcast` or `Balance` and returns `Sink`. @@ -518,7 +515,7 @@ object Sink { */ def onComplete[T](callback: Try[Done] => Unit): Sink[T, NotUsed] = { - def newOnCompleteStage(): GraphStage[FlowShape[T, NotUsed]] = { + def newOnCompleteStage(): GraphStage[FlowShape[T, NotUsed]] = new GraphStage[FlowShape[T, NotUsed]] { val in = Inlet[T]("in") @@ -546,15 +543,13 @@ object Sink { completeStage() } - override def postStop(): Unit = { + override def postStop(): Unit = if (!completionSignalled) callback(Failure(new AbruptStageTerminationException(this))) - } setHandlers(in, out, this) } } - } Flow[T].via(newOnCompleteStage()).to(Sink.ignore).named("onCompleteSink") } diff --git a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Source.scala b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Source.scala index 018317df77f..8dedc4e8393 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Source.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Source.scala @@ -59,7 +59,7 @@ final class Source[+Out, +Mat]( override def via[T, Mat2](flow: Graph[FlowShape[Out, T], Mat2]): Repr[T] = viaMat(flow)(Keep.left) override def viaMat[T, Mat2, Mat3](flow: Graph[FlowShape[Out, T], Mat2])( - combine: (Mat, Mat2) => Mat3): Source[T, Mat3] = { + combine: (Mat, Mat2) => Mat3): Source[T, Mat3] = if (flow.traversalBuilder eq Flow.identityTraversalBuilder) if (combine == Keep.left) // optimization by returning this @@ -77,7 +77,6 @@ final class Source[+Out, +Mat]( new Source[T, Mat3]( traversalBuilder.append(flow.traversalBuilder, flow.shape, combine), SourceShape(flow.shape.out)) - } /** * Connect this [[pekko.stream.scaladsl.Source]] to a [[pekko.stream.scaladsl.Sink]], @@ -89,9 +88,8 @@ final class Source[+Out, +Mat]( * Connect this [[pekko.stream.scaladsl.Source]] to a [[pekko.stream.scaladsl.Sink]], * concatenating the processing steps of both. */ - def toMat[Mat2, Mat3](sink: Graph[SinkShape[Out], Mat2])(combine: (Mat, Mat2) => Mat3): RunnableGraph[Mat3] = { + def toMat[Mat2, Mat3](sink: Graph[SinkShape[Out], Mat2])(combine: (Mat, Mat2) => Mat3): RunnableGraph[Mat3] = RunnableGraph(traversalBuilder.append(sink.traversalBuilder, sink.shape, combine)) - } /** * Transform only the materialized value of this Source, leaving all other properties as they were. @@ -467,9 +465,8 @@ object Source { /** * Create a `Source` that will continually emit the given element. */ - def repeat[T](element: T): Source[T, NotUsed] = { + def repeat[T](element: T): Source[T, NotUsed] = fromIterator(() => Iterator.continually(element)).withAttributes(DefaultAttributes.repeat) - } /** * Create a `Source` that will unfold a value of type `S` into @@ -773,9 +770,8 @@ object Source { ackTo: Option[ActorRef], ackMessage: Any, completionMatcher: PartialFunction[Any, CompletionStrategy], - failureMatcher: PartialFunction[Any, Throwable]): Source[T, ActorRef] = { + failureMatcher: PartialFunction[Any, Throwable]): Source[T, ActorRef] = Source.fromGraph(new ActorRefBackpressureSource(ackTo, ackMessage, completionMatcher, failureMatcher)) - } /** * Creates a `Source` that is materialized as an [[pekko.actor.ActorRef]]. @@ -794,9 +790,8 @@ object Source { def actorRefWithBackpressure[T]( ackMessage: Any, completionMatcher: PartialFunction[Any, CompletionStrategy], - failureMatcher: PartialFunction[Any, Throwable]): Source[T, ActorRef] = { + failureMatcher: PartialFunction[Any, Throwable]): Source[T, ActorRef] = Source.fromGraph(new ActorRefBackpressureSource(None, ackMessage, completionMatcher, failureMatcher)) - } /** * Creates a `Source` that is materialized as an [[pekko.actor.ActorRef]]. @@ -861,9 +856,8 @@ object Source { Source.fromGraph(GraphDSL.create(sources) { implicit b => shapes => import GraphDSL.Implicits._ val c = b.add(fanInStrategy(sources.size)) - for ((shape, i) <- shapes.zipWithIndex) { + for ((shape, i) <- shapes.zipWithIndex) shape ~> c.in(i) - } SourceShape(c.out) }) } @@ -1079,7 +1073,7 @@ object Source { */ def mergePrioritizedN[T]( sourcesAndPriorities: immutable.Seq[(Source[T, _], Int)], - eagerComplete: Boolean): Source[T, NotUsed] = { + eagerComplete: Boolean): Source[T, NotUsed] = sourcesAndPriorities match { case immutable.Seq() => Source.empty case immutable.Seq((source, _)) => source.mapMaterializedValue(_ => NotUsed) @@ -1087,5 +1081,4 @@ object Source { val (sources, priorities) = sourcesAndPriorities.unzip combine(sources.head, sources(1), sources.drop(2): _*)(_ => MergePrioritized(priorities, eagerComplete)) } - } } diff --git a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/StreamConverters.scala b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/StreamConverters.scala index 7b1a743889a..84202aaeb62 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/StreamConverters.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/StreamConverters.scala @@ -53,9 +53,8 @@ object StreamConverters { * @param in a function which creates the InputStream to read from * @param chunkSize the size of each read operation, defaults to 8192 */ - def fromInputStream(in: () => InputStream, chunkSize: Int = 8192): Source[ByteString, Future[IOResult]] = { + def fromInputStream(in: () => InputStream, chunkSize: Int = 8192): Source[ByteString, Future[IOResult]] = Source.fromGraph(new InputStreamSource(in, chunkSize)) - } /** * Creates a Source which when materialized will return an [[OutputStream]] which it is possible @@ -139,7 +138,7 @@ object StreamConverters { * to handle multiple invocations. */ def javaCollectorParallelUnordered[T, R](parallelism: Int)( - collectorFactory: () => java.util.stream.Collector[T, _ <: Any, R]): Sink[T, Future[R]] = { + collectorFactory: () => java.util.stream.Collector[T, _ <: Any, R]): Sink[T, Future[R]] = if (parallelism == 1) javaCollector[T, R](collectorFactory) else { Sink @@ -169,7 +168,6 @@ object StreamConverters { }) .withAttributes(DefaultAttributes.javaCollectorParallelUnordered) } - } /** * Creates a sink which materializes into Java 8 ``Stream`` that can be run to trigger demand through the sink. @@ -184,7 +182,7 @@ object StreamConverters { * As it is interacting wit blocking API the implementation runs on a separate dispatcher * configured through the ``pekko.stream.blocking-io-dispatcher``. */ - def asJavaStream[T](): Sink[T, java.util.stream.Stream[T]] = { + def asJavaStream[T](): Sink[T, java.util.stream.Stream[T]] = // TODO removing the QueueSink name, see issue #22523 Sink .fromGraph(new QueueSink[T](1).withAttributes(Attributes.none)) @@ -211,7 +209,6 @@ object StreamConverters { false) .onClose(new Runnable { def run = queue.cancel() })) .withAttributes(DefaultAttributes.asJavaStream) - } /** * Creates a source that wraps a Java 8 ``Stream``. ``Source`` uses a stream iterator to get all its diff --git a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/TLS.scala b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/TLS.scala index d502f7a1f7d..ec1b63a638e 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/TLS.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/TLS.scala @@ -132,13 +132,12 @@ object TLS { } def verifySession: (ActorSystem, SSLSession) => Try[Unit] = hostInfo match { - case Some((hostname, _)) => { (system, session) => - val config = theSslConfig(system) - if (config.useJvmHostnameVerification || config.hostnameVerifier.verify(hostname, session)) - Success(()) - else - Failure(new ConnectionException(s"Hostname verification failed! Expected session to be for $hostname")) - } + case Some((hostname, _)) => (system, session) => + val config = theSslConfig(system) + if (config.useJvmHostnameVerification || config.hostnameVerifier.verify(hostname, session)) + Success(()) + else + Failure(new ConnectionException(s"Hostname verification failed! Expected session to be for $hostname")) case None => (_, _) => Success(()) } diff --git a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Tcp.scala b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Tcp.scala index 89f15efbac3..bfc5855f3c1 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Tcp.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/scaladsl/Tcp.scala @@ -188,13 +188,12 @@ final class Tcp(system: ExtendedActorSystem) extends pekko.actor.Extension { @nowarn // Traversable deprecated in 2.13 options: immutable.Traversable[SocketOption] = Nil, halfClose: Boolean = false, - idleTimeout: Duration = Duration.Inf)(implicit m: Materializer): Future[ServerBinding] = { + idleTimeout: Duration = Duration.Inf)(implicit m: Materializer): Future[ServerBinding] = bind(interface, port, backlog, options, halfClose, idleTimeout) .to(Sink.foreach { (conn: IncomingConnection) => conn.flow.join(handler).run() }) .run() - } /** * Creates an [[Tcp.OutgoingConnection]] instance representing a prospective TCP client connection to the given endpoint. @@ -477,13 +476,12 @@ final class Tcp(system: ExtendedActorSystem) extends pekko.actor.Extension { options: immutable.Seq[SocketOption], idleTimeout: Duration, verifySession: SSLSession => Try[Unit], - closing: TLSClosing)(implicit m: Materializer): Future[ServerBinding] = { + closing: TLSClosing)(implicit m: Materializer): Future[ServerBinding] = bindWithTls(interface, port, createSSLEngine, backlog, options, idleTimeout, verifySession, closing) .to(Sink.foreach { (conn: IncomingConnection) => conn.handleWith(handler) }) .run() - } /** * Creates a [[Tcp.ServerBinding]] instance which represents a prospective TCP server binding on the given `endpoint` @@ -508,13 +506,12 @@ final class Tcp(system: ExtendedActorSystem) extends pekko.actor.Extension { backlog: Int = defaultBacklog, @nowarn // Traversable deprecated in 2.13 options: immutable.Traversable[SocketOption] = Nil, - idleTimeout: Duration = Duration.Inf)(implicit m: Materializer): Future[ServerBinding] = { + idleTimeout: Duration = Duration.Inf)(implicit m: Materializer): Future[ServerBinding] = bindTls(interface, port, sslContext, negotiateNewSession, backlog, options, idleTimeout) .to(Sink.foreach { (conn: IncomingConnection) => conn.handleWith(handler) }) .run() - } } diff --git a/stream/src/main/scala/org/apache/pekko/stream/serialization/StreamRefSerializer.scala b/stream/src/main/scala/org/apache/pekko/stream/serialization/StreamRefSerializer.scala index 24b9a97c99b..110f7a6f6b4 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/serialization/StreamRefSerializer.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/serialization/StreamRefSerializer.scala @@ -93,12 +93,11 @@ private[pekko] final class StreamRefSerializer(val system: ExtendedActorSystem) // ----- - private def serializeCumulativeDemand(d: StreamRefsProtocol.CumulativeDemand): StreamRefMessages.CumulativeDemand = { + private def serializeCumulativeDemand(d: StreamRefsProtocol.CumulativeDemand): StreamRefMessages.CumulativeDemand = StreamRefMessages.CumulativeDemand.newBuilder().setSeqNr(d.seqNr).build() - } private def serializeRemoteSinkFailure( - d: StreamRefsProtocol.RemoteStreamFailure): StreamRefMessages.RemoteStreamFailure = { + d: StreamRefsProtocol.RemoteStreamFailure): StreamRefMessages.RemoteStreamFailure = StreamRefMessages.RemoteStreamFailure .newBuilder() .setCause { @@ -106,20 +105,17 @@ private[pekko] final class StreamRefSerializer(val system: ExtendedActorSystem) UnsafeByteOperations.unsafeWrap(msg.getBytes(StandardCharsets.UTF_8)) } .build() - } private def serializeRemoteSinkCompleted( - d: StreamRefsProtocol.RemoteStreamCompleted): StreamRefMessages.RemoteStreamCompleted = { + d: StreamRefsProtocol.RemoteStreamCompleted): StreamRefMessages.RemoteStreamCompleted = StreamRefMessages.RemoteStreamCompleted.newBuilder().setSeqNr(d.seqNr).build() - } private def serializeOnSubscribeHandshake( - o: StreamRefsProtocol.OnSubscribeHandshake): StreamRefMessages.OnSubscribeHandshake = { + o: StreamRefsProtocol.OnSubscribeHandshake): StreamRefMessages.OnSubscribeHandshake = StreamRefMessages.OnSubscribeHandshake .newBuilder() .setTargetRef(StreamRefMessages.ActorRef.newBuilder().setPath(Serialization.serializedActorPath(o.targetRef))) .build() - } private def serializeSequencedOnNext(o: StreamRefsProtocol.SequencedOnNext[_]) = { val p = o.payload.asInstanceOf[AnyRef] @@ -136,21 +132,19 @@ private[pekko] final class StreamRefSerializer(val system: ExtendedActorSystem) StreamRefMessages.SequencedOnNext.newBuilder().setSeqNr(o.seqNr).setPayload(payloadBuilder.build()).build() } - private def serializeSinkRef(sink: SinkRefImpl[_]): StreamRefMessages.SinkRef = { + private def serializeSinkRef(sink: SinkRefImpl[_]): StreamRefMessages.SinkRef = StreamRefMessages.SinkRef .newBuilder() .setTargetRef( StreamRefMessages.ActorRef.newBuilder().setPath(Serialization.serializedActorPath(sink.initialPartnerRef))) .build() - } - private def serializeSourceRef(source: SourceRefImpl[_]): StreamRefMessages.SourceRef = { + private def serializeSourceRef(source: SourceRefImpl[_]): StreamRefMessages.SourceRef = StreamRefMessages.SourceRef .newBuilder() .setOriginRef( StreamRefMessages.ActorRef.newBuilder().setPath(Serialization.serializedActorPath(source.initialPartnerRef))) .build() - } // ---------- diff --git a/stream/src/main/scala/org/apache/pekko/stream/snapshot/MaterializerState.scala b/stream/src/main/scala/org/apache/pekko/stream/snapshot/MaterializerState.scala index e22bf920201..6ce34dceab5 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/snapshot/MaterializerState.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/snapshot/MaterializerState.scala @@ -42,25 +42,23 @@ object MaterializerState { * Dump stream snapshots of all streams of the default system materializer. */ @ApiMayChange - def streamSnapshots(system: ActorSystem): Future[immutable.Seq[StreamSnapshot]] = { + def streamSnapshots(system: ActorSystem): Future[immutable.Seq[StreamSnapshot]] = SystemMaterializer(system).materializer match { case impl: PhasedFusingActorMaterializer => requestFromSupervisor(impl.supervisor)(impl.system.dispatchers.internalDispatcher) case other => throw new IllegalArgumentException(s"Unsupported Materializer type ${other.getClass}") } - } /** * Dump stream snapshots of all streams of the given materializer. */ @ApiMayChange - def streamSnapshots(mat: Materializer): Future[immutable.Seq[StreamSnapshot]] = { + def streamSnapshots(mat: Materializer): Future[immutable.Seq[StreamSnapshot]] = mat match { case impl: PhasedFusingActorMaterializer => requestFromSupervisor(impl.supervisor)(impl.system.dispatchers.internalDispatcher) case other => throw new IllegalArgumentException(s"Unsupported Materializer type ${other.getClass}") } - } /** INTERNAL API */ @InternalApi diff --git a/stream/src/main/scala/org/apache/pekko/stream/stage/GraphStage.scala b/stream/src/main/scala/org/apache/pekko/stream/stage/GraphStage.scala index b18630843fc..93d575c5169 100644 --- a/stream/src/main/scala/org/apache/pekko/stream/stage/GraphStage.scala +++ b/stream/src/main/scala/org/apache/pekko/stream/stage/GraphStage.scala @@ -243,7 +243,7 @@ object GraphStageLogic { private[this] var behavior = initialReceive /** INTERNAL API */ - private[pekko] def internalReceive(pack: (ActorRef, Any)): Unit = { + private[pekko] def internalReceive(pack: (ActorRef, Any)): Unit = pack._2 match { case Terminated(ref) => if (functionRef.isWatching(ref)) { @@ -252,19 +252,16 @@ object GraphStageLogic { } case _ => behavior(pack) } - } /** * Special `become` allowing to swap the behavior of this StageActorRef. * Unbecome is not available. */ - def become(receive: StageActorRef.Receive): Unit = { + def become(receive: StageActorRef.Receive): Unit = behavior = receive - } - def stop(): Unit = { + def stop(): Unit = cell.removeFunctionRef(functionRef) - } def watch(actorRef: ActorRef): Unit = functionRef.watch(actorRef) @@ -469,9 +466,8 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: /** * Retrieves the current callback for the events on the given [[Inlet]] */ - final protected def getHandler(in: Inlet[_]): InHandler = { + final protected def getHandler(in: Inlet[_]): InHandler = handlers(in.id).asInstanceOf[InHandler] - } /** * Assigns callbacks for the events for an [[Outlet]] @@ -487,9 +483,8 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: /** * Retrieves the current callback for the events on the given [[Outlet]] */ - final protected def getHandler(out: Outlet[_]): OutHandler = { + final protected def getHandler(out: Outlet[_]): OutHandler = handlers(out.id + inCount).asInstanceOf[OutHandler] - } private def getNonEmittingHandler(out: Outlet[_]): OutHandler = getHandler(out) match { @@ -843,7 +838,7 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: * for the given inlet if suspension is needed and reinstalls the current * handler upon receiving the `onPush()` signal (before invoking the `andThen` function). */ - final protected def read[T](in: Inlet[T])(andThen: T => Unit, onClose: () => Unit): Unit = { + final protected def read[T](in: Inlet[T])(andThen: T => Unit, onClose: () => Unit): Unit = if (isAvailable(in)) { val elem = grab(in) andThen(elem) @@ -854,7 +849,6 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: if (!hasBeenPulled(in)) pull(in) setHandler(in, new Reading(in, 1, getHandler(in))(andThen, onClose)) } - } /** * Java API: Read an element from the given inlet and continue with the given function, @@ -862,9 +856,8 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: * for the given inlet if suspension is needed and reinstalls the current * handler upon receiving the `onPush()` signal (before invoking the `andThen` function). */ - final protected def read[T](in: Inlet[T], andThen: Procedure[T], onClose: Effect): Unit = { + final protected def read[T](in: Inlet[T], andThen: Procedure[T], onClose: Effect): Unit = read(in)(andThen.apply, onClose.apply _) - } /** * Abort outstanding (suspended) reading for the given inlet, if there is any. @@ -1010,9 +1003,8 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: */ final protected def emit[T](out: Outlet[T], elem: T): Unit = emit(out, elem, DoNothing) - final protected def emit[T](out: Outlet[T], elem: T, andThen: Effect): Unit = { + final protected def emit[T](out: Outlet[T], elem: T, andThen: Effect): Unit = emit(out, elem, andThen.apply _) - } /** * Abort outstanding (suspended) emissions for the given outlet, if there are any. @@ -1472,9 +1464,8 @@ abstract class GraphStageLogic private[stream] (val inCount: Int, val outCount: _sink.pullSubstream() } - def cancel(): Unit = { + def cancel(): Unit = cancel(SubscriptionWithCancelException.NoMoreElementsNeeded) - } def cancel(cause: Throwable): Unit = { closed = true _sink.cancelSubstream(cause) diff --git a/testkit/src/main/scala/org/apache/pekko/testkit/CallingThreadDispatcher.scala b/testkit/src/main/scala/org/apache/pekko/testkit/CallingThreadDispatcher.scala index 291969ff52e..aa1b3182359 100644 --- a/testkit/src/main/scala/org/apache/pekko/testkit/CallingThreadDispatcher.scala +++ b/testkit/src/main/scala/org/apache/pekko/testkit/CallingThreadDispatcher.scala @@ -82,7 +82,7 @@ private[testkit] class CallingThreadDispatcherQueues extends Extension { private var lastGC = 0L // we have to forget about long-gone threads sometime - private def gc(): Unit = { + private def gc(): Unit = queues = queues .foldLeft(Map.newBuilder[CallingThreadMailbox, Set[WeakReference[MessageQueue]]]) { case (m, (k, v)) => @@ -90,7 +90,6 @@ private[testkit] class CallingThreadDispatcherQueues extends Extension { if (nv.isEmpty) m else m += (k -> nv) } .result() - } protected[pekko] def registerQueue(mbox: CallingThreadMailbox, q: MessageQueue): Unit = synchronized { if (queues contains mbox) { @@ -200,14 +199,13 @@ class CallingThreadDispatcher(_configurator: MessageDispatcherConfigurator) exte mbox.foreach(CallingThreadDispatcherQueues(actor.system).unregisterQueues) } - protected[pekko] override def suspend(actor: ActorCell): Unit = { + protected[pekko] override def suspend(actor: ActorCell): Unit = actor.mailbox match { - case m: CallingThreadMailbox => { m.suspendSwitch.switchOn; m.suspend() } + case m: CallingThreadMailbox => m.suspendSwitch.switchOn; m.suspend() case m => m.systemEnqueue(actor.self, Suspend()) } - } - protected[pekko] override def resume(actor: ActorCell): Unit = { + protected[pekko] override def resume(actor: ActorCell): Unit = actor.mailbox match { case mbox: CallingThreadMailbox => val queue = mbox.queue @@ -219,18 +217,16 @@ class CallingThreadDispatcher(_configurator: MessageDispatcherConfigurator) exte runQueue(mbox, queue) case m => m.systemEnqueue(actor.self, Resume(causedByFailure = null)) } - } - protected[pekko] override def systemDispatch(receiver: ActorCell, message: SystemMessage): Unit = { + protected[pekko] override def systemDispatch(receiver: ActorCell, message: SystemMessage): Unit = receiver.mailbox match { case mbox: CallingThreadMailbox => mbox.systemEnqueue(receiver.self, message) runQueue(mbox, mbox.queue) case m => m.systemEnqueue(receiver.self, message) } - } - protected[pekko] override def dispatch(receiver: ActorCell, handle: Envelope): Unit = { + protected[pekko] override def dispatch(receiver: ActorCell, handle: Envelope): Unit = receiver.mailbox match { case mbox: CallingThreadMailbox => val queue = mbox.queue @@ -244,9 +240,8 @@ class CallingThreadDispatcher(_configurator: MessageDispatcherConfigurator) exte if (execute) runQueue(mbox, queue) case m => m.enqueue(receiver.self, handle) } - } - protected[pekko] override def executeTask(invocation: TaskInvocation): Unit = { invocation.run() } + protected[pekko] override def executeTask(invocation: TaskInvocation): Unit = invocation.run() /** * This method must be called with this thread's queue. @@ -260,13 +255,12 @@ class CallingThreadDispatcher(_configurator: MessageDispatcherConfigurator) exte mbox: CallingThreadMailbox, queue: MessageQueue, interruptedEx: InterruptedException = null): Unit = { - def checkThreadInterruption(intEx: InterruptedException): InterruptedException = { + def checkThreadInterruption(intEx: InterruptedException): InterruptedException = if (Thread.interrupted()) { // clear interrupted flag before we continue, exception will be thrown later val ie = new InterruptedException("Interrupted during message processing") log.error(ie, "Interrupted during message processing") ie } else intEx - } def throwInterruptionIfExistsOrSet(intEx: InterruptedException): Unit = { val ie = checkThreadInterruption(intEx) @@ -311,9 +305,9 @@ class CallingThreadDispatcher(_configurator: MessageDispatcherConfigurator) exte if (!mbox.ctdLock.isHeldByCurrentThread) { var intex = interruptedEx val gotLock = - try { + try mbox.ctdLock.tryLock(50, TimeUnit.MILLISECONDS) - } catch { + catch { case ie: InterruptedException => Thread.interrupted() // clear interrupted flag before we continue, exception will be thrown later intex = ie @@ -321,11 +315,10 @@ class CallingThreadDispatcher(_configurator: MessageDispatcherConfigurator) exte } if (gotLock) { val ie = - try { + try process(intex) - } finally { + finally mbox.ctdLock.unlock - } throwInterruptionIfExistsOrSet(ie) } else { // if we didn't get the lock and our mailbox still has messages, then we need to try again @@ -379,7 +372,7 @@ class CallingThreadMailbox(_receiver: pekko.actor.Cell, val mailboxType: Mailbox val ctdLock = new ReentrantLock val suspendSwitch = new Switch - override def cleanUp(): Unit = { + override def cleanUp(): Unit = /* * This is called from dispatcher.unregister, i.e. under this.lock. If * another thread obtained a reference to this mailbox and enqueues after @@ -392,5 +385,4 @@ class CallingThreadMailbox(_receiver: pekko.actor.Cell, val mailboxType: Mailbox qq.cleanUp(actor.self, actor.dispatcher.mailboxes.deadLetterMailbox.messageQueue) q.remove() } - } } diff --git a/testkit/src/main/scala/org/apache/pekko/testkit/ExplicitlyTriggeredScheduler.scala b/testkit/src/main/scala/org/apache/pekko/testkit/ExplicitlyTriggeredScheduler.scala index d9f745ee213..93f98a6e476 100644 --- a/testkit/src/main/scala/org/apache/pekko/testkit/ExplicitlyTriggeredScheduler.scala +++ b/testkit/src/main/scala/org/apache/pekko/testkit/ExplicitlyTriggeredScheduler.scala @@ -90,7 +90,7 @@ class ExplicitlyTriggeredScheduler(@unused config: Config, log: LoggingAdapter, .sortBy(_._2) @tailrec - private[testkit] final def executeTasks(runTo: Long): Unit = { + private[testkit] final def executeTasks(runTo: Long): Unit = scheduledTasks(runTo).headOption match { case Some((task, time)) => currentTime.set(time) @@ -104,7 +104,6 @@ class ExplicitlyTriggeredScheduler(@unused config: Config, log: LoggingAdapter, executeTasks(runTo) case _ => // Done } - } private def schedule( initialDelay: FiniteDuration, diff --git a/testkit/src/main/scala/org/apache/pekko/testkit/SocketUtil.scala b/testkit/src/main/scala/org/apache/pekko/testkit/SocketUtil.scala index 8acf66ad5b4..3833f7251c5 100644 --- a/testkit/src/main/scala/org/apache/pekko/testkit/SocketUtil.scala +++ b/testkit/src/main/scala/org/apache/pekko/testkit/SocketUtil.scala @@ -28,14 +28,13 @@ object SocketUtil { val RANDOM_LOOPBACK_ADDRESS = "RANDOM_LOOPBACK_ADDRESS" - private val canBindOnAlternativeLoopbackAddresses = { + private val canBindOnAlternativeLoopbackAddresses = try { SocketUtil.temporaryServerAddress(address = "127.20.0.0") true } catch { case NonFatal(_) => false } - } sealed trait Protocol case object Tcp extends Protocol @@ -61,9 +60,8 @@ object SocketUtil { tcpPort } catch { case NonFatal(_) => findBoth(tries - 1) - } finally { + } finally ds.close() - } } protocol match { @@ -84,7 +82,7 @@ object SocketUtil { def temporaryServerAddresses( numberOfAddresses: Int, hostname: String = RANDOM_LOOPBACK_ADDRESS, - udp: Boolean = false): immutable.IndexedSeq[InetSocketAddress] = { + udp: Boolean = false): immutable.IndexedSeq[InetSocketAddress] = Vector .fill(numberOfAddresses) { @@ -114,7 +112,6 @@ object SocketUtil { } } .collect { case (socket, address) => socket.close(); address } - } def temporaryServerHostnameAndPort(interface: String = RANDOM_LOOPBACK_ADDRESS): (String, Int) = { val socketAddress = temporaryServerAddress(interface) diff --git a/testkit/src/main/scala/org/apache/pekko/testkit/TestActorRef.scala b/testkit/src/main/scala/org/apache/pekko/testkit/TestActorRef.scala index 42d370dfc9d..96826687bf8 100644 --- a/testkit/src/main/scala/org/apache/pekko/testkit/TestActorRef.scala +++ b/testkit/src/main/scala/org/apache/pekko/testkit/TestActorRef.scala @@ -55,11 +55,10 @@ class TestActorRef[T <: Actor](_system: ActorSystem, _props: Props, _supervisor: } _system.asInstanceOf[ActorSystemImpl] - }, { - _props.withDispatcher( - if (_props.deploy.dispatcher == Deploy.NoDispatcherGiven) CallingThreadDispatcher.Id - else _props.dispatcher) - }, { + }, + _props.withDispatcher( + if (_props.deploy.dispatcher == Deploy.NoDispatcherGiven) CallingThreadDispatcher.Id + else _props.dispatcher), { val props = _props.withDispatcher( if (_props.deploy.dispatcher == Deploy.NoDispatcherGiven) CallingThreadDispatcher.Id else _props.dispatcher) @@ -90,12 +89,11 @@ class TestActorRef[T <: Actor](_system: ActorSystem, _props: Props, _supervisor: dispatcher: MessageDispatcher, supervisor: InternalActorRef): ActorCell = new ActorCell(system, ref, props, dispatcher, supervisor) { - override def autoReceiveMessage(msg: Envelope): Unit = { + override def autoReceiveMessage(msg: Envelope): Unit = msg.message match { case InternalGetActor => sender() ! actor case _ => super.autoReceiveMessage(msg) } - } } /** diff --git a/testkit/src/main/scala/org/apache/pekko/testkit/TestBarrier.scala b/testkit/src/main/scala/org/apache/pekko/testkit/TestBarrier.scala index 5c64adc9028..b7b1af94e56 100644 --- a/testkit/src/main/scala/org/apache/pekko/testkit/TestBarrier.scala +++ b/testkit/src/main/scala/org/apache/pekko/testkit/TestBarrier.scala @@ -39,15 +39,14 @@ class TestBarrier(count: Int) { def await()(implicit system: ActorSystem): Unit = await(TestBarrier.DefaultTimeout) - def await(timeout: FiniteDuration)(implicit system: ActorSystem): Unit = { - try { + def await(timeout: FiniteDuration)(implicit system: ActorSystem): Unit = + try barrier.await(timeout.dilated.toNanos, TimeUnit.NANOSECONDS) - } catch { + catch { case _: TimeoutException => throw new TestBarrierTimeoutException( "Timeout of %s and time factor of %s".format(timeout.toString, TestKitExtension(system).TestTimeFactor)) } - } def reset(): Unit = barrier.reset() } diff --git a/testkit/src/main/scala/org/apache/pekko/testkit/TestEventListener.scala b/testkit/src/main/scala/org/apache/pekko/testkit/TestEventListener.scala index 0071d1cc6a2..389e1dd885a 100644 --- a/testkit/src/main/scala/org/apache/pekko/testkit/TestEventListener.scala +++ b/testkit/src/main/scala/org/apache/pekko/testkit/TestEventListener.scala @@ -96,12 +96,11 @@ abstract class EventFilter(occurrences: Int) { */ protected def matches(event: LogEvent): Boolean - final def apply(event: LogEvent): Boolean = { + final def apply(event: LogEvent): Boolean = if (matches(event)) { if (todo != Int.MaxValue) todo -= 1 true } else false - } def awaitDone(max: Duration): Boolean = { if (todo != Int.MaxValue && todo > 0) TestKit.awaitCond(todo <= 0, max, noThrow = true) @@ -328,14 +327,13 @@ final case class ErrorFilter( override val complete: Boolean)(occurrences: Int) extends EventFilter(occurrences) { - def matches(event: LogEvent) = { + def matches(event: LogEvent) = event match { case Error(cause, src, _, msg) if (throwable eq Error.NoCause.getClass) || (throwable.isInstance(cause)) => (msg == null && cause.getMessage == null && cause.getStackTrace.length == 0) || doMatch(src, msg) || doMatch(src, cause.getMessage) case _ => false } - } /** * Java API: create an ErrorFilter @@ -388,12 +386,11 @@ final case class WarningFilter( override val complete: Boolean)(occurrences: Int) extends EventFilter(occurrences) { - def matches(event: LogEvent) = { + def matches(event: LogEvent) = event match { case Warning(src, _, msg) => doMatch(src, msg) case _ => false } - } /** * Java API: create a WarningFilter @@ -433,12 +430,11 @@ final case class InfoFilter( override val complete: Boolean)(occurrences: Int) extends EventFilter(occurrences) { - def matches(event: LogEvent) = { + def matches(event: LogEvent) = event match { case Info(src, _, msg) => doMatch(src, msg) case _ => false } - } /** * Java API: create an InfoFilter @@ -478,12 +474,11 @@ final case class DebugFilter( override val complete: Boolean)(occurrences: Int) extends EventFilter(occurrences) { - def matches(event: LogEvent) = { + def matches(event: LogEvent) = event match { case Debug(src, _, msg) => doMatch(src, msg) case _ => false } - } /** * Java API: create a DebugFilter @@ -516,9 +511,8 @@ final case class DebugFilter( */ final case class CustomEventFilter(test: PartialFunction[LogEvent, Boolean])(occurrences: Int) extends EventFilter(occurrences) { - def matches(event: LogEvent) = { + def matches(event: LogEvent) = test.isDefinedAt(event) && test(event) - } } object DeadLettersFilter { @@ -532,12 +526,11 @@ object DeadLettersFilter { */ final case class DeadLettersFilter(val messageClass: Class[_])(occurrences: Int) extends EventFilter(occurrences) { - def matches(event: LogEvent) = { + def matches(event: LogEvent) = event match { case Warning(_, _, msg) => BoxedType(messageClass).isInstance(msg) case _ => false } - } } @@ -592,9 +585,9 @@ class TestEventListener extends Logging.DefaultLogger { def filter(event: LogEvent): Boolean = filters.exists(f => - try { + try f(event) - } catch { case _: Exception => false }) + catch { case _: Exception => false }) def addFilter(filter: EventFilter): Unit = filters ::= filter diff --git a/testkit/src/main/scala/org/apache/pekko/testkit/TestFSMRef.scala b/testkit/src/main/scala/org/apache/pekko/testkit/TestFSMRef.scala index 57ea08b0b0d..576a0be0fb8 100644 --- a/testkit/src/main/scala/org/apache/pekko/testkit/TestFSMRef.scala +++ b/testkit/src/main/scala/org/apache/pekko/testkit/TestFSMRef.scala @@ -67,9 +67,8 @@ class TestFSMRef[S, D, T <: Actor](system: ActorSystem, props: Props, supervisor stateName: S = fsm.stateName, stateData: D = fsm.stateData, timeout: FiniteDuration = null, - stopReason: Option[FSM.Reason] = None): Unit = { + stopReason: Option[FSM.Reason] = None): Unit = fsm.applyState(FSM.State(stateName, stateData, Option(timeout), stopReason)) - } /** * Proxy for [[pekko.actor.FSM#startTimerWithFixedDelay]]. @@ -96,14 +95,13 @@ class TestFSMRef[S, D, T <: Actor](system: ActorSystem, props: Props, supervisor "Use startTimerWithFixedDelay or startTimerAtFixedRate instead. This has the same semantics as " + "startTimerAtFixedRate, but startTimerWithFixedDelay is often preferred.", since = "Akka 2.6.0") - def setTimer(name: String, msg: Any, timeout: FiniteDuration, repeat: Boolean = false): Unit = { + def setTimer(name: String, msg: Any, timeout: FiniteDuration, repeat: Boolean = false): Unit = fsm.setTimer(name, msg, timeout, repeat) - } /** * Proxy for [[pekko.actor.FSM#cancelTimer]]. */ - def cancelTimer(name: String): Unit = { fsm.cancelTimer(name) } + def cancelTimer(name: String): Unit = fsm.cancelTimer(name) /** * Proxy for [[pekko.actor.FSM#isStateTimerActive]]. diff --git a/testkit/src/main/scala/org/apache/pekko/testkit/TestJavaSerializer.scala b/testkit/src/main/scala/org/apache/pekko/testkit/TestJavaSerializer.scala index 4dac31c04b0..fbf3b010f2d 100644 --- a/testkit/src/main/scala/org/apache/pekko/testkit/TestJavaSerializer.scala +++ b/testkit/src/main/scala/org/apache/pekko/testkit/TestJavaSerializer.scala @@ -37,14 +37,14 @@ class TestJavaSerializer(val system: ExtendedActorSystem) extends BaseSerializer def toBinary(o: AnyRef): Array[Byte] = { val bos = new ByteArrayOutputStream val out = new ObjectOutputStream(bos) - JavaSerializer.currentSystem.withValue(system) { out.writeObject(o) } + JavaSerializer.currentSystem.withValue(system)(out.writeObject(o)) out.close() bos.toByteArray } def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]]): AnyRef = { val in = new ClassLoaderObjectInputStream(system.dynamicAccess.classLoader, new ByteArrayInputStream(bytes)) - val obj = JavaSerializer.currentSystem.withValue(system) { in.readObject } + val obj = JavaSerializer.currentSystem.withValue(system)(in.readObject) in.close() obj } diff --git a/testkit/src/main/scala/org/apache/pekko/testkit/TestKit.scala b/testkit/src/main/scala/org/apache/pekko/testkit/TestKit.scala index 1b43f585011..4df428f77f3 100644 --- a/testkit/src/main/scala/org/apache/pekko/testkit/TestKit.scala +++ b/testkit/src/main/scala/org/apache/pekko/testkit/TestKit.scala @@ -88,9 +88,8 @@ object TestActor { override def decider = defaultDecider // not actually invoked - override def handleChildTerminated(context: ActorContext, child: ActorRef, children: Iterable[ActorRef]): Unit = { + override def handleChildTerminated(context: ActorContext, child: ActorRef, children: Iterable[ActorRef]): Unit = delegates -= child - } override def processFailure( context: ActorContext, @@ -98,18 +97,16 @@ object TestActor { child: ActorRef, cause: Throwable, stats: ChildRestartStats, - children: Iterable[ChildRestartStats]): Unit = { + children: Iterable[ChildRestartStats]): Unit = delegate(child).processFailure(context, restart, child, cause, stats, children) - } override def handleFailure( context: ActorContext, child: ActorRef, cause: Throwable, stats: ChildRestartStats, - children: Iterable[ChildRestartStats]): Boolean = { + children: Iterable[ChildRestartStats]): Boolean = delegate(child).handleFailure(context, child, cause, stats, children) - } } // make creator serializable, for VerifySerializabilitySpec @@ -211,12 +208,12 @@ trait TestKitBase { * Ignore all messages in the test actor for which the given partial * function returns true. */ - def ignoreMsg(f: PartialFunction[Any, Boolean]): Unit = { testActor ! TestActor.SetIgnore(Some(f)) } + def ignoreMsg(f: PartialFunction[Any, Boolean]): Unit = testActor ! TestActor.SetIgnore(Some(f)) /** * Stop ignoring messages in the test actor. */ - def ignoreNoMsg(): Unit = { testActor ! TestActor.SetIgnore(None) } + def ignoreNoMsg(): Unit = testActor ! TestActor.SetIgnore(None) /** * Have the testActor watch someone (i.e. `context.watch(...)`). @@ -305,13 +302,12 @@ trait TestKitBase { val stop = now + _max @tailrec - def poll(t: Duration): Unit = { + def poll(t: Duration): Unit = if (!p) { assert(now < stop, s"timeout ${_max} expired: $message") Thread.sleep(t.toMillis) poll((stop - now) min interval) } - } poll(_max min interval) } @@ -380,9 +376,9 @@ trait TestKitBase { // because Java API and not wanting to return a value will be "return null" val instantNow = now val result = - try { + try a - } catch { + catch { case e: Throwable => throw e } @@ -651,12 +647,11 @@ trait TestKitBase { missing: Seq[Any], unexpected: Seq[Any], missingMessage: String, - unexpectedMessage: String): Unit = { + unexpectedMessage: String): Unit = assert( missing.isEmpty && unexpected.isEmpty, (if (missing.isEmpty) "" else missing.mkString(missingMessage + " [", ", ", "] ")) + (if (unexpected.isEmpty) "" else unexpected.mkString(unexpectedMessage + " [", ", ", "]"))) - } private def expectMsgAllOf_internal[T](max: FiniteDuration, obj: T*): immutable.Seq[T] = { val recv = receiveN_internal(obj.size, max) @@ -732,17 +727,15 @@ trait TestKitBase { * NOTE! Supplied value is always dilated. */ @deprecated(message = "Use expectNoMessage instead", since = "Akka 2.5.5") - def expectNoMsg(max: FiniteDuration): Unit = { + def expectNoMsg(max: FiniteDuration): Unit = expectNoMsg_internal(max.dilated) - } /** * Assert that no message is received for the specified time. * Supplied value is not dilated. */ - def expectNoMessage(max: FiniteDuration) = { + def expectNoMessage(max: FiniteDuration) = expectNoMsg_internal(max) - } /** * Assert that no message is received. Waits for the default period configured as @@ -808,7 +801,7 @@ trait TestKitBase { var msg: Message = NullMessage @tailrec - def doit(acc: List[T], count: Int): List[T] = { + def doit(acc: List[T], count: Int): List[T] = if (count >= messages) acc.reverse else { receiveOne((stop - now) min idle) @@ -826,7 +819,6 @@ trait TestKitBase { case unexpected => throw new RuntimeException(s"Unexpected: $unexpected") // exhaustiveness check } } - } val ret = doit(Nil, 0) lastWasNoMsg = true @@ -890,9 +882,8 @@ trait TestKitBase { def shutdown( actorSystem: ActorSystem = system, duration: Duration = Duration.Undefined, - verifySystemShutdown: Boolean = false): Unit = { + verifySystemShutdown: Boolean = false): Unit = TestKit.shutdownActorSystem(actorSystem, duration, verifySystemShutdown) - } /** * Spawns an actor as a child of this test actor, and returns the child's ActorRef. @@ -999,7 +990,7 @@ object TestKit { val stop = now + max @tailrec - def poll(): Boolean = { + def poll(): Boolean = if (!p) { val toSleep = stop - now if (toSleep <= Duration.Zero) { @@ -1010,7 +1001,6 @@ object TestKit { poll() } } else true - } poll() } diff --git a/testkit/src/main/scala/org/apache/pekko/testkit/TestKitUtils.scala b/testkit/src/main/scala/org/apache/pekko/testkit/TestKitUtils.scala index 67c471b4a1f..66ffca976f0 100644 --- a/testkit/src/main/scala/org/apache/pekko/testkit/TestKitUtils.scala +++ b/testkit/src/main/scala/org/apache/pekko/testkit/TestKitUtils.scala @@ -27,13 +27,12 @@ private[pekko] object TestKitUtils { def testNameFromCallStack(classToStartFrom: Class[_], testKitRegex: Regex): String = { - def isAbstractClass(className: String): Boolean = { - try { + def isAbstractClass(className: String): Boolean = + try Modifier.isAbstract(Class.forName(className).getModifiers) - } catch { + catch { case _: Throwable => false // yes catch everything, best effort check } - } val startFrom = classToStartFrom.getName val filteredStack = Thread.currentThread.getStackTrace.iterator @@ -61,11 +60,10 @@ private[pekko] object TestKitUtils { * replacing invalid characters. `name` may for example be a fully qualified * class name and then the short class name will be used. */ - def scrubActorSystemName(name: String): String = { + def scrubActorSystemName(name: String): String = name .replaceFirst("""^.*\.""", "") // drop package name .replaceAll("""\$\$?\w+""", "") // drop scala anonymous functions/classes .replaceAll("[^a-zA-Z_0-9-]", "_") .replaceAll("""MultiJvmNode\d+""", "") // drop MultiJvm suffix - } } diff --git a/testkit/src/main/scala/org/apache/pekko/testkit/TestLatch.scala b/testkit/src/main/scala/org/apache/pekko/testkit/TestLatch.scala index 02d30642b0b..19dc5c4f24c 100644 --- a/testkit/src/main/scala/org/apache/pekko/testkit/TestLatch.scala +++ b/testkit/src/main/scala/org/apache/pekko/testkit/TestLatch.scala @@ -55,7 +55,6 @@ class TestLatch(count: Int = 1)(implicit system: ActorSystem) extends Awaitable[ this } @throws(classOf[Exception]) - def result(atMost: Duration)(implicit permit: CanAwait): Unit = { + def result(atMost: Duration)(implicit permit: CanAwait): Unit = ready(atMost) - } } diff --git a/testkit/src/main/scala/org/apache/pekko/testkit/javadsl/TestKit.scala b/testkit/src/main/scala/org/apache/pekko/testkit/javadsl/TestKit.scala index b295655bd37..252ec223697 100644 --- a/testkit/src/main/scala/org/apache/pekko/testkit/javadsl/TestKit.scala +++ b/testkit/src/main/scala/org/apache/pekko/testkit/javadsl/TestKit.scala @@ -68,13 +68,12 @@ class TestKit(system: ActorSystem) { def getSystem: ActorSystem = tp.system - def duration(s: String): FiniteDuration = { + def duration(s: String): FiniteDuration = Duration.apply(s) match { case fd: FiniteDuration => fd case _ => throw new IllegalArgumentException("duration() is only for finite durations, use Duration.Inf() and friends") } - } /** * Scale timeouts (durations) during tests with the configured @@ -128,12 +127,11 @@ class TestKit(system: ActorSystem) { * Ignore all messages in the test actor for which the given partial * function returns true. */ - def ignoreMsg(pf: JFunction[Any, Boolean]): Unit = { + def ignoreMsg(pf: JFunction[Any, Boolean]): Unit = tp.ignoreMsg(new CachingPartialFunction[Any, Boolean] { @throws(classOf[Exception]) override def `match`(x: Any): Boolean = pf.apply(x) }) - } /** * Stop ignoring messages in the test actor. @@ -498,12 +496,11 @@ class TestKit(system: ActorSystem) { * Use this variant to implement more complicated or conditional * processing. */ - def expectMsgPF[T](hint: String, f: JFunction[Any, T]): T = { + def expectMsgPF[T](hint: String, f: JFunction[Any, T]): T = tp.expectMsgPF(hint = hint)(new CachingPartialFunction[Any, T] { @throws(classOf[Exception]) override def `match`(x: Any): T = f.apply(x) }) - } /** * Receive one message from the test actor and assert that the given @@ -514,12 +511,11 @@ class TestKit(system: ActorSystem) { * processing. */ @deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "Akka 2.6.0") - def expectMsgPF[T](max: Duration, hint: String, f: JFunction[Any, T]): T = { + def expectMsgPF[T](max: Duration, hint: String, f: JFunction[Any, T]): T = tp.expectMsgPF(max, hint)(new CachingPartialFunction[Any, T] { @throws(classOf[Exception]) override def `match`(x: Any): T = f.apply(x) }) - } /** * Receive one message from the test actor and assert that the given @@ -726,12 +722,11 @@ class TestKit(system: ActorSystem) { * Same as `fishForMessage`, but gets a different partial function and returns properly typed message. */ @deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "Akka 2.6.0") - def fishForSpecificMessage[T](max: Duration, hint: String, f: JFunction[Any, T]): T = { + def fishForSpecificMessage[T](max: Duration, hint: String, f: JFunction[Any, T]): T = tp.fishForSpecificMessage(max, hint)(new CachingPartialFunction[Any, T] { @throws(classOf[Exception]) override def `match`(x: Any): T = f.apply(x) }) - } /** * Same as `fishForMessage`, but gets a different partial function and returns properly typed message. @@ -788,13 +783,12 @@ class TestKit(system: ActorSystem) { * certain characteristics are generated at a certain rate: */ @deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "Akka 2.5.13") - def receiveWhile[T](max: Duration, idle: Duration, messages: Int, f: JFunction[AnyRef, T]): JList[T] = { + def receiveWhile[T](max: Duration, idle: Duration, messages: Int, f: JFunction[AnyRef, T]): JList[T] = tp.receiveWhile(max, idle, messages)(new CachingPartialFunction[AnyRef, T] { @throws(classOf[Exception]) override def `match`(x: AnyRef): T = f.apply(x) }) .asJava - } /** * Receive a series of messages until one does not match the given partial @@ -811,30 +805,27 @@ class TestKit(system: ActorSystem) { max: java.time.Duration, idle: java.time.Duration, messages: Int, - f: JFunction[AnyRef, T]): JList[T] = { + f: JFunction[AnyRef, T]): JList[T] = tp.receiveWhile(max.asScala, idle.asScala, messages)(new CachingPartialFunction[AnyRef, T] { @throws(classOf[Exception]) override def `match`(x: AnyRef): T = f.apply(x) }) .asJava - } @deprecated("Use the overloaded one which accepts java.time.Duration instead.", since = "Akka 2.5.13") - def receiveWhile[T](max: Duration, f: JFunction[AnyRef, T]): JList[T] = { + def receiveWhile[T](max: Duration, f: JFunction[AnyRef, T]): JList[T] = tp.receiveWhile(max = max)(new CachingPartialFunction[AnyRef, T] { @throws(classOf[Exception]) override def `match`(x: AnyRef): T = f.apply(x) }) .asJava - } - def receiveWhile[T](max: java.time.Duration, f: JFunction[AnyRef, T]): JList[T] = { + def receiveWhile[T](max: java.time.Duration, f: JFunction[AnyRef, T]): JList[T] = tp.receiveWhile(max = max.asScala)(new CachingPartialFunction[AnyRef, T] { @throws(classOf[Exception]) override def `match`(x: AnyRef): T = f.apply(x) }) .asJava - } /** * Spawns an actor as a child of this test actor, and returns the child's ActorRef. @@ -868,26 +859,22 @@ object TestKit { * * If verifySystemShutdown is true, then an exception will be thrown on failure. */ - def shutdownActorSystem(actorSystem: ActorSystem, duration: Duration, verifySystemShutdown: Boolean): Unit = { - + def shutdownActorSystem(actorSystem: ActorSystem, duration: Duration, verifySystemShutdown: Boolean): Unit = pekko.testkit.TestKit.shutdownActorSystem(actorSystem, duration, verifySystemShutdown) - } /** * Shut down an actor system and wait for termination. * On failure debug output will be logged about the remaining actors in the system. */ - def shutdownActorSystem(actorSystem: ActorSystem): Unit = { + def shutdownActorSystem(actorSystem: ActorSystem): Unit = shutdownActorSystem(actorSystem, 10.seconds, false) - } /** * Shut down an actor system and wait for termination. * On failure debug output will be logged about the remaining actors in the system. */ - def shutdownActorSystem(actorSystem: ActorSystem, duration: Duration): Unit = { + def shutdownActorSystem(actorSystem: ActorSystem, duration: Duration): Unit = shutdownActorSystem(actorSystem, duration, false) - } /** * Shut down an actor system and wait for termination. @@ -895,9 +882,8 @@ object TestKit { * * If verifySystemShutdown is true, then an exception will be thrown on failure. */ - def shutdownActorSystem(actorSystem: ActorSystem, verifySystemShutdown: Boolean): Unit = { + def shutdownActorSystem(actorSystem: ActorSystem, verifySystemShutdown: Boolean): Unit = shutdownActorSystem(actorSystem, 10.seconds, verifySystemShutdown) - } } diff --git a/testkit/src/main/scala/org/apache/pekko/testkit/package.scala b/testkit/src/main/scala/org/apache/pekko/testkit/package.scala index 609cff64674..1341215b42d 100644 --- a/testkit/src/main/scala/org/apache/pekko/testkit/package.scala +++ b/testkit/src/main/scala/org/apache/pekko/testkit/package.scala @@ -42,9 +42,8 @@ package object testkit { throw new AssertionError("Filter completion error:\n" + failed.mkString("\n")) result - } finally { + } finally system.eventStream.publish(TestEvent.UnMute(eventFilters.to(immutable.Seq))) - } } def filterEvents[T](eventFilters: EventFilter*)(block: => T)(implicit system: ActorSystem): T = diff --git a/testkit/src/test/scala/org/apache/pekko/testkit/Coroner.scala b/testkit/src/test/scala/org/apache/pekko/testkit/Coroner.scala index 2b3c1d50e27..bcf57a5290f 100644 --- a/testkit/src/test/scala/org/apache/pekko/testkit/Coroner.scala +++ b/testkit/src/test/scala/org/apache/pekko/testkit/Coroner.scala @@ -53,9 +53,8 @@ object Coroner { val startedLatch = new CountDownLatch(1) val finishedLatch = new CountDownLatch(1) - def waitForStart(): Unit = { + def waitForStart(): Unit = startedLatch.await(startAndStopDuration.length, startAndStopDuration.unit) - } def started(): Unit = startedLatch.countDown() @@ -74,9 +73,9 @@ object Coroner { } override def result(atMost: Duration)(implicit permit: CanAwait): Boolean = - try { + try Await.result(cancelPromise.future, atMost) - } catch { case _: TimeoutException => false } + catch { case _: TimeoutException => false } } @@ -106,19 +105,18 @@ object Coroner { out.println(s"Coroner Thread Count starts at $startThreads in $reportTitle") } watchedHandle.started() - try { + try if (!Await.result(watchedHandle, duration)) { watchedHandle.expired() out.println(s"Coroner not cancelled after ${duration.toMillis}ms. Looking for signs of foul play...") try printReport(reportTitle, out) catch { - case NonFatal(ex) => { + case NonFatal(ex) => out.println("Error displaying Coroner's Report") ex.printStackTrace(out) - } } } - } finally { + finally { if (displayThreadCounts) { val endThreads = threadMx.getThreadCount out.println( @@ -175,13 +173,12 @@ object Coroner { } } - def printThreadInfos(threadInfos: Seq[ThreadInfo]) = { + def printThreadInfos(threadInfos: Seq[ThreadInfo]) = if (threadInfos.isEmpty) { println("None") } else { - for (ti <- threadInfos.sortBy(_.getThreadName)) { println(threadInfoToString(ti)) } + for (ti <- threadInfos.sortBy(_.getThreadName)) println(threadInfoToString(ti)) } - } def threadInfoToString(ti: ThreadInfo): String = { val sb = new java.lang.StringBuilder @@ -270,14 +267,13 @@ trait WatchedByCoroner { @volatile private var coronerWatch: Coroner.WatchHandle = _ - final def startCoroner(): Unit = { + final def startCoroner(): Unit = coronerWatch = Coroner.watch( expectedTestDuration.dilated, getClass.getName, System.err, startAndStopDuration.dilated, displayThreadCounts) - } final def stopCoroner(): Unit = { coronerWatch.cancel() diff --git a/testkit/src/test/scala/org/apache/pekko/testkit/CoronerSpec.scala b/testkit/src/test/scala/org/apache/pekko/testkit/CoronerSpec.scala index 5e0d1111a89..f1041bf8540 100644 --- a/testkit/src/test/scala/org/apache/pekko/testkit/CoronerSpec.scala +++ b/testkit/src/test/scala/org/apache/pekko/testkit/CoronerSpec.scala @@ -37,30 +37,30 @@ class CoronerSpec extends AnyWordSpec with Matchers { "A Coroner" must { "generate a report if enough time passes" in { - val (_, report) = captureOutput(out => { + val (_, report) = captureOutput { out => val coroner = Coroner.watch(100.milliseconds, "XXXX", out) Await.ready(coroner, 5.seconds) coroner.cancel() - }) + } report should include("Coroner's Report") report should include("XXXX") } "not generate a report if cancelled early" in { - val (_, report) = captureOutput(out => { + val (_, report) = captureOutput { out => val coroner = Coroner.watch(60.seconds, "XXXX", out) coroner.cancel() Await.ready(coroner, 1.seconds) - }) + } report should ===("") } "display thread counts if enabled" in { - val (_, report) = captureOutput(out => { + val (_, report) = captureOutput { out => val coroner = Coroner.watch(60.seconds, "XXXX", out, displayThreadCounts = true) coroner.cancel() Await.ready(coroner, 1.second) - }) + } report should include("Coroner Thread Count starts at ") report should include("Coroner Thread Count started at ") report should include("XXXX") @@ -86,21 +86,18 @@ class CoronerSpec extends AnyWordSpec with Matchers { try recursiveLock(initialLocks) catch { case _: InterruptedException => () } - def recursiveLock(locks: List[ReentrantLock]): Unit = { + def recursiveLock(locks: List[ReentrantLock]): Unit = locks match { case Nil => () - case lock :: rest => { + case lock :: rest => ready.release() proceed.acquire() lock.lockInterruptibly() // Allows us to break deadlock and free threads - try { + try recursiveLock(rest) - } finally { + finally lock.unlock() - } - } } - } }, name) t.start() LockingThread(name, t, ready, proceed) diff --git a/testkit/src/test/scala/org/apache/pekko/testkit/PekkoSpec.scala b/testkit/src/test/scala/org/apache/pekko/testkit/PekkoSpec.scala index 807b2f556fd..de1c8b1ac1c 100644 --- a/testkit/src/test/scala/org/apache/pekko/testkit/PekkoSpec.scala +++ b/testkit/src/test/scala/org/apache/pekko/testkit/PekkoSpec.scala @@ -72,9 +72,8 @@ object PekkoSpec { /** * Get path's normalized path, which works on Windows too. */ - def normalizedPath(path: Path): String = { + def normalizedPath(path: Path): String = path.toAbsolutePath.normalize().toString.replace('\\', '/') - } } abstract class PekkoSpec(_system: ActorSystem) diff --git a/testkit/src/test/scala/org/apache/pekko/testkit/PekkoSpecSpec.scala b/testkit/src/test/scala/org/apache/pekko/testkit/PekkoSpecSpec.scala index 93442cc279b..617ad7358f9 100644 --- a/testkit/src/test/scala/org/apache/pekko/testkit/PekkoSpecSpec.scala +++ b/testkit/src/test/scala/org/apache/pekko/testkit/PekkoSpecSpec.scala @@ -41,9 +41,8 @@ class PekkoSpecSpec extends AnyWordSpec with Matchers { EventFilter.warning(start = "unhandled message", occurrences = 1).intercept { a ! 42 } - } finally { + } finally TestKit.shutdownActorSystem(system) - } } "terminate all actors" in { diff --git a/testkit/src/test/scala/org/apache/pekko/testkit/TestActorRefSpec.scala b/testkit/src/test/scala/org/apache/pekko/testkit/TestActorRefSpec.scala index 004dc16f46a..c573c99cf3e 100644 --- a/testkit/src/test/scala/org/apache/pekko/testkit/TestActorRefSpec.scala +++ b/testkit/src/test/scala/org/apache/pekko/testkit/TestActorRefSpec.scala @@ -52,11 +52,10 @@ object TestActorRefSpec { var replyTo: ActorRef = null def receiveT = { - case "complexRequest" => { + case "complexRequest" => replyTo = sender() val worker = TestActorRef(Props[WorkerActor]()) worker ! "work" - } case "complexRequest2" => val worker = TestActorRef(Props[WorkerActor]()) worker ! sender() @@ -84,12 +83,10 @@ object TestActorRefSpec { case "complex" => replyActor ! "complexRequest" case "complex2" => replyActor ! "complexRequest2" case "simple" => replyActor ! "simpleRequest" - case "complexReply" => { + case "complexReply" => counter -= 1 - } - case "simpleReply" => { + case "simpleReply" => counter -= 1 - } } } @@ -205,8 +202,8 @@ class TestActorRefSpec extends PekkoSpec("disp1.type=Dispatcher") with BeforeAnd val boss = TestActorRef(Props(new TActor { val ref = TestActorRef(Props(new TActor { def receiveT = { case _ => } - override def preRestart(reason: Throwable, msg: Option[Any]): Unit = { counter -= 1 } - override def postRestart(reason: Throwable): Unit = { counter -= 1 } + override def preRestart(reason: Throwable, msg: Option[Any]): Unit = counter -= 1 + override def postRestart(reason: Throwable): Unit = counter -= 1 }), self, "child") override def supervisorStrategy = diff --git a/testkit/src/test/scala/org/apache/pekko/testkit/TestProbeSpec.scala b/testkit/src/test/scala/org/apache/pekko/testkit/TestProbeSpec.scala index 7872c3483e3..7110c91a0b6 100644 --- a/testkit/src/test/scala/org/apache/pekko/testkit/TestProbeSpec.scala +++ b/testkit/src/test/scala/org/apache/pekko/testkit/TestProbeSpec.scala @@ -77,9 +77,8 @@ class TestProbeSpec extends PekkoSpec with DefaultTimeout with Eventually { throw new RuntimeException("simulated failure") } - override def postRestart(reason: Throwable): Unit = { + override def postRestart(reason: Throwable): Unit = restarts.incrementAndGet() - } } val probe = TestProbe() @@ -91,7 +90,7 @@ class TestProbeSpec extends PekkoSpec with DefaultTimeout with Eventually { } } - def assertFailureMessageContains(expectedHint: String)(block: => Unit): Unit = { + def assertFailureMessageContains(expectedHint: String)(block: => Unit): Unit = Try { block } match { @@ -103,7 +102,6 @@ class TestProbeSpec extends PekkoSpec with DefaultTimeout with Eventually { case scala.util.Success(result) => fail(s"expected failure but got: $result") } - } "throw AssertionError containing hint in its message if max await time is exceeded" in { val probe = TestProbe() diff --git a/testkit/src/test/scala/org/apache/pekko/testkit/TestTimeSpec.scala b/testkit/src/test/scala/org/apache/pekko/testkit/TestTimeSpec.scala index 49fd7fa9ed0..248e994c052 100644 --- a/testkit/src/test/scala/org/apache/pekko/testkit/TestTimeSpec.scala +++ b/testkit/src/test/scala/org/apache/pekko/testkit/TestTimeSpec.scala @@ -26,7 +26,7 @@ class TestTimeSpec extends PekkoSpec(Map("pekko.test.timefactor" -> 2.0)) { val probe = TestProbe() val now = System.nanoTime - intercept[AssertionError] { probe.awaitCond(false, 1.second) } + intercept[AssertionError](probe.awaitCond(false, 1.second)) val diff = System.nanoTime - now val target = (1000000000L * testKitSettings.TestTimeFactor).toLong diff should be >= target diff --git a/testkit/src/test/scala/org/apache/pekko/testkit/WithLogCapturing.scala b/testkit/src/test/scala/org/apache/pekko/testkit/WithLogCapturing.scala index bd695bbecf6..09aed3975eb 100644 --- a/testkit/src/test/scala/org/apache/pekko/testkit/WithLogCapturing.scala +++ b/testkit/src/test/scala/org/apache/pekko/testkit/WithLogCapturing.scala @@ -51,7 +51,7 @@ trait WithLogCapturing extends SuiteMixin { this: TestSuite => if (!(res.isSucceeded || res.isPending)) { println(s"--> [${Console.BLUE}${test.name}${Console.RESET}] Start of log messages of test that [$res]") val logger = new StdOutLogger {} - withPrefixedOut("| ") { events.reverse.foreach(logger.print) } + withPrefixedOut("| ")(events.reverse.foreach(logger.print)) println(s"<-- [${Console.BLUE}${test.name}${Console.RESET}] End of log messages of test that [$res]") } diff --git a/testkit/src/test/scala/org/apache/pekko/testkit/metrics/FileDescriptorMetricSet.scala b/testkit/src/test/scala/org/apache/pekko/testkit/metrics/FileDescriptorMetricSet.scala index 1a77b1ceac7..132abc8e0be 100644 --- a/testkit/src/test/scala/org/apache/pekko/testkit/metrics/FileDescriptorMetricSet.scala +++ b/testkit/src/test/scala/org/apache/pekko/testkit/metrics/FileDescriptorMetricSet.scala @@ -28,14 +28,13 @@ import org.apache.pekko.util.ccompat.JavaConverters._ private[pekko] class FileDescriptorMetricSet(os: OperatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean) extends MetricSet { - override def getMetrics: util.Map[String, Metric] = { + override def getMetrics: util.Map[String, Metric] = Map[String, Metric](name("file-descriptors", "open") -> new Gauge[Long] { override def getValue: Long = invoke("getOpenFileDescriptorCount") }, name("file-descriptors", "max") -> new Gauge[Long] { override def getValue: Long = invoke("getMaxFileDescriptorCount") }, name("file-descriptors", "ratio") -> new FileDescriptorRatioGauge(os)).asJava - } private def invoke(name: String): Long = { val method = os.getClass.getDeclaredMethod(name) diff --git a/testkit/src/test/scala/org/apache/pekko/testkit/metrics/HdrHistogram.scala b/testkit/src/test/scala/org/apache/pekko/testkit/metrics/HdrHistogram.scala index f988f5845f6..44fa7bcd9fa 100644 --- a/testkit/src/test/scala/org/apache/pekko/testkit/metrics/HdrHistogram.scala +++ b/testkit/src/test/scala/org/apache/pekko/testkit/metrics/HdrHistogram.scala @@ -33,19 +33,17 @@ private[pekko] class HdrHistogram( private val hist = new hdr.Histogram(highestTrackableValue, numberOfSignificantValueDigits) - def update(value: Long): Unit = { + def update(value: Long): Unit = try hist.recordValue(value) catch { case ex: ArrayIndexOutOfBoundsException => throw wrapHistogramOutOfBoundsException(value, ex) } - } - def updateWithCount(value: Long, count: Long): Unit = { + def updateWithCount(value: Long, count: Long): Unit = try hist.recordValueWithCount(value, count) catch { case ex: ArrayIndexOutOfBoundsException => throw wrapHistogramOutOfBoundsException(value, ex) } - } private def wrapHistogramOutOfBoundsException( value: Long, diff --git a/testkit/src/test/scala/org/apache/pekko/testkit/metrics/MetricsKit.scala b/testkit/src/test/scala/org/apache/pekko/testkit/metrics/MetricsKit.scala index 4fccefcf1b3..1770035a905 100644 --- a/testkit/src/test/scala/org/apache/pekko/testkit/metrics/MetricsKit.scala +++ b/testkit/src/test/scala/org/apache/pekko/testkit/metrics/MetricsKit.scala @@ -62,7 +62,7 @@ private[pekko] trait MetricsKit extends MetricsKitOps { def initMetricReporters(): Unit = { val settings = new MetricsKitSettings(metricsConfig) - def configureConsoleReporter(): Unit = { + def configureConsoleReporter(): Unit = if (settings.Reporters.contains("console")) { val pekkoConsoleReporter = new PekkoConsoleReporter(registry, settings.ConsoleReporter.Verbose) @@ -71,7 +71,6 @@ private[pekko] trait MetricsKit extends MetricsKitOps { reporters ::= pekkoConsoleReporter } - } configureConsoleReporter() } @@ -79,9 +78,8 @@ private[pekko] trait MetricsKit extends MetricsKitOps { /** * Schedule metric reports execution iterval. Should not be used multiple times */ - def scheduleMetricReports(every: FiniteDuration): Unit = { - reporters.foreach { _.start(every.toMillis, TimeUnit.MILLISECONDS) } - } + def scheduleMetricReports(every: FiniteDuration): Unit = + reporters.foreach(_.start(every.toMillis, TimeUnit.MILLISECONDS)) def registeredMetrics = registry.getMetrics.asScala @@ -103,10 +101,9 @@ private[pekko] trait MetricsKit extends MetricsKitOps { * * HINT: this operation can be costy, run outside of your tested code, or rely on scheduled reporting. */ - def reportMetrics(): Unit = { + def reportMetrics(): Unit = if (reportMetricsEnabled) - reporters.foreach { _.report() } - } + reporters.foreach(_.report()) /** * Causes immediate flush of only memory related metrics, using all registered reporters. @@ -116,7 +113,7 @@ private[pekko] trait MetricsKit extends MetricsKitOps { def reportMemoryMetrics(): Unit = { val gauges = registry.getGauges(MemMetricsFilter) - reporters.foreach { _.report(gauges, empty, empty, empty, empty) } + reporters.foreach(_.report(gauges, empty, empty, empty, empty)) } /** @@ -127,7 +124,7 @@ private[pekko] trait MetricsKit extends MetricsKitOps { def reportGcMetrics(): Unit = { val gauges = registry.getGauges(GcMetricsFilter) - reporters.foreach { _.report(gauges, empty, empty, empty, empty) } + reporters.foreach(_.report(gauges, empty, empty, empty, empty)) } /** @@ -138,7 +135,7 @@ private[pekko] trait MetricsKit extends MetricsKitOps { def reportFileDescriptorMetrics(): Unit = { val gauges = registry.getGauges(FileDescriptorMetricsFilter) - reporters.foreach { _.report(gauges, empty, empty, empty, empty) } + reporters.foreach(_.report(gauges, empty, empty, empty, empty)) } /** @@ -149,16 +146,14 @@ private[pekko] trait MetricsKit extends MetricsKitOps { * Please note that, if you have registered a `timer("thing")` previously, you will need to call `timer("thing")` again, * in order to register a new timer. */ - def clearMetrics(matching: MetricFilter = MetricFilter.ALL): Unit = { + def clearMetrics(matching: MetricFilter = MetricFilter.ALL): Unit = registry.removeMatching(matching) - } /** * MUST be called after all tests have finished. */ - def shutdownMetrics(): Unit = { - reporters.foreach { _.stop() } - } + def shutdownMetrics(): Unit = + reporters.foreach(_.stop()) private[metrics] def getOrRegister[M <: Metric](key: String, metric: => M)(implicit tag: ClassTag[M]): M = { import pekko.util.ccompat.JavaConverters._ diff --git a/testkit/src/test/scala/org/apache/pekko/testkit/metrics/MetricsKitOps.scala b/testkit/src/test/scala/org/apache/pekko/testkit/metrics/MetricsKitOps.scala index 73ea03bdeee..3bf2b00fe60 100644 --- a/testkit/src/test/scala/org/apache/pekko/testkit/metrics/MetricsKitOps.scala +++ b/testkit/src/test/scala/org/apache/pekko/testkit/metrics/MetricsKitOps.scala @@ -69,17 +69,15 @@ private[pekko] trait MetricsKitOps extends MetricKeyDSL { * * Backed by codahale `ExponentiallyDecayingReservoir`. */ - def histogram(key: MetricKeyType): Histogram = { + def histogram(key: MetricKeyType): Histogram = registry.histogram((key / "histogram").toString) - } def forceGcEnabled: Boolean = true /** Yet another delegate to `System.gc()` */ - def gc(): Unit = { + def gc(): Unit = if (forceGcEnabled) System.gc() - } /** * Enable memory measurements - will be logged by `ScheduledReporter`s if enabled. diff --git a/testkit/src/test/scala/org/apache/pekko/testkit/metrics/MetricsKitSpec.scala b/testkit/src/test/scala/org/apache/pekko/testkit/metrics/MetricsKitSpec.scala index 6a8fc2b13e1..4b9b874b671 100644 --- a/testkit/src/test/scala/org/apache/pekko/testkit/metrics/MetricsKitSpec.scala +++ b/testkit/src/test/scala/org/apache/pekko/testkit/metrics/MetricsKitSpec.scala @@ -30,9 +30,8 @@ class MetricsKitSpec extends AnyWordSpec with Matchers with BeforeAndAfter with clearMetrics() } - override def afterAll(): Unit = { + override def afterAll(): Unit = shutdownMetrics() - } "MetricsKit" must { diff --git a/testkit/src/test/scala/org/apache/pekko/testkit/metrics/reporter/PekkoConsoleReporter.scala b/testkit/src/test/scala/org/apache/pekko/testkit/metrics/reporter/PekkoConsoleReporter.scala index 651985f0f44..8aef274668c 100644 --- a/testkit/src/test/scala/org/apache/pekko/testkit/metrics/reporter/PekkoConsoleReporter.scala +++ b/testkit/src/test/scala/org/apache/pekko/testkit/metrics/reporter/PekkoConsoleReporter.scala @@ -59,7 +59,7 @@ class PekkoConsoleReporter(registry: PekkoMetricRegistry, verbose: Boolean, outp output.flush() } - def printMetrics[T <: Metric](metrics: Iterable[(String, T)], printer: T => Unit): Unit = { + def printMetrics[T <: Metric](metrics: Iterable[(String, T)], printer: T => Unit): Unit = if (metrics.nonEmpty) { printWithBanner(s"-- ${simpleName(metrics.head._2.getClass)}", '-') for ((key, metric) <- metrics) { @@ -68,7 +68,6 @@ class PekkoConsoleReporter(registry: PekkoMetricRegistry, verbose: Boolean, outp } output.println() } - } private def printMeter(meter: Meter): Unit = { output.print(" count = %d%n".format(meter.getCount)) @@ -78,13 +77,11 @@ class PekkoConsoleReporter(registry: PekkoMetricRegistry, verbose: Boolean, outp output.print(" 15-minute rate = %2.2f events/%s%n".format(convertRate(meter.getFifteenMinuteRate), getRateUnit)) } - private def printCounter(entry: Counter): Unit = { + private def printCounter(entry: Counter): Unit = output.print(" count = %d%n".format(entry.getCount)) - } - private def printGauge(entry: Gauge[_]): Unit = { + private def printGauge(entry: Gauge[_]): Unit = output.print(" value = %s%n".format(entry.getValue)) - } private def printHistogram(histogram: Histogram): Unit = { val snapshot = histogram.getSnapshot @@ -152,9 +149,8 @@ class PekkoConsoleReporter(registry: PekkoMetricRegistry, verbose: Boolean, outp data.outputPercentileDistribution(output, 1) } - private def printAveragingGauge(gauge: AveragingGauge): Unit = { + private def printAveragingGauge(gauge: AveragingGauge): Unit = output.print(" avg = %2.2f%n".format(gauge.getValue())) - } private def printWithBanner(s: String, c: Char): Unit = { output.print(s)