format source with scalafmt, #26511

This commit is contained in:
Auto Format 2019-03-13 10:56:20 +01:00 committed by Patrik Nordwall
parent 2ba9b988df
commit 75579bed17
779 changed files with 15729 additions and 13096 deletions

View file

@ -17,20 +17,22 @@ import scala.compat.java8.OptionConverters._
/**
* Representation of a Log Event issued by a [[akka.actor.typed.Behavior]]
*/
final case class CapturedLogEvent(logLevel: LogLevel,
message: String,
cause: Option[Throwable],
marker: Option[LogMarker],
mdc: Map[String, Any]) {
final case class CapturedLogEvent(
logLevel: LogLevel,
message: String,
cause: Option[Throwable],
marker: Option[LogMarker],
mdc: Map[String, Any]) {
/**
* Constructor for Java API
*/
def this(logLevel: LogLevel,
message: String,
errorCause: Optional[Throwable],
marker: Optional[LogMarker],
mdc: java.util.Map[String, Any]) {
def this(
logLevel: LogLevel,
message: String,
errorCause: Optional[Throwable],
marker: Optional[LogMarker],
mdc: java.util.Map[String, Any]) {
this(logLevel, message, errorCause.asScala, marker.asScala, mdc.asScala.toMap)
}
@ -88,11 +90,12 @@ object CapturedLogEvent {
* INTERNAL API
*/
@InternalApi
private[akka] def apply(logLevel: LogLevel,
message: String,
errorCause: OptionVal[Throwable],
logMarker: OptionVal[LogMarker],
mdc: Map[String, Any]): CapturedLogEvent = {
private[akka] def apply(
logLevel: LogLevel,
message: String,
errorCause: OptionVal[Throwable],
logMarker: OptionVal[LogMarker],
mdc: Map[String, Any]): CapturedLogEvent = {
new CapturedLogEvent(logLevel, message, toOption(errorCause), toOption(logMarker), mdc)
}
}

View file

@ -69,13 +69,15 @@ private[akka] final class FunctionRef[-T](override val path: ActorPath, send: (T
override def isInfoEnabled(marker: LogMarker): Boolean = true
override def isDebugEnabled(marker: LogMarker): Boolean = true
override private[akka] def notifyError(message: String,
cause: OptionVal[Throwable],
marker: OptionVal[LogMarker]): Unit =
override private[akka] def notifyError(
message: String,
cause: OptionVal[Throwable],
marker: OptionVal[LogMarker]): Unit =
logBuffer = CapturedLogEvent(Logging.ErrorLevel, message, cause, marker, mdc) :: logBuffer
override private[akka] def notifyWarning(message: String,
cause: OptionVal[Throwable],
marker: OptionVal[LogMarker]): Unit =
override private[akka] def notifyWarning(
message: String,
cause: OptionVal[Throwable],
marker: OptionVal[LogMarker]): Unit =
logBuffer = CapturedLogEvent(Logging.WarningLevel, message, OptionVal.None, marker, mdc) :: logBuffer
override private[akka] def notifyInfo(message: String, marker: OptionVal[LogMarker]): Unit =
@ -111,18 +113,20 @@ private[akka] final class FunctionRef[-T](override val path: ActorPath, send: (T
override def isInfoEnabled(marker: LogMarker): Boolean = actual.isInfoEnabled(marker)
override def isDebugEnabled(marker: LogMarker): Boolean = actual.isDebugEnabled(marker)
override private[akka] def notifyError(message: String,
cause: OptionVal[Throwable],
marker: OptionVal[LogMarker]): Unit = {
override private[akka] def notifyError(
message: String,
cause: OptionVal[Throwable],
marker: OptionVal[LogMarker]): Unit = {
val original = actual.mdc
actual.mdc = mdc
actual.notifyError(message, cause, marker)
actual.mdc = original
}
override private[akka] def notifyWarning(message: String,
cause: OptionVal[Throwable],
marker: OptionVal[LogMarker]): Unit = {
override private[akka] def notifyWarning(
message: String,
cause: OptionVal[Throwable],
marker: OptionVal[LogMarker]): Unit = {
val original = actual.mdc
actual.mdc = mdc
actual.notifyWarning(message, cause, marker)

View file

@ -266,9 +266,10 @@ private[akka] final class TestProbeImpl[M](name: String, system: ActorSystem[_])
override def fishForMessage(max: JDuration, fisher: java.util.function.Function[M, FishingOutcome]): JList[M] =
fishForMessage(max, "", fisher)
override def fishForMessage(max: JDuration,
hint: String,
fisher: java.util.function.Function[M, FishingOutcome]): JList[M] =
override def fishForMessage(
max: JDuration,
hint: String,
fisher: java.util.function.Function[M, FishingOutcome]): JList[M] =
fishForMessage_internal(max.asScala.dilated, hint, fisher.apply).asJava
private def fishForMessage_internal(max: FiniteDuration, hint: String, fisher: M => FishingOutcome): List[M] = {
@ -281,9 +282,10 @@ private[akka] final class TestProbeImpl[M](name: String, system: ActorSystem[_])
try fisher(message)
catch {
case ex: MatchError =>
throw new AssertionError(s"Unexpected message $message while fishing for messages, " +
s"seen messages ${seen.reverse}, hint: $hint",
ex)
throw new AssertionError(
s"Unexpected message $message while fishing for messages, " +
s"seen messages ${seen.reverse}, hint: $hint",
ex)
}
outcome match {
case FishingOutcome.Complete => (message :: seen).reverse

View file

@ -44,8 +44,9 @@ final class TestKitJunitResource(_kit: ActorTestKit) extends ExternalResource {
*/
def this(customConfig: String) =
this(
ActorTestKit.create(TestKitUtils.testNameFromCallStack(classOf[TestKitJunitResource]),
ConfigFactory.parseString(customConfig)))
ActorTestKit.create(
TestKitUtils.testNameFromCallStack(classOf[TestKitJunitResource]),
ConfigFactory.parseString(customConfig)))
/**
* Use a custom config for the actor system.

View file

@ -215,9 +215,10 @@ abstract class TestProbe[M] {
/**
* Same as the other `fishForMessage` but includes the provided hint in all error messages
*/
def fishForMessage(max: Duration,
hint: String,
fisher: java.util.function.Function[M, FishingOutcome]): java.util.List[M]
def fishForMessage(
max: Duration,
hint: String,
fisher: java.util.function.Function[M, FishingOutcome]): java.util.List[M]
/**
* Expect the given actor to be stopped or stop within the given timeout or

View file

@ -29,9 +29,10 @@ object ActorTestKit {
* the testkit with [[ActorTestKit#shutdownTestKit]].
*/
def apply(): ActorTestKit =
new ActorTestKit(name = TestKitUtils.testNameFromCallStack(classOf[ActorTestKit]),
config = noConfigSet,
settings = None)
new ActorTestKit(
name = TestKitUtils.testNameFromCallStack(classOf[ActorTestKit]),
config = noConfigSet,
settings = None)
/**
* Create a named testkit.
@ -119,9 +120,10 @@ final class ActorTestKit private[akka] (val name: String, val config: Config, se
implicit val timeout: Timeout = testKitSettings.DefaultTimeout
def shutdownTestKit(): Unit = {
ActorTestKit.shutdown(system,
testKitSettings.DefaultActorSystemShutdownTimeout,
testKitSettings.ThrowOnShutdownTimeout)
ActorTestKit.shutdown(
system,
testKitSettings.DefaultActorSystemShutdownTimeout,
testKitSettings.ThrowOnShutdownTimeout)
}
/**

View file

@ -251,14 +251,15 @@ class ActorLookupSpec extends AkkaSpec with DefaultTimeout {
}
def check(looker: ActorRef): Unit = {
val lookname = looker.path.elements.mkString("", "/", "/")
for ((l, r) <- Seq(LookupString("a/b/c") -> empty(lookname + "a/b/c"),
LookupString("") -> system.deadLetters,
LookupString("akka://all-systems/Nobody") -> system.deadLetters,
LookupPath(system / "hallo") -> empty("user/hallo"),
LookupPath(looker.path.child("hallo")) -> empty(lookname + "hallo"), // test Java API
LookupPath(looker.path.descendant(Seq("a", "b").asJava)) -> empty(lookname + "a/b"), // test Java API
LookupElems(Seq()) -> system.deadLetters,
LookupElems(Seq("a")) -> empty(lookname + "a"))) checkOne(looker, l, r)
for ((l, r) <- Seq(
LookupString("a/b/c") -> empty(lookname + "a/b/c"),
LookupString("") -> system.deadLetters,
LookupString("akka://all-systems/Nobody") -> system.deadLetters,
LookupPath(system / "hallo") -> empty("user/hallo"),
LookupPath(looker.path.child("hallo")) -> empty(lookname + "hallo"), // test Java API
LookupPath(looker.path.descendant(Seq("a", "b").asJava)) -> empty(lookname + "a/b"), // test Java API
LookupElems(Seq()) -> system.deadLetters,
LookupElems(Seq("a")) -> empty(lookname + "a"))) checkOne(looker, l, r)
}
for (looker <- all) check(looker)
}

View file

@ -189,20 +189,24 @@ object ActorMailboxSpec {
val UnboundedMailboxTypes = Seq(classOf[UnboundedMessageQueueSemantics])
val BoundedMailboxTypes = Seq(classOf[BoundedMessageQueueSemantics])
val UnboundedDeqMailboxTypes = Seq(classOf[DequeBasedMessageQueueSemantics],
classOf[UnboundedMessageQueueSemantics],
classOf[UnboundedDequeBasedMessageQueueSemantics])
val UnboundedDeqMailboxTypes = Seq(
classOf[DequeBasedMessageQueueSemantics],
classOf[UnboundedMessageQueueSemantics],
classOf[UnboundedDequeBasedMessageQueueSemantics])
val BoundedDeqMailboxTypes = Seq(classOf[DequeBasedMessageQueueSemantics],
classOf[BoundedMessageQueueSemantics],
classOf[BoundedDequeBasedMessageQueueSemantics])
val BoundedDeqMailboxTypes = Seq(
classOf[DequeBasedMessageQueueSemantics],
classOf[BoundedMessageQueueSemantics],
classOf[BoundedDequeBasedMessageQueueSemantics])
val BoundedControlAwareMailboxTypes = Seq(classOf[BoundedMessageQueueSemantics],
classOf[ControlAwareMessageQueueSemantics],
classOf[BoundedControlAwareMessageQueueSemantics])
val UnboundedControlAwareMailboxTypes = Seq(classOf[UnboundedMessageQueueSemantics],
classOf[ControlAwareMessageQueueSemantics],
classOf[UnboundedControlAwareMessageQueueSemantics])
val BoundedControlAwareMailboxTypes = Seq(
classOf[BoundedMessageQueueSemantics],
classOf[ControlAwareMessageQueueSemantics],
classOf[BoundedControlAwareMessageQueueSemantics])
val UnboundedControlAwareMailboxTypes = Seq(
classOf[UnboundedMessageQueueSemantics],
classOf[ControlAwareMessageQueueSemantics],
classOf[UnboundedControlAwareMessageQueueSemantics])
trait MCBoundedMessageQueueSemantics extends MessageQueue with MultipleConsumerSemantics
final case class MCBoundedMailbox(val capacity: Int, val pushTimeOut: FiniteDuration)
@ -240,9 +244,10 @@ class ActorMailboxSpec(conf: Config) extends AkkaSpec(conf) with DefaultTimeout
}
"get an unbounded deque message queue when it is only configured on the props" in {
checkMailboxQueue(Props[QueueReportingActor].withMailbox("akka.actor.mailbox.unbounded-deque-based"),
"default-override-from-props",
UnboundedDeqMailboxTypes)
checkMailboxQueue(
Props[QueueReportingActor].withMailbox("akka.actor.mailbox.unbounded-deque-based"),
"default-override-from-props",
UnboundedDeqMailboxTypes)
}
"get an bounded message queue when it's only configured with RequiresMailbox" in {
@ -252,12 +257,14 @@ class ActorMailboxSpec(conf: Config) extends AkkaSpec(conf) with DefaultTimeout
"get an unbounded deque message queue when it's only mixed with Stash" in {
checkMailboxQueue(Props[StashQueueReportingActor], "default-override-from-stash", UnboundedDeqMailboxTypes)
checkMailboxQueue(Props(new StashQueueReportingActor), "default-override-from-stash2", UnboundedDeqMailboxTypes)
checkMailboxQueue(Props(classOf[StashQueueReportingActorWithParams], 17, "hello"),
"default-override-from-stash3",
UnboundedDeqMailboxTypes)
checkMailboxQueue(Props(new StashQueueReportingActorWithParams(17, "hello")),
"default-override-from-stash4",
UnboundedDeqMailboxTypes)
checkMailboxQueue(
Props(classOf[StashQueueReportingActorWithParams], 17, "hello"),
"default-override-from-stash3",
UnboundedDeqMailboxTypes)
checkMailboxQueue(
Props(new StashQueueReportingActorWithParams(17, "hello")),
"default-override-from-stash4",
UnboundedDeqMailboxTypes)
}
"get a bounded message queue when it's configured as mailbox" in {
@ -273,21 +280,24 @@ class ActorMailboxSpec(conf: Config) extends AkkaSpec(conf) with DefaultTimeout
}
"get an unbounded control aware message queue when it's configured as mailbox" in {
checkMailboxQueue(Props[QueueReportingActor],
"default-unbounded-control-aware",
UnboundedControlAwareMailboxTypes)
checkMailboxQueue(
Props[QueueReportingActor],
"default-unbounded-control-aware",
UnboundedControlAwareMailboxTypes)
}
"get an bounded control aware message queue when it's only configured with RequiresMailbox" in {
checkMailboxQueue(Props[BoundedControlAwareQueueReportingActor],
"default-override-from-trait-bounded-control-aware",
BoundedControlAwareMailboxTypes)
checkMailboxQueue(
Props[BoundedControlAwareQueueReportingActor],
"default-override-from-trait-bounded-control-aware",
BoundedControlAwareMailboxTypes)
}
"get an unbounded control aware message queue when it's only configured with RequiresMailbox" in {
checkMailboxQueue(Props[UnboundedControlAwareQueueReportingActor],
"default-override-from-trait-unbounded-control-aware",
UnboundedControlAwareMailboxTypes)
checkMailboxQueue(
Props[UnboundedControlAwareQueueReportingActor],
"default-override-from-trait-unbounded-control-aware",
UnboundedControlAwareMailboxTypes)
}
"fail to create actor when an unbounded dequeu message queue is configured as mailbox overriding RequestMailbox" in {
@ -313,9 +323,10 @@ class ActorMailboxSpec(conf: Config) extends AkkaSpec(conf) with DefaultTimeout
}
"get a bounded message queue with 0 push timeout when defined in dispatcher" in {
val q = checkMailboxQueue(Props[QueueReportingActor],
"default-bounded-mailbox-with-zero-pushtimeout",
BoundedMailboxTypes)
val q = checkMailboxQueue(
Props[QueueReportingActor],
"default-bounded-mailbox-with-zero-pushtimeout",
BoundedMailboxTypes)
q.asInstanceOf[BoundedMessageQueueSemantics].pushTimeOut should ===(Duration.Zero)
}
@ -324,15 +335,17 @@ class ActorMailboxSpec(conf: Config) extends AkkaSpec(conf) with DefaultTimeout
}
"get an unbounded message queue overriding configuration on the props" in {
checkMailboxQueue(Props[QueueReportingActor].withMailbox("akka.actor.mailbox.unbounded-deque-based"),
"bounded-unbounded-override-props",
UnboundedMailboxTypes)
checkMailboxQueue(
Props[QueueReportingActor].withMailbox("akka.actor.mailbox.unbounded-deque-based"),
"bounded-unbounded-override-props",
UnboundedMailboxTypes)
}
"get a bounded deque-based message queue if configured and required" in {
checkMailboxQueue(Props[StashQueueReportingActor],
"bounded-deque-requirements-configured",
BoundedDeqMailboxTypes)
checkMailboxQueue(
Props[StashQueueReportingActor],
"bounded-deque-requirements-configured",
BoundedDeqMailboxTypes)
}
"fail with a unbounded deque-based message queue if configured and required" in {
@ -365,38 +378,44 @@ class ActorMailboxSpec(conf: Config) extends AkkaSpec(conf) with DefaultTimeout
"fail with a bounded deque-based message queue if not configured with Props" in {
intercept[ConfigurationException](
system.actorOf(Props[StashQueueReportingActor].withDispatcher("requiring-bounded-dispatcher"),
"bounded-deque-require-unbounded-unconfigured-props"))
system.actorOf(
Props[StashQueueReportingActor].withDispatcher("requiring-bounded-dispatcher"),
"bounded-deque-require-unbounded-unconfigured-props"))
}
"get a bounded deque-based message queue if configured and required with Props (dispatcher)" in {
checkMailboxQueue(Props[StashQueueReportingActor].withDispatcher("requiring-bounded-dispatcher"),
"bounded-deque-requirements-configured-props-disp",
BoundedDeqMailboxTypes)
checkMailboxQueue(
Props[StashQueueReportingActor].withDispatcher("requiring-bounded-dispatcher"),
"bounded-deque-requirements-configured-props-disp",
BoundedDeqMailboxTypes)
}
"fail with a unbounded deque-based message queue if configured and required with Props (dispatcher)" in {
intercept[ConfigurationException](
system.actorOf(Props[StashQueueReportingActor].withDispatcher("requiring-bounded-dispatcher"),
"bounded-deque-require-unbounded-configured-props-disp"))
system.actorOf(
Props[StashQueueReportingActor].withDispatcher("requiring-bounded-dispatcher"),
"bounded-deque-require-unbounded-configured-props-disp"))
}
"fail with a bounded deque-based message queue if not configured with Props (dispatcher)" in {
intercept[ConfigurationException](
system.actorOf(Props[StashQueueReportingActor].withDispatcher("requiring-bounded-dispatcher"),
"bounded-deque-require-unbounded-unconfigured-props-disp"))
system.actorOf(
Props[StashQueueReportingActor].withDispatcher("requiring-bounded-dispatcher"),
"bounded-deque-require-unbounded-unconfigured-props-disp"))
}
"get a bounded deque-based message queue if configured and required with Props (mailbox)" in {
checkMailboxQueue(Props[StashQueueReportingActor].withMailbox("akka.actor.mailbox.bounded-deque-based"),
"bounded-deque-requirements-configured-props-mail",
BoundedDeqMailboxTypes)
checkMailboxQueue(
Props[StashQueueReportingActor].withMailbox("akka.actor.mailbox.bounded-deque-based"),
"bounded-deque-requirements-configured-props-mail",
BoundedDeqMailboxTypes)
}
"fail with a unbounded deque-based message queue if configured and required with Props (mailbox)" in {
intercept[ConfigurationException](
system.actorOf(Props[StashQueueReportingActor].withMailbox("akka.actor.mailbox.unbounded-deque-based"),
"bounded-deque-require-unbounded-configured-props-mail"))
system.actorOf(
Props[StashQueueReportingActor].withMailbox("akka.actor.mailbox.unbounded-deque-based"),
"bounded-deque-require-unbounded-configured-props-mail"))
}
"fail with a bounded deque-based message queue if not configured with Props (mailbox)" in {
@ -405,21 +424,24 @@ class ActorMailboxSpec(conf: Config) extends AkkaSpec(conf) with DefaultTimeout
}
"get an unbounded message queue with a balancing dispatcher" in {
checkMailboxQueue(Props[QueueReportingActor].withDispatcher("balancing-dispatcher"),
"unbounded-balancing",
UnboundedMailboxTypes)
checkMailboxQueue(
Props[QueueReportingActor].withDispatcher("balancing-dispatcher"),
"unbounded-balancing",
UnboundedMailboxTypes)
}
"get a bounded message queue with a balancing bounded dispatcher" in {
checkMailboxQueue(Props[QueueReportingActor].withDispatcher("balancing-bounded-dispatcher"),
"bounded-balancing",
BoundedMailboxTypes)
checkMailboxQueue(
Props[QueueReportingActor].withDispatcher("balancing-bounded-dispatcher"),
"bounded-balancing",
BoundedMailboxTypes)
}
"get a bounded message queue with a requiring balancing bounded dispatcher" in {
checkMailboxQueue(Props[QueueReportingActor].withDispatcher("requiring-balancing-bounded-dispatcher"),
"requiring-bounded-balancing",
BoundedMailboxTypes)
checkMailboxQueue(
Props[QueueReportingActor].withDispatcher("requiring-balancing-bounded-dispatcher"),
"requiring-bounded-balancing",
BoundedMailboxTypes)
}
}
}

View file

@ -252,11 +252,12 @@ class ActorSelectionSpec extends AkkaSpec with DefaultTimeout {
}
def check(looker: ActorRef): Unit = {
val lookname = looker.path.elements.mkString("", "/", "/")
for ((l, r) <- Seq(SelectString("a/b/c") -> None,
SelectString("akka://all-systems/Nobody") -> None,
SelectPath(system / "hallo") -> None,
SelectPath(looker.path.child("hallo")) -> None, // test Java API
SelectPath(looker.path.descendant(Seq("a", "b").asJava)) -> None) // test Java API
for ((l, r) <- Seq(
SelectString("a/b/c") -> None,
SelectString("akka://all-systems/Nobody") -> None,
SelectPath(system / "hallo") -> None,
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)

View file

@ -75,16 +75,18 @@ object ActorSystemSpec {
class SlowDispatcher(_config: Config, _prerequisites: DispatcherPrerequisites)
extends MessageDispatcherConfigurator(_config, _prerequisites) {
private val instance = new Dispatcher(this,
config.getString("id"),
config.getInt("throughput"),
config.getNanosDuration("throughput-deadline-time"),
configureExecutor(),
config.getMillisDuration("shutdown-timeout")) {
private val instance = new Dispatcher(
this,
config.getString("id"),
config.getInt("throughput"),
config.getNanosDuration("throughput-deadline-time"),
configureExecutor(),
config.getMillisDuration("shutdown-timeout")) {
val doneIt = new Switch
override protected[akka] def registerForExecution(mbox: Mailbox,
hasMessageHint: Boolean,
hasSystemMessageHint: Boolean): Boolean = {
override protected[akka] def registerForExecution(
mbox: Mailbox,
hasMessageHint: Boolean,
hasSystemMessageHint: Boolean): Boolean = {
val ret = super.registerForExecution(mbox, hasMessageHint, hasSystemMessageHint)
doneIt.switchOn {
TestKit.awaitCond(mbox.actor.actor != null, 1.second)
@ -134,14 +136,15 @@ class ActorSystemSpec extends AkkaSpec(ActorSystemSpec.config) with ImplicitSend
}
"reject invalid names" in {
for (n <- Seq("-hallowelt",
"_hallowelt",
"hallo*welt",
"hallo@welt",
"hallo#welt",
"hallo$welt",
"hallo%welt",
"hallo/welt")) intercept[IllegalArgumentException] {
for (n <- Seq(
"-hallowelt",
"_hallowelt",
"hallo*welt",
"hallo@welt",
"hallo#welt",
"hallo$welt",
"hallo%welt",
"hallo/welt")) intercept[IllegalArgumentException] {
ActorSystem(n)
}
}
@ -163,8 +166,9 @@ class ActorSystemSpec extends AkkaSpec(ActorSystemSpec.config) with ImplicitSend
.info(pattern = """from Actor\[akka://LogDeadLetters/system/testProbe.*not delivered""", occurrences = 1)
.intercept {
EventFilter
.warning(pattern = """received dead letter from Actor\[akka://LogDeadLetters/system/testProbe""",
occurrences = 1)
.warning(
pattern = """received dead letter from Actor\[akka://LogDeadLetters/system/testProbe""",
occurrences = 1)
.intercept {
a.tell("boom", probe.ref)
}(sys)
@ -321,10 +325,11 @@ class ActorSystemSpec extends AkkaSpec(ActorSystemSpec.config) with ImplicitSend
"allow configuration of guardian supervisor strategy" in {
implicit val system =
ActorSystem("Stop",
ConfigFactory
.parseString("akka.actor.guardian-supervisor-strategy=akka.actor.StoppingSupervisorStrategy")
.withFallback(AkkaSpec.testConf))
ActorSystem(
"Stop",
ConfigFactory
.parseString("akka.actor.guardian-supervisor-strategy=akka.actor.StoppingSupervisorStrategy")
.withFallback(AkkaSpec.testConf))
val a = system.actorOf(Props(new Actor {
def receive = {
case "die" => throw new Exception("hello")
@ -343,10 +348,11 @@ class ActorSystemSpec extends AkkaSpec(ActorSystemSpec.config) with ImplicitSend
"shut down when /user escalates" in {
implicit val system =
ActorSystem("Stop",
ConfigFactory
.parseString("akka.actor.guardian-supervisor-strategy=\"akka.actor.ActorSystemSpec$Strategy\"")
.withFallback(AkkaSpec.testConf))
ActorSystem(
"Stop",
ConfigFactory
.parseString("akka.actor.guardian-supervisor-strategy=\"akka.actor.ActorSystemSpec$Strategy\"")
.withFallback(AkkaSpec.testConf))
val a = system.actorOf(Props(new Actor {
def receive = {
case "die" => throw new Exception("hello")
@ -403,12 +409,13 @@ class ActorSystemSpec extends AkkaSpec(ActorSystemSpec.config) with ImplicitSend
}
"not allow top-level actor creation with custom guardian" in {
val sys = new ActorSystemImpl("custom",
ConfigFactory.defaultReference(),
getClass.getClassLoader,
None,
Some(Props.empty),
ActorSystemSetup.empty)
val sys = new ActorSystemImpl(
"custom",
ConfigFactory.defaultReference(),
getClass.getClassLoader,
None,
Some(Props.empty),
ActorSystemSetup.empty)
sys.start()
try {
intercept[UnsupportedOperationException] {

View file

@ -107,18 +107,19 @@ class CoordinatedShutdownSpec
"have pre-defined phases from config" in {
import CoordinatedShutdown._
CoordinatedShutdown(system).orderedPhases should ===(
List(PhaseBeforeServiceUnbind,
PhaseServiceUnbind,
PhaseServiceRequestsDone,
PhaseServiceStop,
PhaseBeforeClusterShutdown,
PhaseClusterShardingShutdownRegion,
PhaseClusterLeave,
PhaseClusterExiting,
PhaseClusterExitingDone,
PhaseClusterShutdown,
PhaseBeforeActorSystemTerminate,
PhaseActorSystemTerminate))
List(
PhaseBeforeServiceUnbind,
PhaseServiceUnbind,
PhaseServiceRequestsDone,
PhaseServiceStop,
PhaseBeforeClusterShutdown,
PhaseClusterShardingShutdownRegion,
PhaseClusterLeave,
PhaseClusterExiting,
PhaseClusterExitingDone,
PhaseClusterShutdown,
PhaseBeforeActorSystemTerminate,
PhaseActorSystemTerminate))
}
"run ordered phases" in {
@ -188,9 +189,10 @@ class CoordinatedShutdownSpec
"continue after timeout or failure" in {
import system.dispatcher
val phases = Map("a" -> emptyPhase,
"b" -> Phase(dependsOn = Set("a"), timeout = 100.millis, recover = true, enabled = true),
"c" -> phase("b", "a"))
val phases = Map(
"a" -> emptyPhase,
"b" -> Phase(dependsOn = Set("a"), timeout = 100.millis, recover = true, enabled = true),
"c" -> phase("b", "a"))
val co = new CoordinatedShutdown(extSys, phases)
co.addTask("a", "a1") { () =>
testActor ! "A"
@ -226,9 +228,10 @@ class CoordinatedShutdownSpec
}
"abort if recover=off" in {
val phases = Map("a" -> emptyPhase,
"b" -> Phase(dependsOn = Set("a"), timeout = 100.millis, recover = false, enabled = true),
"c" -> phase("b", "a"))
val phases = Map(
"a" -> emptyPhase,
"b" -> Phase(dependsOn = Set("a"), timeout = 100.millis, recover = false, enabled = true),
"c" -> phase("b", "a"))
val co = new CoordinatedShutdown(extSys, phases)
co.addTask("b", "b1") { () =>
testActor ! "B"
@ -247,9 +250,10 @@ class CoordinatedShutdownSpec
}
"skip tasks in disabled phase" in {
val phases = Map("a" -> emptyPhase,
"b" -> Phase(dependsOn = Set("a"), timeout = 100.millis, recover = false, enabled = false),
"c" -> phase("b", "a"))
val phases = Map(
"a" -> emptyPhase,
"b" -> Phase(dependsOn = Set("a"), timeout = 100.millis, recover = false, enabled = false),
"c" -> phase("b", "a"))
val co = new CoordinatedShutdown(extSys, phases)
co.addTask("b", "b1") { () =>
testActor ! "B"
@ -297,9 +301,10 @@ class CoordinatedShutdownSpec
}
}
""")) should ===(
Map("a" -> Phase(dependsOn = Set.empty, timeout = 10.seconds, recover = true, enabled = true),
"b" -> Phase(dependsOn = Set("a"), timeout = 15.seconds, recover = true, enabled = true),
"c" -> Phase(dependsOn = Set("a", "b"), timeout = 10.seconds, recover = false, enabled = true)))
Map(
"a" -> Phase(dependsOn = Set.empty, timeout = 10.seconds, recover = true, enabled = true),
"b" -> Phase(dependsOn = Set("a"), timeout = 15.seconds, recover = true, enabled = true),
"c" -> Phase(dependsOn = Set("a", "b"), timeout = 10.seconds, recover = false, enabled = true)))
}
"default exit code to 0" in {

View file

@ -169,11 +169,12 @@ trait DeathWatchSpec { this: AkkaSpec with ImplicitSender with DefaultTimeout =>
"fail a monitor which does not handle Terminated()" in {
filterEvents(EventFilter[ActorKilledException](), EventFilter[DeathPactException]()) {
val strategy = new OneForOneStrategy()(SupervisorStrategy.defaultStrategy.decider) {
override def handleFailure(context: ActorContext,
child: ActorRef,
cause: Throwable,
stats: ChildRestartStats,
children: Iterable[ChildRestartStats]) = {
override def handleFailure(
context: ActorContext,
child: ActorRef,
cause: Throwable,
stats: ChildRestartStats,
children: Iterable[ChildRestartStats]) = {
testActor.tell(FF(Failed(child, cause, 0)), child)
super.handleFailure(context, child, cause, stats, children)
}

View file

@ -13,7 +13,8 @@ import akka.routing._
import scala.concurrent.duration._
object DeployerSpec {
val deployerConf = ConfigFactory.parseString("""
val deployerConf = ConfigFactory.parseString(
"""
akka.actor.deployment {
/service1 {
}
@ -68,7 +69,7 @@ object DeployerSpec {
}
}
""",
ConfigParseOptions.defaults)
ConfigParseOptions.defaults)
class RecipeActor extends Actor {
def receive = { case _ => }
@ -85,12 +86,13 @@ class DeployerSpec extends AkkaSpec(DeployerSpec.deployerConf) {
deployment should ===(
Some(
Deploy(service,
deployment.get.config,
NoRouter,
NoScopeGiven,
Deploy.NoDispatcherGiven,
Deploy.NoMailboxGiven)))
Deploy(
service,
deployment.get.config,
NoRouter,
NoScopeGiven,
Deploy.NoDispatcherGiven,
Deploy.NoMailboxGiven)))
}
"use None deployment for undefined service" in {
@ -105,12 +107,13 @@ class DeployerSpec extends AkkaSpec(DeployerSpec.deployerConf) {
deployment should ===(
Some(
Deploy(service,
deployment.get.config,
NoRouter,
NoScopeGiven,
dispatcher = "my-dispatcher",
Deploy.NoMailboxGiven)))
Deploy(
service,
deployment.get.config,
NoRouter,
NoScopeGiven,
dispatcher = "my-dispatcher",
Deploy.NoMailboxGiven)))
}
"be able to parse 'akka.actor.deployment._' with mailbox config" in {
@ -119,18 +122,20 @@ class DeployerSpec extends AkkaSpec(DeployerSpec.deployerConf) {
deployment should ===(
Some(
Deploy(service,
deployment.get.config,
NoRouter,
NoScopeGiven,
Deploy.NoDispatcherGiven,
mailbox = "my-mailbox")))
Deploy(
service,
deployment.get.config,
NoRouter,
NoScopeGiven,
Deploy.NoDispatcherGiven,
mailbox = "my-mailbox")))
}
"detect invalid number-of-instances" in {
intercept[com.typesafe.config.ConfigException.WrongType] {
val invalidDeployerConf = ConfigFactory
.parseString("""
.parseString(
"""
akka.actor.deployment {
/service-invalid-number-of-instances {
router = round-robin-pool
@ -138,7 +143,7 @@ class DeployerSpec extends AkkaSpec(DeployerSpec.deployerConf) {
}
}
""",
ConfigParseOptions.defaults)
ConfigParseOptions.defaults)
.withFallback(AkkaSpec.testConf)
shutdown(ActorSystem("invalid-number-of-instances", invalidDeployerConf))
@ -148,7 +153,8 @@ class DeployerSpec extends AkkaSpec(DeployerSpec.deployerConf) {
"detect invalid deployment path" in {
val e = intercept[InvalidActorNameException] {
val invalidDeployerConf = ConfigFactory
.parseString("""
.parseString(
"""
akka.actor.deployment {
/gul/ubåt {
router = round-robin-pool
@ -156,7 +162,7 @@ class DeployerSpec extends AkkaSpec(DeployerSpec.deployerConf) {
}
}
""",
ConfigParseOptions.defaults)
ConfigParseOptions.defaults)
.withFallback(AkkaSpec.testConf)
shutdown(ActorSystem("invalid-path", invalidDeployerConf))
@ -182,9 +188,10 @@ class DeployerSpec extends AkkaSpec(DeployerSpec.deployerConf) {
}
"be able to parse 'akka.actor.deployment._' with scatter-gather router" in {
assertRouting("/service-scatter-gather",
ScatterGatherFirstCompletedPool(nrOfInstances = 1, within = 2 seconds),
"/service-scatter-gather")
assertRouting(
"/service-scatter-gather",
ScatterGatherFirstCompletedPool(nrOfInstances = 1, within = 2 seconds),
"/service-scatter-gather")
}
"be able to parse 'akka.actor.deployment._' with consistent-hashing router" in {
@ -198,9 +205,10 @@ class DeployerSpec extends AkkaSpec(DeployerSpec.deployerConf) {
"be able to use wildcards" in {
assertRouting("/some/wildcardmatch", RandomPool(1), "/some/*")
assertRouting("/somewildcardmatch/some",
ScatterGatherFirstCompletedPool(nrOfInstances = 1, within = 2 seconds),
"/*/some")
assertRouting(
"/somewildcardmatch/some",
ScatterGatherFirstCompletedPool(nrOfInstances = 1, within = 2 seconds),
"/*/some")
}
"be able to use double wildcards" in {

View file

@ -84,8 +84,9 @@ class ExtensionSpec extends WordSpec with Matchers {
"fail the actor system if an extension listed in akka.extensions fails to start" in {
intercept[RuntimeException] {
val system = ActorSystem("failing",
ConfigFactory.parseString("""
val system = ActorSystem(
"failing",
ConfigFactory.parseString("""
akka.extensions = ["akka.actor.FailingTestExtension"]
"""))
@ -94,8 +95,9 @@ class ExtensionSpec extends WordSpec with Matchers {
}
"log an error if an extension listed in akka.extensions cannot be loaded" in {
val system = ActorSystem("failing",
ConfigFactory.parseString("""
val system = ActorSystem(
"failing",
ConfigFactory.parseString("""
akka.extensions = ["akka.actor.MissingExtension"]
"""))
EventFilter.error("While trying to load extension [akka.actor.MissingExtension], skipping.").intercept(())(system)
@ -114,8 +116,9 @@ class ExtensionSpec extends WordSpec with Matchers {
"fail the actor system if a library-extension fails to start" in {
intercept[FailingTestExtension.TestException] {
ActorSystem("failing",
ConfigFactory.parseString("""
ActorSystem(
"failing",
ConfigFactory.parseString("""
akka.library-extensions += "akka.actor.FailingTestExtension"
""").withFallback(ConfigFactory.load()).resolve())
}
@ -124,8 +127,9 @@ class ExtensionSpec extends WordSpec with Matchers {
"fail the actor system if a library-extension cannot be loaded" in {
intercept[RuntimeException] {
ActorSystem("failing",
ConfigFactory.parseString("""
ActorSystem(
"failing",
ConfigFactory.parseString("""
akka.library-extensions += "akka.actor.MissingExtension"
""").withFallback(ConfigFactory.load()))
}

View file

@ -253,9 +253,10 @@ class FSMActorSpec extends AkkaSpec(Map("akka.actor.debug.fsm" -> true)) with Im
"log events and transitions if asked to do so" in {
import scala.collection.JavaConverters._
val config = ConfigFactory
.parseMap(Map("akka.loglevel" -> "DEBUG",
"akka.actor.serialize-messages" -> "off",
"akka.actor.debug.fsm" -> true).asJava)
.parseMap(Map(
"akka.loglevel" -> "DEBUG",
"akka.actor.serialize-messages" -> "off",
"akka.actor.debug.fsm" -> true).asJava)
.withFallback(system.settings.config)
val fsmEventSystem = ActorSystem("fsmEvent", config)
try {

View file

@ -109,8 +109,9 @@ class FSMTimingSpec extends AkkaSpec with ImplicitSender {
expectMsg(500 millis, Tick)
Thread.sleep(200) // this is ugly: need to wait for StateTimeout to be queued
resume(fsm)
expectMsg(500 millis,
Transition(fsm, TestCancelStateTimerInNamedTimerMessage, TestCancelStateTimerInNamedTimerMessage2))
expectMsg(
500 millis,
Transition(fsm, TestCancelStateTimerInNamedTimerMessage, TestCancelStateTimerInNamedTimerMessage2))
fsm ! Cancel
within(500 millis) {
expectMsg(Cancel) // if this is not received, that means StateTimeout was not properly discarded
@ -132,9 +133,10 @@ class FSMTimingSpec extends AkkaSpec with ImplicitSender {
"notify unhandled messages" taggedAs TimingTest in {
filterEvents(
EventFilter.warning("unhandled event Tick in state TestUnhandled", source = fsm.path.toString, occurrences = 1),
EventFilter.warning("unhandled event Unhandled(test) in state TestUnhandled",
source = fsm.path.toString,
occurrences = 1)) {
EventFilter.warning(
"unhandled event Unhandled(test) in state TestUnhandled",
source = fsm.path.toString,
occurrences = 1)) {
fsm ! TestUnhandled
within(3 second) {
fsm ! Tick

View file

@ -63,13 +63,14 @@ object SupervisorHierarchySpec {
case object PongOfDeath
final case class Event(msg: Any, identity: Long) { val time: Long = System.nanoTime }
final case class ErrorLog(msg: String, log: Vector[Event])
final case class Failure(directive: Directive,
stop: Boolean,
depth: Int,
var failPre: Int,
var failPost: Int,
val failConstr: Int,
stopKids: Int)
final case class Failure(
directive: Directive,
stop: Boolean,
depth: Int,
var failPre: Int,
var failPost: Int,
val failConstr: Int,
stopKids: Int)
extends RuntimeException("Failure")
with NoStackTrace {
override def toString = productPrefix + productIterator.mkString("(", ",", ")")
@ -89,12 +90,13 @@ object SupervisorHierarchySpec {
extends DispatcherConfigurator(config, prerequisites) {
private val instance: MessageDispatcher =
new Dispatcher(this,
config.getString("id"),
config.getInt("throughput"),
config.getNanosDuration("throughput-deadline-time"),
configureExecutor(),
config.getMillisDuration("shutdown-timeout")) {
new Dispatcher(
this,
config.getString("id"),
config.getInt("throughput"),
config.getNanosDuration("throughput-deadline-time"),
configureExecutor(),
config.getMillisDuration("shutdown-timeout")) {
override def suspend(cell: ActorCell): Unit = {
cell.actor match {
@ -517,17 +519,18 @@ object SupervisorHierarchySpec {
nextJob.next match {
case Ping(ref) => ref ! "ping"
case Fail(ref, dir) =>
val f = Failure(dir,
stop = random012 > 0,
depth = random012,
failPre = random012,
failPost = random012,
failConstr = random012,
stopKids = random012 match {
case 0 => 0
case 1 => random.nextInt(breadth / 2)
case 2 => 1000
})
val f = Failure(
dir,
stop = random012 > 0,
depth = random012,
failPre = random012,
failPost = random012,
failConstr = random012,
stopKids = random012 match {
case 0 => 0
case 1 => random.nextInt(breadth / 2)
case 2 => 1000
})
ref ! f
}
if (idleChildren.nonEmpty) self ! Work
@ -843,11 +846,12 @@ class SupervisorHierarchySpec extends AkkaSpec(SupervisorHierarchySpec.config) w
val preStartCalled = new AtomicInteger(0)
val postRestartCalled = new AtomicInteger(0)
filterEvents(EventFilter[Failure](),
EventFilter[ActorInitializationException](),
EventFilter[IllegalArgumentException]("OH NO!"),
EventFilter.error(start = "changing Recreate into Create"),
EventFilter.error(start = "changing Resume into Create")) {
filterEvents(
EventFilter[Failure](),
EventFilter[ActorInitializationException](),
EventFilter[IllegalArgumentException]("OH NO!"),
EventFilter.error(start = "changing Recreate into Create"),
EventFilter.error(start = "changing Resume into Create")) {
val failResumer =
system.actorOf(
Props(new Actor {
@ -892,14 +896,15 @@ class SupervisorHierarchySpec extends AkkaSpec(SupervisorHierarchySpec.config) w
"survive being stressed" taggedAs LongRunningTest in {
system.eventStream.publish(
Mute(EventFilter[Failure](),
EventFilter.warning("Failure"),
EventFilter[ActorInitializationException](),
EventFilter[NoSuchElementException]("head of empty list"),
EventFilter.error(start = "changing Resume into Restart"),
EventFilter.error(start = "changing Resume into Create"),
EventFilter.error(start = "changing Recreate into Create"),
EventFilter.warning(start = "received dead ")))
Mute(
EventFilter[Failure](),
EventFilter.warning("Failure"),
EventFilter[ActorInitializationException](),
EventFilter[NoSuchElementException]("head of empty list"),
EventFilter.error(start = "changing Resume into Restart"),
EventFilter.error(start = "changing Resume into Create"),
EventFilter.error(start = "changing Recreate into Create"),
EventFilter.warning(start = "received dead ")))
val fsm = system.actorOf(Props(new StressTest(testActor, size = 500, breadth = 6)), "stressTest")

View file

@ -132,9 +132,10 @@ class SupervisorMiscSpec extends AkkaSpec(SupervisorMiscSpec.config) with Defaul
"be able to create a similar kid in the fault handling strategy" in {
val parent = system.actorOf(Props(new Actor {
override val supervisorStrategy = new OneForOneStrategy()(SupervisorStrategy.defaultStrategy.decider) {
override def handleChildTerminated(context: ActorContext,
child: ActorRef,
children: Iterable[ActorRef]): Unit = {
override def handleChildTerminated(
context: ActorContext,
child: ActorRef,
children: Iterable[ActorRef]): Unit = {
val newKid = context.actorOf(Props.empty, child.path.name)
testActor ! { if ((newKid ne child) && newKid.path == child.path) "green" else "red" }
}

View file

@ -417,9 +417,10 @@ class SupervisorSpec
supervisor ! dyingProps
val dyingActor = expectMsgType[ActorRef]
filterEvents(EventFilter[RuntimeException]("Expected", occurrences = 1),
EventFilter[PreRestartException]("Don't wanna!", occurrences = 1),
EventFilter[PostRestartException]("Don't wanna!", occurrences = 1)) {
filterEvents(
EventFilter[RuntimeException]("Expected", occurrences = 1),
EventFilter[PreRestartException]("Don't wanna!", occurrences = 1),
EventFilter[PostRestartException]("Don't wanna!", occurrences = 1)) {
intercept[RuntimeException] {
Await.result(dyingActor.?(DieReply)(DilatedTimeout), DilatedTimeout)
}
@ -468,8 +469,9 @@ class SupervisorSpec
parent ! latch
parent ! "testchildAndAck"
expectMsg("ack")
filterEvents(EventFilter[IllegalStateException]("OHNOES", occurrences = 1),
EventFilter.warning(pattern = "dead.*test", occurrences = 1)) {
filterEvents(
EventFilter[IllegalStateException]("OHNOES", occurrences = 1),
EventFilter.warning(pattern = "dead.*test", occurrences = 1)) {
latch.countDown()
}
expectMsg("parent restarted")

View file

@ -149,19 +149,21 @@ object TimerSpec {
class TimerSpec extends AbstractTimerSpec {
override def testName: String = "Timers"
override def target(monitor: ActorRef,
interval: FiniteDuration,
repeat: Boolean,
initial: () => Int = () => 1): Props =
override def target(
monitor: ActorRef,
interval: FiniteDuration,
repeat: Boolean,
initial: () => Int = () => 1): Props =
TimerSpec.target(monitor, interval, repeat, initial)
}
class FsmTimerSpec extends AbstractTimerSpec {
override def testName: String = "FSM Timers"
override def target(monitor: ActorRef,
interval: FiniteDuration,
repeat: Boolean,
initial: () => Int = () => 1): Props =
override def target(
monitor: ActorRef,
interval: FiniteDuration,
repeat: Boolean,
initial: () => Int = () => 1): Props =
TimerSpec.fsmTarget(monitor, interval, repeat, initial)
}

View file

@ -393,8 +393,9 @@ class TypedActorSpec
case p: TypedProps[_] => context.sender() ! TypedActor(context).typedActorOf(p)
}
}))
val t = Await.result((boss ? TypedProps[Bar](classOf[Foo], classOf[Bar]).withTimeout(2 seconds)).mapTo[Foo],
timeout.duration)
val t = Await.result(
(boss ? TypedProps[Bar](classOf[Foo], classOf[Bar]).withTimeout(2 seconds)).mapTo[Foo],
timeout.duration)
t.incr()
t.failingPigdog()

View file

@ -18,9 +18,10 @@ object UidClashTest {
@volatile var oldActor: ActorRef = _
private[akka] class EvilCollidingActorRef(override val provider: ActorRefProvider,
override val path: ActorPath,
val eventStream: EventStream)
private[akka] class EvilCollidingActorRef(
override val provider: ActorRefProvider,
override val path: ActorPath,
val eventStream: EventStream)
extends MinimalActorRef {
//Ignore everything

View file

@ -172,11 +172,12 @@ object ActorModelSpec {
} catch {
case e: Throwable =>
system.eventStream.publish(
Error(e,
dispatcher.toString,
dispatcher.getClass,
"actual: stops=" + dispatcher.stops.get +
" required: stops=" + stops))
Error(
e,
dispatcher.toString,
dispatcher.getClass,
"actual: stops=" + dispatcher.stops.get +
" required: stops=" + stops))
throw e
}
}
@ -213,9 +214,10 @@ object ActorModelSpec {
msgsReceived: Long = statsFor(actorRef, dispatcher).msgsReceived.get(),
msgsProcessed: Long = statsFor(actorRef, dispatcher).msgsProcessed.get(),
restarts: Long = statsFor(actorRef, dispatcher).restarts.get())(implicit system: ActorSystem): Unit = {
val stats = statsFor(actorRef,
Option(dispatcher).getOrElse(
actorRef.asInstanceOf[ActorRefWithCell].underlying.asInstanceOf[ActorCell].dispatcher))
val stats = statsFor(
actorRef,
Option(dispatcher).getOrElse(
actorRef.asInstanceOf[ActorRefWithCell].underlying.asInstanceOf[ActorCell].dispatcher))
val deadline = System.currentTimeMillis + 1000
try {
await(deadline)(stats.suspensions.get() == suspensions)
@ -228,12 +230,13 @@ object ActorModelSpec {
} catch {
case e: Throwable =>
system.eventStream.publish(
Error(e,
Option(dispatcher).toString,
Option(dispatcher).getOrElse(this).getClass,
"actual: " + stats + ", required: InterceptorStats(susp=" + suspensions +
",res=" + resumes + ",reg=" + registers + ",unreg=" + unregisters +
",recv=" + msgsReceived + ",proc=" + msgsProcessed + ",restart=" + restarts))
Error(
e,
Option(dispatcher).toString,
Option(dispatcher).getOrElse(this).getClass,
"actual: " + stats + ", required: InterceptorStats(susp=" + suspensions +
",res=" + resumes + ",reg=" + registers + ",unreg=" + unregisters +
",recv=" + msgsReceived + ",proc=" + msgsProcessed + ",restart=" + restarts))
throw e
}
}
@ -276,13 +279,14 @@ abstract class ActorModelSpec(config: String) extends AkkaSpec(config) with Defa
assertDispatcher(dispatcher)(stops = 0)
system.stop(a)
assertDispatcher(dispatcher)(stops = 1)
assertRef(a, dispatcher)(suspensions = 0,
resumes = 0,
registers = 1,
unregisters = 1,
msgsReceived = 0,
msgsProcessed = 0,
restarts = 0)
assertRef(a, dispatcher)(
suspensions = 0,
resumes = 0,
registers = 1,
unregisters = 1,
msgsReceived = 0,
msgsProcessed = 0,
restarts = 0)
for (i <- 1 to 10) yield Future { i }
assertDispatcher(dispatcher)(stops = 2)
@ -359,12 +363,13 @@ abstract class ActorModelSpec(config: String) extends AkkaSpec(config) with Defa
assertRefDefaultZero(a)(registers = 1, msgsReceived = 1, msgsProcessed = 1, suspensions = 1, resumes = 1)
system.stop(a)
assertRefDefaultZero(a)(registers = 1,
unregisters = 1,
msgsReceived = 1,
msgsProcessed = 1,
suspensions = 1,
resumes = 1)
assertRefDefaultZero(a)(
registers = 1,
unregisters = 1,
msgsReceived = 1,
msgsProcessed = 1,
suspensions = 1,
resumes = 1)
}
"handle waves of actors" in {
@ -432,9 +437,10 @@ abstract class ActorModelSpec(config: String) extends AkkaSpec(config) with Defa
}
"continue to process messages when a thread gets interrupted and throws an exception" in {
filterEvents(EventFilter[InterruptedException](),
EventFilter[ActorInterruptedException](),
EventFilter[akka.event.Logging.LoggerException]()) {
filterEvents(
EventFilter[InterruptedException](),
EventFilter[ActorInterruptedException](),
EventFilter[akka.event.Logging.LoggerException]()) {
implicit val dispatcher = interceptedDispatcher()
val a = newTestActor(dispatcher.id)
val f1 = a ? Reply("foo")
@ -541,12 +547,13 @@ object DispatcherModelSpec {
import akka.util.Helpers.ConfigOps
private val instance: MessageDispatcher =
new Dispatcher(this,
config.getString("id"),
config.getInt("throughput"),
config.getNanosDuration("throughput-deadline-time"),
configureExecutor(),
config.getMillisDuration("shutdown-timeout")) with MessageDispatcherInterceptor
new Dispatcher(
this,
config.getString("id"),
config.getInt("throughput"),
config.getNanosDuration("throughput-deadline-time"),
configureExecutor(),
config.getMillisDuration("shutdown-timeout")) with MessageDispatcherInterceptor
override def dispatcher(): MessageDispatcher = instance
}
@ -617,14 +624,15 @@ object BalancingDispatcherModelSpec {
import akka.util.Helpers.ConfigOps
override protected def create(mailboxType: MailboxType): BalancingDispatcher =
new BalancingDispatcher(this,
config.getString("id"),
config.getInt("throughput"),
config.getNanosDuration("throughput-deadline-time"),
mailboxType,
configureExecutor(),
config.getMillisDuration("shutdown-timeout"),
config.getBoolean("attempt-teamwork")) with MessageDispatcherInterceptor
new BalancingDispatcher(
this,
config.getString("id"),
config.getInt("throughput"),
config.getNanosDuration("throughput-deadline-time"),
mailboxType,
configureExecutor(),
config.getMillisDuration("shutdown-timeout"),
config.getBoolean("attempt-teamwork")) with MessageDispatcherInterceptor
}
}

View file

@ -126,10 +126,11 @@ abstract class MailboxSpec extends AkkaSpec with BeforeAndAfterAll with BeforeAn
q.hasMessages should ===(false)
}
def testEnqueueDequeue(config: MailboxType,
enqueueN: Int = 10000,
dequeueN: Int = 10000,
parallel: Boolean = true): Unit = within(10 seconds) {
def testEnqueueDequeue(
config: MailboxType,
enqueueN: Int = 10000,
dequeueN: Int = 10000,
parallel: Boolean = true): Unit = within(10 seconds) {
val q = factory(config)
ensureInitialMailboxState(config, q)

View file

@ -109,10 +109,12 @@ class EventStreamSpec extends AkkaSpec(EventStreamSpec.config) {
sys.eventStream.subscribe(testActor, classOf[AnyRef])
val m = UnhandledMessage(42, sys.deadLetters, sys.deadLetters)
sys.eventStream.publish(m)
expectMsgAllOf(m,
Logging.Debug(sys.deadLetters.path.toString,
sys.deadLetters.getClass,
"unhandled message from " + sys.deadLetters + ": 42"))
expectMsgAllOf(
m,
Logging.Debug(
sys.deadLetters.path.toString,
sys.deadLetters.getClass,
"unhandled message from " + sys.deadLetters + ": 42"))
sys.eventStream.unsubscribe(testActor)
} finally {
shutdown(sys)

View file

@ -73,10 +73,12 @@ class LoggingReceiveSpec extends WordSpec with BeforeAndAfterAll {
})
}))
a ! "hallo"
expectMsg(1 second,
Logging.Debug("funky",
classOf[DummyClassForStringSources],
"received unhandled message hallo from " + system.deadLetters))
expectMsg(
1 second,
Logging.Debug(
"funky",
classOf[DummyClassForStringSources],
"received unhandled message hallo from " + system.deadLetters))
expectMsgType[UnhandledMessage](1 second)
}
}
@ -272,9 +274,10 @@ class LoggingReceiveSpec extends WordSpec with BeforeAndAfterAll {
}
system.stop(supervisor)
expectMsgAllOf(Logging.Debug(aname, aclass, "stopped"),
Logging.Debug(sname, sclass, "stopping"),
Logging.Debug(sname, sclass, "stopped"))
expectMsgAllOf(
Logging.Debug(aname, aclass, "stopped"),
Logging.Debug(sname, sclass, "stopping"),
Logging.Debug(sname, sclass, "stopped"))
}
def expectMsgAllPF(messages: Int)(matchers: PartialFunction[AnyRef, Int]): Set[Int] = {
@ -285,9 +288,10 @@ class LoggingReceiveSpec extends WordSpec with BeforeAndAfterAll {
else if (gotMatching.size == messages) gotMatching
else {
val msg = receiveOne(remainingOrDefault)
assert(msg ne null,
s"timeout ($max) during expectMsgAllPF, got matching " +
s"[${gotMatching.mkString(", ")}], got unknown: [${unknown.mkString(", ")}]")
assert(
msg ne null,
s"timeout ($max) during expectMsgAllPF, got matching " +
s"[${gotMatching.mkString(", ")}], got unknown: [${unknown.mkString(", ")}]")
if (matchers.isDefinedAt(msg)) receiveNMatching(gotMatching + matchers(msg), Vector.empty)
else receiveNMatching(gotMatching, unknown :+ msg) // unknown message, just ignore
}

View file

@ -9,10 +9,11 @@ import akka.testkit._
class MarkerLoggingSpec extends AkkaSpec with ImplicitSender {
"A MarkerLoggerAdapter" should {
val markerLogging = new MarkerLoggingAdapter(system.eventStream,
getClass.getName,
this.getClass,
new DefaultLoggingFilter(() => Logging.InfoLevel))
val markerLogging = new MarkerLoggingAdapter(
system.eventStream,
getClass.getName,
this.getClass,
new DefaultLoggingFilter(() => Logging.InfoLevel))
"add markers to logging" in {
system.eventStream.subscribe(self, classOf[Info])

View file

@ -89,9 +89,10 @@ class InetAddressDnsResolverSpec extends AkkaSpec("""
private def dnsResolver = {
val actorRef = TestActorRef[InetAddressDnsResolver](
Props(classOf[InetAddressDnsResolver],
new SimpleDnsCache(),
system.settings.config.getConfig("akka.io.dns.inet-address")))
Props(
classOf[InetAddressDnsResolver],
new SimpleDnsCache(),
system.settings.config.getConfig("akka.io.dns.inet-address")))
actorRef.underlyingActor
}
@ -136,9 +137,10 @@ class InetAddressDnsResolverConfigSpec extends AkkaSpec("""
private def dnsResolver = {
val actorRef = TestActorRef[InetAddressDnsResolver](
Props(classOf[InetAddressDnsResolver],
new SimpleDnsCache(),
system.settings.config.getConfig("akka.io.dns.inet-address")))
Props(
classOf[InetAddressDnsResolver],
new SimpleDnsCache(),
system.settings.config.getConfig("akka.io.dns.inet-address")))
actorRef.underlyingActor
}
}

View file

@ -912,10 +912,11 @@ class TcpConnectionSpec extends AkkaSpec("""
def setServerSocketOptions() = ()
def createConnectionActor(serverAddress: InetSocketAddress = serverAddress,
options: immutable.Seq[SocketOption] = Nil,
timeout: Option[FiniteDuration] = None,
pullMode: Boolean = false): TestActorRef[TcpOutgoingConnection] = {
def createConnectionActor(
serverAddress: InetSocketAddress = serverAddress,
options: immutable.Seq[SocketOption] = Nil,
timeout: Option[FiniteDuration] = None,
pullMode: Boolean = false): TestActorRef[TcpOutgoingConnection] = {
val ref = createConnectionActorWithoutRegistration(serverAddress, options, timeout, pullMode)
ref ! newChannelRegistration
ref
@ -930,15 +931,17 @@ class TcpConnectionSpec extends AkkaSpec("""
protected def onCancelAndClose(andThen: () => Unit): Unit = andThen()
def createConnectionActorWithoutRegistration(serverAddress: InetSocketAddress = serverAddress,
options: immutable.Seq[SocketOption] = Nil,
timeout: Option[FiniteDuration] = None,
pullMode: Boolean = false): TestActorRef[TcpOutgoingConnection] =
def createConnectionActorWithoutRegistration(
serverAddress: InetSocketAddress = serverAddress,
options: immutable.Seq[SocketOption] = Nil,
timeout: Option[FiniteDuration] = None,
pullMode: Boolean = false): TestActorRef[TcpOutgoingConnection] =
TestActorRef(
new TcpOutgoingConnection(Tcp(system),
this,
userHandler.ref,
Connect(serverAddress, options = options, timeout = timeout, pullMode = pullMode)) {
new TcpOutgoingConnection(
Tcp(system),
this,
userHandler.ref,
Connect(serverAddress, options = options, timeout = timeout, pullMode = pullMode)) {
override def postRestart(reason: Throwable): Unit = context.stop(self) // ensure we never restart
})
}
@ -960,9 +963,10 @@ class TcpConnectionSpec extends AkkaSpec("""
}
}
abstract class EstablishedConnectionTest(keepOpenOnPeerClosed: Boolean = false,
useResumeWriting: Boolean = true,
pullMode: Boolean = false)
abstract class EstablishedConnectionTest(
keepOpenOnPeerClosed: Boolean = false,
useResumeWriting: Boolean = true,
pullMode: Boolean = false)
extends UnacceptedConnectionTest(pullMode) {
// lazy init since potential exceptions should not be triggered in the constructor but during execution of `run`
@ -1054,9 +1058,10 @@ class TcpConnectionSpec extends AkkaSpec("""
/**
* Tries to simultaneously act on client and server side to read from the server all pending data from the client.
*/
@tailrec final def pullFromServerSide(remaining: Int,
remainingTries: Int = 1000,
into: ByteBuffer = defaultbuffer): Unit =
@tailrec final def pullFromServerSide(
remaining: Int,
remainingTries: Int = 1000,
into: ByteBuffer = defaultbuffer): Unit =
if (remainingTries <= 0)
throw new AssertionError("Pulling took too many loops, remaining data: " + remaining)
else if (remaining > 0) {
@ -1109,11 +1114,10 @@ class TcpConnectionSpec extends AkkaSpec("""
def selectedAs(interest: Int, duration: Duration): BeMatcher[SelectionKey] =
new BeMatcher[SelectionKey] {
def apply(key: SelectionKey) =
MatchResult(checkFor(key, interest, duration.toMillis.toInt),
"%s key was not selected for %s after %s".format(key.attachment(),
interestsDesc(interest),
duration),
"%s key was selected for %s after %s".format(key.attachment(), interestsDesc(interest), duration))
MatchResult(
checkFor(key, interest, duration.toMillis.toInt),
"%s key was not selected for %s after %s".format(key.attachment(), interestsDesc(interest), duration),
"%s key was selected for %s after %s".format(key.attachment(), interestsDesc(interest), duration))
}
val interestsNames =

View file

@ -195,11 +195,12 @@ class TcpIntegrationSpec extends AkkaSpec("""
}
}
def chitchat(clientHandler: TestProbe,
clientConnection: ActorRef,
serverHandler: TestProbe,
serverConnection: ActorRef,
rounds: Int = 100) = {
def chitchat(
clientHandler: TestProbe,
clientConnection: ActorRef,
serverHandler: TestProbe,
serverConnection: ActorRef,
rounds: Int = 100) = {
val testData = ByteString(0)
(1 to rounds).foreach { _ =>

View file

@ -175,12 +175,13 @@ class TcpListenerSpec extends AkkaSpec("""
private class ListenerParent(pullMode: Boolean) extends Actor with ChannelRegistry {
val listener = context.actorOf(
props = Props(classOf[TcpListener],
selectorRouter.ref,
Tcp(system),
this,
bindCommander.ref,
Bind(handler.ref, endpoint, 100, Nil, pullMode)).withDeploy(Deploy.local),
props = Props(
classOf[TcpListener],
selectorRouter.ref,
Tcp(system),
this,
bindCommander.ref,
Bind(handler.ref, endpoint, 100, Nil, pullMode)).withDeploy(Deploy.local),
name = "test-listener-" + counter.next())
parent.watch(listener)
def receive: Receive = {

View file

@ -24,9 +24,10 @@ class UdpConnectedIntegrationSpec extends AkkaSpec("""
commander.sender()
}
def connectUdp(localAddress: Option[InetSocketAddress],
remoteAddress: InetSocketAddress,
handler: ActorRef): ActorRef = {
def connectUdp(
localAddress: Option[InetSocketAddress],
remoteAddress: InetSocketAddress,
handler: ActorRef): ActorRef = {
val commander = TestProbe()
commander.send(IO(UdpConnected), UdpConnected.Connect(handler, remoteAddress, localAddress, Nil))
commander.expectMsg(UdpConnected.Connected)

View file

@ -61,8 +61,9 @@ class AsyncDnsResolverIntegrationSpec extends AkkaSpec(s"""
val name = "a-double.foo.test"
val answer = resolve(name)
answer.name shouldEqual name
answer.records.map(_.asInstanceOf[ARecord].ip).toSet shouldEqual Set(InetAddress.getByName("192.168.1.21"),
InetAddress.getByName("192.168.1.22"))
answer.records.map(_.asInstanceOf[ARecord].ip).toSet shouldEqual Set(
InetAddress.getByName("192.168.1.21"),
InetAddress.getByName("192.168.1.22"))
}
"resolve single AAAA record" in {
@ -87,8 +88,9 @@ class AsyncDnsResolverIntegrationSpec extends AkkaSpec(s"""
val answer = resolve(name)
answer.name shouldEqual name
answer.records.collect { case r: ARecord => r.ip }.toSet shouldEqual Set(InetAddress.getByName("192.168.1.23"),
InetAddress.getByName("192.168.1.24"))
answer.records.collect { case r: ARecord => r.ip }.toSet shouldEqual Set(
InetAddress.getByName("192.168.1.23"),
InetAddress.getByName("192.168.1.24"))
answer.records.collect { case r: AAAARecord => r.ip }.toSet shouldEqual Set(
InetAddress.getByName("fd4d:36b2:3eca:a2d8:0:0:0:4"),
@ -108,8 +110,9 @@ class AsyncDnsResolverIntegrationSpec extends AkkaSpec(s"""
val answer = resolve(name)
answer.name shouldEqual name
answer.records.collect { case r: CNameRecord => r.canonicalName }.toSet shouldEqual Set("a-double.foo.test")
answer.records.collect { case r: ARecord => r.ip }.toSet shouldEqual Set(InetAddress.getByName("192.168.1.21"),
InetAddress.getByName("192.168.1.22"))
answer.records.collect { case r: ARecord => r.ip }.toSet shouldEqual Set(
InetAddress.getByName("192.168.1.21"),
InetAddress.getByName("192.168.1.22"))
}
"resolve SRV record" in {

View file

@ -17,8 +17,9 @@ class DnsSettingsSpec extends AkkaSpec {
"DNS settings" must {
"use host servers if set to default" in {
val dnsSettings = new DnsSettings(eas,
ConfigFactory.parseString("""
val dnsSettings = new DnsSettings(
eas,
ConfigFactory.parseString("""
nameservers = "default"
resolve-timeout = 1s
search-domains = []
@ -30,8 +31,9 @@ class DnsSettingsSpec extends AkkaSpec {
}
"parse a single name server" in {
val dnsSettings = new DnsSettings(eas,
ConfigFactory.parseString("""
val dnsSettings = new DnsSettings(
eas,
ConfigFactory.parseString("""
nameservers = "127.0.0.1"
resolve-timeout = 1s
search-domains = []
@ -42,21 +44,24 @@ class DnsSettingsSpec extends AkkaSpec {
}
"parse a list of name servers" in {
val dnsSettings = new DnsSettings(eas,
ConfigFactory.parseString("""
val dnsSettings = new DnsSettings(
eas,
ConfigFactory.parseString("""
nameservers = ["127.0.0.1", "127.0.0.2"]
resolve-timeout = 1s
search-domains = []
ndots = 1
"""))
dnsSettings.NameServers.map(_.getAddress) shouldEqual List(InetAddress.getByName("127.0.0.1"),
InetAddress.getByName("127.0.0.2"))
dnsSettings.NameServers.map(_.getAddress) shouldEqual List(
InetAddress.getByName("127.0.0.1"),
InetAddress.getByName("127.0.0.2"))
}
"use host search domains if set to default" in {
val dnsSettings = new DnsSettings(eas,
ConfigFactory.parseString("""
val dnsSettings = new DnsSettings(
eas,
ConfigFactory.parseString("""
nameservers = "127.0.0.1"
resolve-timeout = 1s
search-domains = "default"
@ -68,8 +73,9 @@ class DnsSettingsSpec extends AkkaSpec {
}
"parse a single search domain" in {
val dnsSettings = new DnsSettings(eas,
ConfigFactory.parseString("""
val dnsSettings = new DnsSettings(
eas,
ConfigFactory.parseString("""
nameservers = "127.0.0.1"
resolve-timeout = 1s
search-domains = "example.com"
@ -80,8 +86,9 @@ class DnsSettingsSpec extends AkkaSpec {
}
"parse a single list of search domains" in {
val dnsSettings = new DnsSettings(eas,
ConfigFactory.parseString("""
val dnsSettings = new DnsSettings(
eas,
ConfigFactory.parseString("""
nameservers = "127.0.0.1"
resolve-timeout = 1s
search-domains = [ "example.com", "example.net" ]
@ -92,8 +99,9 @@ class DnsSettingsSpec extends AkkaSpec {
}
"use host ndots if set to default" in {
val dnsSettings = new DnsSettings(eas,
ConfigFactory.parseString("""
val dnsSettings = new DnsSettings(
eas,
ConfigFactory.parseString("""
nameservers = "127.0.0.1"
resolve-timeout = 1s
search-domains = "example.com"
@ -105,8 +113,9 @@ class DnsSettingsSpec extends AkkaSpec {
}
"parse ndots" in {
val dnsSettings = new DnsSettings(eas,
ConfigFactory.parseString("""
val dnsSettings = new DnsSettings(
eas,
ConfigFactory.parseString("""
nameservers = "127.0.0.1"
resolve-timeout = 1s
search-domains = "example.com"

View file

@ -46,8 +46,9 @@ trait DockerBindDnsService extends Eventually { self: AkkaSpec =>
.hostConfig(
HostConfig
.builder()
.portBindings(Map("53/tcp" -> List(PortBinding.of("", hostPort)).asJava,
"53/udp" -> List(PortBinding.of("", hostPort)).asJava).asJava)
.portBindings(Map(
"53/tcp" -> List(PortBinding.of("", hostPort)).asJava,
"53/udp" -> List(PortBinding.of("", hostPort)).asJava).asJava)
.binds(HostConfig.Bind
.from(new java.io.File("akka-actor-tests/src/test/bind/").getAbsolutePath)
.to("/data/bind")

View file

@ -134,8 +134,9 @@ class AsyncDnsResolverSpec extends AkkaSpec("""
}
def resolver(clients: List[ActorRef]): ActorRef = {
val settings = new DnsSettings(system.asInstanceOf[ExtendedActorSystem],
ConfigFactory.parseString("""
val settings = new DnsSettings(
system.asInstanceOf[ExtendedActorSystem],
ConfigFactory.parseString("""
nameservers = ["one","two"]
resolve-timeout = 300ms
search-domains = []

View file

@ -143,8 +143,9 @@ class AskSpec extends AkkaSpec {
val deadListener = TestProbe()
system.eventStream.subscribe(deadListener.ref, classOf[DeadLetter])
val echo = system.actorOf(Props(new Actor { def receive = { case x => context.actorSelection("/temp/*") ! x } }),
"select-echo3")
val echo = system.actorOf(
Props(new Actor { def receive = { case x => context.actorSelection("/temp/*") ! x } }),
"select-echo3")
val f = echo ? "hi"
intercept[AskTimeoutException] {
Await.result(f, 1 seconds)

View file

@ -141,12 +141,13 @@ class BackoffOnRestartSupervisorSpec extends AkkaSpec with ImplicitSender {
"accept commands while child is terminating" in {
val postStopLatch = new CountDownLatch(1)
val options = Backoff
.onFailure(Props(new SlowlyFailingActor(postStopLatch)),
"someChildName",
1 nanos,
1 nanos,
0.0,
maxNrOfRetries = -1)
.onFailure(
Props(new SlowlyFailingActor(postStopLatch)),
"someChildName",
1 nanos,
1 nanos,
0.0,
maxNrOfRetries = -1)
.withSupervisorStrategy(OneForOneStrategy(loggingEnabled = false) {
case _: TestActor.StoppingException => SupervisorStrategy.Stop
})

View file

@ -222,20 +222,22 @@ class BackoffSupervisorSpec extends AkkaSpec with ImplicitSender with Eventually
"correctly calculate the delay" in {
val delayTable =
Table(("restartCount", "minBackoff", "maxBackoff", "randomFactor", "expectedResult"),
(0, 0.minutes, 0.minutes, 0d, 0.minutes),
(0, 5.minutes, 7.minutes, 0d, 5.minutes),
(2, 5.seconds, 7.seconds, 0d, 7.seconds),
(2, 5.seconds, 7.days, 0d, 20.seconds),
(29, 5.minutes, 10.minutes, 0d, 10.minutes),
(29, 10000.days, 10000.days, 0d, 10000.days),
(Int.MaxValue, 10000.days, 10000.days, 0d, 10000.days))
Table(
("restartCount", "minBackoff", "maxBackoff", "randomFactor", "expectedResult"),
(0, 0.minutes, 0.minutes, 0d, 0.minutes),
(0, 5.minutes, 7.minutes, 0d, 5.minutes),
(2, 5.seconds, 7.seconds, 0d, 7.seconds),
(2, 5.seconds, 7.days, 0d, 20.seconds),
(29, 5.minutes, 10.minutes, 0d, 10.minutes),
(29, 10000.days, 10000.days, 0d, 10000.days),
(Int.MaxValue, 10000.days, 10000.days, 0d, 10000.days))
forAll(delayTable) {
(restartCount: Int,
minBackoff: FiniteDuration,
maxBackoff: FiniteDuration,
randomFactor: Double,
expectedResult: FiniteDuration) =>
(
restartCount: Int,
minBackoff: FiniteDuration,
maxBackoff: FiniteDuration,
randomFactor: Double,
expectedResult: FiniteDuration) =>
val calculatedValue = BackoffSupervisor.calculateDelay(restartCount, minBackoff, maxBackoff, randomFactor)
assert(calculatedValue === expectedResult)
}

View file

@ -670,9 +670,10 @@ class CircuitBreakerSpec extends AkkaSpec with BeforeAndAfter with MockitoSugar
val breaker: CircuitBreakerSpec.Breaker = CircuitBreakerSpec.multiFailureCb()
for (_ <- 1 to 4) breaker().withCircuitBreaker(Future(throwException))
awaitCond(breaker().currentFailureCount == 4,
awaitTimeout,
message = s"Current failure count: ${breaker().currentFailureCount}")
awaitCond(
breaker().currentFailureCount == 4,
awaitTimeout,
message = s"Current failure count: ${breaker().currentFailureCount}")
val harmlessException = new TestException
val harmlessExceptionAsSuccess: Try[String] => Boolean = {

View file

@ -27,13 +27,14 @@ class RetrySpec extends AkkaSpec with RetrySupport {
"run a successful Future only once" in {
@volatile var counter = 0
val retried = retry(() =>
Future.successful({
counter += 1
counter
}),
5,
1 second)
val retried = retry(
() =>
Future.successful({
counter += 1
counter
}),
5,
1 second)
within(3 seconds) {
Await.result(retried, remaining) should ===(1)

View file

@ -96,8 +96,9 @@ class BalancingSpec extends AkkaSpec("""
"deliver messages in a balancing fashion when defined programatically" in {
val latch = TestLatch(poolSize)
val pool = system.actorOf(BalancingPool(poolSize).props(routeeProps = Props(classOf[Worker], latch)),
name = "balancingPool-1")
val pool = system.actorOf(
BalancingPool(poolSize).props(routeeProps = Props(classOf[Worker], latch)),
name = "balancingPool-1")
test(pool, latch)
}

View file

@ -84,8 +84,9 @@ class ConsistentHashingRouterSpec
case Msg2(key, _) => key
}
val router2 =
system.actorOf(ConsistentHashingPool(nrOfInstances = 1, hashMapping = hashMapping).props(Props[Echo]),
"router2")
system.actorOf(
ConsistentHashingPool(nrOfInstances = 1, hashMapping = hashMapping).props(Props[Echo]),
"router2")
router2 ! Msg2("a", "A")
val destinationA = expectMsgType[ActorRef]

View file

@ -45,9 +45,10 @@ object MetricsBasedResizerSpec {
var msgs: Set[TestLatch] = Set()
def mockSend(await: Boolean,
l: TestLatch = TestLatch(),
routeeIdx: Int = Random.nextInt(routees.length)): Latches = {
def mockSend(
await: Boolean,
l: TestLatch = TestLatch(),
routeeIdx: Int = Random.nextInt(routees.length)): Latches = {
val target = routees(routeeIdx)
val first = TestLatch()
val latches = Latches(first, l)
@ -334,8 +335,9 @@ class MetricsBasedResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultT
}
"ignore further away sample data when optmizing" in {
val resizer = DefaultOptimalSizeExploringResizer(explorationProbability = 0,
numOfAdjacentSizesToConsiderDuringOptimization = 4)
val resizer = DefaultOptimalSizeExploringResizer(
explorationProbability = 0,
numOfAdjacentSizesToConsiderDuringOptimization = 4)
resizer.performanceLog =
Map(7 -> 5.millis, 8 -> 2.millis, 10 -> 3.millis, 11 -> 4.millis, 12 -> 3.millis, 13 -> 1.millis)

View file

@ -160,13 +160,14 @@ class ResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultTimeout with
// make sure the pool starts at the expected lower limit and grows to the upper as needed
// as influenced by the backlog of blocking pooled actors
val resizer = DefaultResizer(lowerBound = 3,
upperBound = 5,
rampupRate = 0.1,
backoffRate = 0.0,
pressureThreshold = 1,
messagesPerResize = 1,
backoffThreshold = 0.0)
val resizer = DefaultResizer(
lowerBound = 3,
upperBound = 5,
rampupRate = 0.1,
backoffRate = 0.0,
pressureThreshold = 1,
messagesPerResize = 1,
backoffThreshold = 0.0)
val router = system.actorOf(RoundRobinPool(nrOfInstances = 0, resizer = Some(resizer)).props(Props(new Actor {
def receive = {
@ -203,13 +204,14 @@ class ResizerSpec extends AkkaSpec(ResizerSpec.config) with DefaultTimeout with
}
"backoff" in within(10 seconds) {
val resizer = DefaultResizer(lowerBound = 2,
upperBound = 5,
rampupRate = 1.0,
backoffRate = 1.0,
backoffThreshold = 0.40,
pressureThreshold = 1,
messagesPerResize = 2)
val resizer = DefaultResizer(
lowerBound = 2,
upperBound = 5,
rampupRate = 1.0,
backoffRate = 1.0,
backoffThreshold = 0.40,
pressureThreshold = 1,
messagesPerResize = 2)
val router = system.actorOf(RoundRobinPool(nrOfInstances = 0, resizer = Some(resizer)).props(Props(new Actor {
def receive = {

View file

@ -124,8 +124,9 @@ class RoutingSpec extends AkkaSpec(RoutingSpec.config) with DefaultTimeout with
}
}
val router =
system.actorOf(RoundRobinPool(nrOfInstances = 0, resizer = Some(resizer)).props(routeeProps = Props[TestActor]),
"router3")
system.actorOf(
RoundRobinPool(nrOfInstances = 0, resizer = Some(resizer)).props(routeeProps = Props[TestActor]),
"router3")
Await.ready(latch, remainingOrDefault)
router ! GetRoutees
expectMsgType[Routees].routees.size should ===(3)
@ -232,10 +233,11 @@ class RoutingSpec extends AkkaSpec(RoutingSpec.config) with DefaultTimeout with
}
"allow external configuration" in {
val sys = ActorSystem("FromConfig",
ConfigFactory
.parseString("akka.actor.deployment./routed.router=round-robin-pool")
.withFallback(system.settings.config))
val sys = ActorSystem(
"FromConfig",
ConfigFactory
.parseString("akka.actor.deployment./routed.router=round-robin-pool")
.withFallback(system.settings.config))
try {
sys.actorOf(FromConfig.props(routeeProps = Props[TestActor]), "routed")
} finally {

View file

@ -52,10 +52,9 @@ object SerializationSetupSpec {
val serializationSettings = SerializationSetup { _ =>
List(SerializerDetails("test", programmaticDummySerializer, List(classOf[ProgrammaticDummy])))
}
val bootstrapSettings = BootstrapSetup(None,
Some(
ConfigFactory.parseString(
"""
val bootstrapSettings = BootstrapSetup(
None,
Some(ConfigFactory.parseString("""
akka {
actor {
serialize-messages = off
@ -69,12 +68,12 @@ object SerializationSetupSpec {
}
}
""")),
None)
None)
val actorSystemSettings = ActorSystemSetup(bootstrapSettings, serializationSettings)
val noJavaSerializationSystem = ActorSystem("SerializationSettingsSpec" + "NoJavaSerialization",
ConfigFactory.parseString(
"""
val noJavaSerializationSystem = ActorSystem(
"SerializationSettingsSpec" + "NoJavaSerialization",
ConfigFactory.parseString("""
akka {
actor {
allow-java-serialization = off
@ -125,15 +124,16 @@ class SerializationSetupSpec
// allow-java-serialization=on to create the SerializationSetup and use that SerializationSetup
// in another system with allow-java-serialization=off
val addedJavaSerializationSettings = SerializationSetup { _ =>
List(SerializerDetails("test", programmaticDummySerializer, List(classOf[ProgrammaticDummy])),
SerializerDetails("java-manual",
new JavaSerializer(system.asInstanceOf[ExtendedActorSystem]),
List(classOf[ProgrammaticJavaDummy])))
List(
SerializerDetails("test", programmaticDummySerializer, List(classOf[ProgrammaticDummy])),
SerializerDetails(
"java-manual",
new JavaSerializer(system.asInstanceOf[ExtendedActorSystem]),
List(classOf[ProgrammaticJavaDummy])))
}
val addedJavaSerializationProgramaticallyButDisabledSettings = BootstrapSetup(None,
Some(
ConfigFactory.parseString(
"""
val addedJavaSerializationProgramaticallyButDisabledSettings = BootstrapSetup(
None,
Some(ConfigFactory.parseString("""
akka {
loglevel = debug
actor {
@ -143,7 +143,7 @@ class SerializationSetupSpec
}
}
""")),
None)
None)
val addedJavaSerializationViaSettingsSystem =
ActorSystem(

View file

@ -132,16 +132,17 @@ object SerializationTests {
}
"""
val systemMessageClasses = List[Class[_]](classOf[Create],
classOf[Recreate],
classOf[Suspend],
classOf[Resume],
classOf[Terminate],
classOf[Supervise],
classOf[Watch],
classOf[Unwatch],
classOf[Failed],
NoMessage.getClass)
val systemMessageClasses = List[Class[_]](
classOf[Create],
classOf[Recreate],
classOf[Suspend],
classOf[Resume],
classOf[Terminate],
classOf[Supervise],
classOf[Watch],
classOf[Unwatch],
classOf[Failed],
NoMessage.getClass)
}
class SerializeSpec extends AkkaSpec(SerializationTests.serializeConf) {
@ -387,64 +388,74 @@ class SerializationCompatibilitySpec extends AkkaSpec(SerializationTests.mostlyR
"be preserved for the Create SystemMessage" in {
// Using null as the cause to avoid a large serialized message and JDK differences
verify(Create(Some(null)),
"aced00057372001b616b6b612e64697370617463682e7379736d73672e4372656174650000000000" +
"0000010200014c00076661696c75726574000e4c7363616c612f4f7074696f6e3b78707372000a73" +
"63616c612e536f6d651122f2695ea18b740200014c0001787400124c6a6176612f6c616e672f4f62" +
"6a6563743b7872000c7363616c612e4f7074696f6efe6937fddb0e6674020000787070")
verify(
Create(Some(null)),
"aced00057372001b616b6b612e64697370617463682e7379736d73672e4372656174650000000000" +
"0000010200014c00076661696c75726574000e4c7363616c612f4f7074696f6e3b78707372000a73" +
"63616c612e536f6d651122f2695ea18b740200014c0001787400124c6a6176612f6c616e672f4f62" +
"6a6563743b7872000c7363616c612e4f7074696f6efe6937fddb0e6674020000787070")
}
"be preserved for the Recreate SystemMessage" in {
verify(Recreate(null),
"aced00057372001d616b6b612e64697370617463682e7379736d73672e5265637265617465000000" +
"00000000010200014c000563617573657400154c6a6176612f6c616e672f5468726f7761626c653b" +
"787070")
verify(
Recreate(null),
"aced00057372001d616b6b612e64697370617463682e7379736d73672e5265637265617465000000" +
"00000000010200014c000563617573657400154c6a6176612f6c616e672f5468726f7761626c653b" +
"787070")
}
"be preserved for the Suspend SystemMessage" in {
verify(Suspend(),
"aced00057372001c616b6b612e64697370617463682e7379736d73672e53757370656e6400000000" +
"000000010200007870")
verify(
Suspend(),
"aced00057372001c616b6b612e64697370617463682e7379736d73672e53757370656e6400000000" +
"000000010200007870")
}
"be preserved for the Resume SystemMessage" in {
verify(Resume(null),
"aced00057372001b616b6b612e64697370617463682e7379736d73672e526573756d650000000000" +
"0000010200014c000f63617573656442794661696c7572657400154c6a6176612f6c616e672f5468" +
"726f7761626c653b787070")
verify(
Resume(null),
"aced00057372001b616b6b612e64697370617463682e7379736d73672e526573756d650000000000" +
"0000010200014c000f63617573656442794661696c7572657400154c6a6176612f6c616e672f5468" +
"726f7761626c653b787070")
}
"be preserved for the Terminate SystemMessage" in {
verify(Terminate(),
"aced00057372001e616b6b612e64697370617463682e7379736d73672e5465726d696e6174650000" +
"0000000000010200007870")
verify(
Terminate(),
"aced00057372001e616b6b612e64697370617463682e7379736d73672e5465726d696e6174650000" +
"0000000000010200007870")
}
"be preserved for the Supervise SystemMessage" in {
verify(Supervise(null, true),
"aced00057372001e616b6b612e64697370617463682e7379736d73672e5375706572766973650000" +
"0000000000010200025a00056173796e634c00056368696c647400154c616b6b612f6163746f722f" +
"4163746f725265663b78700170")
verify(
Supervise(null, true),
"aced00057372001e616b6b612e64697370617463682e7379736d73672e5375706572766973650000" +
"0000000000010200025a00056173796e634c00056368696c647400154c616b6b612f6163746f722f" +
"4163746f725265663b78700170")
}
"be preserved for the Watch SystemMessage" in {
verify(Watch(null, null),
"aced00057372001a616b6b612e64697370617463682e7379736d73672e5761746368000000000000" +
"00010200024c00077761746368656574001d4c616b6b612f6163746f722f496e7465726e616c4163" +
"746f725265663b4c00077761746368657271007e000178707070")
verify(
Watch(null, null),
"aced00057372001a616b6b612e64697370617463682e7379736d73672e5761746368000000000000" +
"00010200024c00077761746368656574001d4c616b6b612f6163746f722f496e7465726e616c4163" +
"746f725265663b4c00077761746368657271007e000178707070")
}
"be preserved for the Unwatch SystemMessage" in {
verify(Unwatch(null, null),
"aced00057372001c616b6b612e64697370617463682e7379736d73672e556e776174636800000000" +
"000000010200024c0007776174636865657400154c616b6b612f6163746f722f4163746f72526566" +
"3b4c00077761746368657271007e000178707070")
verify(
Unwatch(null, null),
"aced00057372001c616b6b612e64697370617463682e7379736d73672e556e776174636800000000" +
"000000010200024c0007776174636865657400154c616b6b612f6163746f722f4163746f72526566" +
"3b4c00077761746368657271007e000178707070")
}
"be preserved for the NoMessage SystemMessage" in {
verify(NoMessage,
"aced00057372001f616b6b612e64697370617463682e7379736d73672e4e6f4d6573736167652400" +
"000000000000010200007870")
verify(
NoMessage,
"aced00057372001f616b6b612e64697370617463682e7379736d73672e4e6f4d6573736167652400" +
"000000000000010200007870")
}
"be preserved for the Failed SystemMessage" in {
// Using null as the cause to avoid a large serialized message and JDK differences
verify(Failed(null, cause = null, uid = 0),
"aced00057372001b616b6b612e64697370617463682e7379736d73672e4661696c65640000000000" +
"0000010200034900037569644c000563617573657400154c6a6176612f6c616e672f5468726f7761" +
"626c653b4c00056368696c647400154c616b6b612f6163746f722f4163746f725265663b78700000" +
"00007070")
verify(
Failed(null, cause = null, uid = 0),
"aced00057372001b616b6b612e64697370617463682e7379736d73672e4661696c65640000000000" +
"0000010200034900037569644c000563617573657400154c6a6176612f6c616e672f5468726f7761" +
"626c653b4c00056368696c647400154c616b6b612f6163746f722f4163746f725265663b78700000" +
"00007070")
}
}

View file

@ -624,9 +624,10 @@ trait CustomContainsMatcher {
}
def matchResult(success: Boolean): MatchResult =
MatchResult(success,
s"""$left did not contain all of $right in sequence""",
s"""$left contains all of $right in sequence""")
MatchResult(
success,
s"""$left did not contain all of $right in sequence""",
s"""$left contains all of $right in sequence""")
attemptMatch(left.toList, right)
}
@ -704,12 +705,13 @@ trait QueueSetupHelper {
import akka.util.QueueTestEvents._
case class TestContext(queue: BoundedBlockingQueue[String],
events: mutable.Buffer[QueueEvent],
notEmpty: TestCondition,
notFull: TestCondition,
lock: ReentrantLock,
backingQueue: util.Queue[String])
case class TestContext(
queue: BoundedBlockingQueue[String],
events: mutable.Buffer[QueueEvent],
notEmpty: TestCondition,
notFull: TestCondition,
lock: ReentrantLock,
backingQueue: util.Queue[String])
/**
* Backing queue that records all poll and offer calls in `events`
@ -735,10 +737,11 @@ trait QueueSetupHelper {
/**
* Reentrant lock condition that records when the condition is signaled or `await`ed.
*/
class TestCondition(events: mutable.Buffer[QueueEvent],
condition: Condition,
signalEvent: QueueEvent,
awaitEvent: QueueEvent)
class TestCondition(
events: mutable.Buffer[QueueEvent],
condition: Condition,
signalEvent: QueueEvent,
awaitEvent: QueueEvent)
extends Condition {
case class Manual(waitTime: Long = 0, waitingThread: Option[Thread] = None)

View file

@ -164,8 +164,9 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
(!strict || (bsIterator.toSeq == vecIterator.toSeq))
}
def likeVecIts(a: ByteString, b: ByteString)(body: (BufferedIterator[Byte], BufferedIterator[Byte]) => Any,
strict: Boolean = true): Boolean = {
def likeVecIts(a: ByteString, b: ByteString)(
body: (BufferedIterator[Byte], BufferedIterator[Byte]) => Any,
strict: Boolean = true): Boolean = {
val (bsAIt, bsBIt) = (a.iterator, b.iterator)
val (vecAIt, vecBIt) = (Vector(a: _*).iterator.buffered, Vector(b: _*).iterator.buffered)
(body(bsAIt, bsBIt) == body(vecAIt, vecBIt)) &&
@ -689,17 +690,19 @@ class ByteStringSpec extends WordSpec with Matchers with Checkers {
(a ++ b ++ c) should ===(xs)
}
"recombining - edge cases" in {
excerciseRecombining(ByteStrings(Vector(ByteString1(Array[Byte](1)), ByteString1(Array[Byte](2)))),
-2147483648,
112121212)
excerciseRecombining(
ByteStrings(Vector(ByteString1(Array[Byte](1)), ByteString1(Array[Byte](2)))),
-2147483648,
112121212)
excerciseRecombining(ByteStrings(Vector(ByteString1(Array[Byte](100)))), 0, 2)
excerciseRecombining(ByteStrings(Vector(ByteString1(Array[Byte](100)))), -2147483648, 2)
excerciseRecombining(ByteStrings(Vector(ByteString1.fromString("ab"), ByteString1.fromString("cd"))), 0, 1)
excerciseRecombining(ByteString1.fromString("abc").drop(1).take(1), -324234, 234232)
excerciseRecombining(ByteString("a"), 0, 2147483647)
excerciseRecombining(ByteStrings(Vector(ByteString1.fromString("ab"), ByteString1.fromString("cd"))).drop(2),
2147483647,
1)
excerciseRecombining(
ByteStrings(Vector(ByteString1.fromString("ab"), ByteString1.fromString("cd"))).drop(2),
2147483647,
1)
excerciseRecombining(ByteString1.fromString("ab").drop1(1), Int.MaxValue, Int.MaxValue)
}
}

View file

@ -517,16 +517,18 @@ class InterceptScalaBehaviorSpec extends ImmutableWithSignalScalaBehaviorSpec wi
override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = {
val inbox = TestInbox[Either[Signal, Command]]("tapListener")
val tap = new BehaviorInterceptor[Command, Command] {
override def aroundReceive(context: TypedActorContext[Command],
message: Command,
target: ReceiveTarget[Command]): Behavior[Command] = {
override def aroundReceive(
context: TypedActorContext[Command],
message: Command,
target: ReceiveTarget[Command]): Behavior[Command] = {
inbox.ref ! Right(message)
target(context, message)
}
override def aroundSignal(context: TypedActorContext[Command],
signal: Signal,
target: SignalTarget[Command]): Behavior[Command] = {
override def aroundSignal(
context: TypedActorContext[Command],
signal: Signal,
target: SignalTarget[Command]): Behavior[Command] = {
inbox.ref ! Left(signal)
target(context, signal)
}
@ -567,7 +569,7 @@ class ImmutableWithSignalJavaBehaviorSpec extends Messages with BecomeWithLifecy
SBehaviors.same
case Stop => SBehaviors.stopped
case _: AuxPing => SBehaviors.unhandled
}),
}),
fs((_, sig) => {
monitor ! ReceivedSignal(sig)
SBehaviors.same
@ -600,7 +602,7 @@ class ImmutableJavaBehaviorSpec extends Messages with Become with Stoppable {
SBehaviors.same
case Stop => SBehaviors.stopped
case _: AuxPing => SBehaviors.unhandled
})
})
}
}
@ -635,16 +637,18 @@ class TapJavaBehaviorSpec extends ImmutableWithSignalJavaBehaviorSpec with Reuse
override def behavior(monitor: ActorRef[Event]): (Behavior[Command], Aux) = {
val inbox = TestInbox[Either[Signal, Command]]("tapListener")
val tap = new BehaviorInterceptor[Command, Command] {
override def aroundReceive(context: TypedActorContext[Command],
message: Command,
target: ReceiveTarget[Command]): Behavior[Command] = {
override def aroundReceive(
context: TypedActorContext[Command],
message: Command,
target: ReceiveTarget[Command]): Behavior[Command] = {
inbox.ref ! Right(message)
target(context, message)
}
override def aroundSignal(context: TypedActorContext[Command],
signal: Signal,
target: SignalTarget[Command]): Behavior[Command] = {
override def aroundSignal(
context: TypedActorContext[Command],
signal: Signal,
target: SignalTarget[Command]): Behavior[Command] = {
inbox.ref ! Left(signal)
target(context, signal)
}

View file

@ -95,9 +95,11 @@ class ExtensionsSpec extends ScalaTestWithActorTestKit with WordSpecLike {
}
"load extensions from the configuration" in
withEmptyActorSystem("ExtensionsSpec03",
Some(ConfigFactory.parseString(
"""
withEmptyActorSystem(
"ExtensionsSpec03",
Some(
ConfigFactory.parseString(
"""
akka.actor.typed.extensions = ["akka.actor.typed.DummyExtension1$", "akka.actor.typed.SlowExtension$"]
"""))) { sys =>
sys.hasExtension(DummyExtension1) should ===(true)
@ -109,10 +111,10 @@ class ExtensionsSpec extends ScalaTestWithActorTestKit with WordSpecLike {
"handle extensions that fail to initialize" in {
def create(): Unit = {
ActorSystem[Any](Behavior.EmptyBehavior,
"ExtensionsSpec04",
ConfigFactory.parseString(
"""
ActorSystem[Any](
Behavior.EmptyBehavior,
"ExtensionsSpec04",
ConfigFactory.parseString("""
akka.actor.typed.extensions = ["akka.actor.typed.FailingToLoadExtension$"]
"""))
}
@ -157,9 +159,10 @@ class ExtensionsSpec extends ScalaTestWithActorTestKit with WordSpecLike {
"fail the system if a library-extension is missing" in
intercept[RuntimeException] {
withEmptyActorSystem("ExtensionsSpec08",
Some(ConfigFactory.parseString(
"""akka.actor.typed.library-extensions += "akka.actor.typed.MissingExtension""""))) { _ =>
withEmptyActorSystem(
"ExtensionsSpec08",
Some(ConfigFactory.parseString(
"""akka.actor.typed.library-extensions += "akka.actor.typed.MissingExtension""""))) { _ =>
()
}
}
@ -206,12 +209,14 @@ class ExtensionsSpec extends ScalaTestWithActorTestKit with WordSpecLike {
}
"override extensions via ActorSystemSetup" in
withEmptyActorSystem("ExtensionsSpec10",
Some(ConfigFactory.parseString(
"""
withEmptyActorSystem(
"ExtensionsSpec10",
Some(
ConfigFactory.parseString(
"""
akka.actor.typed.extensions = ["akka.actor.typed.DummyExtension1$", "akka.actor.typed.SlowExtension$"]
""")),
Some(ActorSystemSetup(new DummyExtension1Setup(sys => new DummyExtension1ViaSetup)))) { sys =>
Some(ActorSystemSetup(new DummyExtension1Setup(sys => new DummyExtension1ViaSetup)))) { sys =>
sys.hasExtension(DummyExtension1) should ===(true)
sys.extension(DummyExtension1) shouldBe a[DummyExtension1ViaSetup]
DummyExtension1(sys) shouldBe a[DummyExtension1ViaSetup]

View file

@ -31,18 +31,20 @@ class InterceptSpec extends ScalaTestWithActorTestKit("""
implicit val untypedSystem = system.toUntyped
private def snitchingInterceptor(probe: ActorRef[String]) = new BehaviorInterceptor[String, String] {
override def aroundReceive(context: TypedActorContext[String],
message: String,
target: ReceiveTarget[String]): Behavior[String] = {
override def aroundReceive(
context: TypedActorContext[String],
message: String,
target: ReceiveTarget[String]): Behavior[String] = {
probe ! ("before " + message)
val b = target(context, message)
probe ! ("after " + message)
b
}
override def aroundSignal(context: TypedActorContext[String],
signal: Signal,
target: SignalTarget[String]): Behavior[String] = {
override def aroundSignal(
context: TypedActorContext[String],
signal: Signal,
target: SignalTarget[String]): Behavior[String] = {
target(context, signal)
}
@ -154,19 +156,22 @@ class InterceptSpec extends ScalaTestWithActorTestKit("""
"allow an interceptor to replace started behavior" in {
val interceptor = new BehaviorInterceptor[String, String] {
override def aroundStart(context: TypedActorContext[String],
target: PreStartTarget[String]): Behavior[String] = {
override def aroundStart(
context: TypedActorContext[String],
target: PreStartTarget[String]): Behavior[String] = {
Behaviors.stopped
}
def aroundReceive(context: TypedActorContext[String],
message: String,
target: ReceiveTarget[String]): Behavior[String] =
def aroundReceive(
context: TypedActorContext[String],
message: String,
target: ReceiveTarget[String]): Behavior[String] =
target(context, message)
def aroundSignal(context: TypedActorContext[String],
signal: Signal,
target: SignalTarget[String]): Behavior[String] =
def aroundSignal(
context: TypedActorContext[String],
signal: Signal,
target: SignalTarget[String]): Behavior[String] =
target(context, signal)
}
@ -260,18 +265,20 @@ class InterceptSpec extends ScalaTestWithActorTestKit("""
}
val poisonInterceptor = new BehaviorInterceptor[Any, Msg] {
override def aroundReceive(context: TypedActorContext[Any],
message: Any,
target: ReceiveTarget[Msg]): Behavior[Msg] =
override def aroundReceive(
context: TypedActorContext[Any],
message: Any,
target: ReceiveTarget[Msg]): Behavior[Msg] =
message match {
case MyPoisonPill => Behaviors.stopped
case m: Msg => target(context, m)
case _ => Behaviors.unhandled
}
override def aroundSignal(context: TypedActorContext[Any],
signal: Signal,
target: SignalTarget[Msg]): Behavior[Msg] =
override def aroundSignal(
context: TypedActorContext[Any],
signal: Signal,
target: SignalTarget[Msg]): Behavior[Msg] =
target.apply(context, signal)
}
@ -302,16 +309,18 @@ class InterceptSpec extends ScalaTestWithActorTestKit("""
override def interceptMessageType = classOf[B]
override def aroundReceive(ctx: TypedActorContext[Message],
msg: Message,
target: ReceiveTarget[Message]): Behavior[Message] = {
override def aroundReceive(
ctx: TypedActorContext[Message],
msg: Message,
target: ReceiveTarget[Message]): Behavior[Message] = {
interceptProbe.ref ! msg
target(ctx, msg)
}
override def aroundSignal(ctx: TypedActorContext[Message],
signal: Signal,
target: SignalTarget[Message]): Behavior[Message] =
override def aroundSignal(
ctx: TypedActorContext[Message],
signal: Signal,
target: SignalTarget[Message]): Behavior[Message] =
target(ctx, signal)
}
@ -332,14 +341,16 @@ class InterceptSpec extends ScalaTestWithActorTestKit("""
"intercept PostStop" in {
val probe = TestProbe[String]()
val postStopInterceptor = new BehaviorInterceptor[String, String] {
def aroundReceive(ctx: TypedActorContext[String],
msg: String,
target: ReceiveTarget[String]): Behavior[String] = {
def aroundReceive(
ctx: TypedActorContext[String],
msg: String,
target: ReceiveTarget[String]): Behavior[String] = {
target(ctx, msg)
}
def aroundSignal(ctx: TypedActorContext[String],
signal: Signal,
target: SignalTarget[String]): Behavior[String] = {
def aroundSignal(
ctx: TypedActorContext[String],
signal: Signal,
target: SignalTarget[String]): Behavior[String] = {
signal match {
case PostStop =>
probe.ref ! "interceptor-post-stop"

View file

@ -42,9 +42,10 @@ object SupervisionSpec {
class Exc2 extends Exc1("exc-2")
class Exc3(message: String = "exc-3") extends RuntimeException(message) with NoStackTrace
def targetBehavior(monitor: ActorRef[Event],
state: State = State(0, Map.empty),
slowStop: Option[CountDownLatch] = None): Behavior[Command] =
def targetBehavior(
monitor: ActorRef[Event],
state: State = State(0, Map.empty),
slowStop: Option[CountDownLatch] = None): Behavior[Command] =
receive[Command] { (context, cmd) =>
cmd match {
case Ping(n) =>
@ -1066,14 +1067,16 @@ class SupervisionSpec extends ScalaTestWithActorTestKit("""
// irrelevant for test case but needed to use intercept in the pyramid of doom below
val whateverInterceptor = new BehaviorInterceptor[String, String] {
// identity intercept
override def aroundReceive(context: TypedActorContext[String],
message: String,
target: ReceiveTarget[String]): Behavior[String] =
override def aroundReceive(
context: TypedActorContext[String],
message: String,
target: ReceiveTarget[String]): Behavior[String] =
target(context, message)
override def aroundSignal(context: TypedActorContext[String],
signal: Signal,
target: SignalTarget[String]): Behavior[String] =
override def aroundSignal(
context: TypedActorContext[String],
signal: Signal,
target: SignalTarget[String]): Behavior[String] =
target(context, signal)
}
@ -1197,11 +1200,12 @@ class SupervisionSpec extends ScalaTestWithActorTestKit("""
}
val allStrategies = Seq(SupervisorStrategy.stop,
SupervisorStrategy.restart,
SupervisorStrategy.resume,
SupervisorStrategy.restartWithBackoff(1.millis, 100.millis, 2d),
SupervisorStrategy.restart.withLimit(1, 100.millis))
val allStrategies = Seq(
SupervisorStrategy.stop,
SupervisorStrategy.restart,
SupervisorStrategy.resume,
SupervisorStrategy.restartWithBackoff(1.millis, 100.millis, 2d),
SupervisorStrategy.restart.withLimit(1, 100.millis))
allStrategies.foreach { strategy =>
s"Supervision with the strategy $strategy" should {

View file

@ -118,12 +118,13 @@ class WatchSpec extends ScalaTestWithActorTestKit(WatchSpec.config) with WordSpe
val probe = TestProbe[Any]()
val ex = new TestException("boom")
val behavior = Behaviors.setup[Any] { context =>
val child = context.spawn(Behaviors
.supervise(Behaviors.receive[Any]((_, _) => {
throw ex
}))
.onFailure[Throwable](SupervisorStrategy.stop),
"child")
val child = context.spawn(
Behaviors
.supervise(Behaviors.receive[Any]((_, _) => {
throw ex
}))
.onFailure[Throwable](SupervisorStrategy.stop),
"child")
context.watch(child)
Behaviors
@ -153,8 +154,8 @@ class WatchSpec extends ScalaTestWithActorTestKit(WatchSpec.config) with WordSpe
val probe = TestProbe[Any]()
val ex = new TestException("boom")
val grossoBosso =
spawn(Behaviors.setup[Any] {
context =>
spawn(
Behaviors.setup[Any] { context =>
val middleManagement = context.spawn(Behaviors.setup[Any] { context =>
val sixPackJoe = context.spawn(Behaviors.receive[Any]((context, message) => throw ex), "joe")
context.watch(sixPackJoe)
@ -178,7 +179,8 @@ class WatchSpec extends ScalaTestWithActorTestKit(WatchSpec.config) with WordSpe
Behaviors.stopped
}
}, "grosso-bosso")
},
"grosso-bosso")
EventFilter[TestException](occurrences = 1).intercept {
EventFilter[DeathPactException](occurrences = 1).intercept {

View file

@ -39,9 +39,10 @@ class ActorSystemSpec extends WordSpec with Matchers with BeforeAndAfterAll with
"An ActorSystem" must {
"start the guardian actor and terminate when it terminates" in {
val t = withSystem("a",
Behaviors.receive[Probe] { case (_, p) => p.replyTo ! p.message; Behaviors.stopped },
doTerminate = false) { sys =>
val t = withSystem(
"a",
Behaviors.receive[Probe] { case (_, p) => p.replyTo ! p.message; Behaviors.stopped },
doTerminate = false) { sys =>
val inbox = TestInbox[String]("a")
sys ! Probe("hello", inbox.ref)
eventually {
@ -68,16 +69,17 @@ class ActorSystemSpec extends WordSpec with Matchers with BeforeAndAfterAll with
"terminate the guardian actor" in {
val inbox = TestInbox[String]("terminate")
val sys = system(Behaviors
.receive[Probe] {
case (_, _) => Behaviors.unhandled
}
.receiveSignal {
case (_, PostStop) =>
inbox.ref ! "done"
Behaviors.same
},
"terminate")
val sys = system(
Behaviors
.receive[Probe] {
case (_, _) => Behaviors.unhandled
}
.receiveSignal {
case (_, PostStop) =>
inbox.ref ! "done"
Behaviors.same
},
"terminate")
sys.terminate().futureValue
inbox.receiveAll() should ===("done" :: Nil)
}

View file

@ -302,12 +302,13 @@ class ActorLoggingSpec extends ScalaTestWithActorTestKit("""
"Logging with MDC for a typed actor" must {
"provide the MDC values in the log" in {
val behaviors = Behaviors.withMdc[Protocol](Map("static" -> 1),
// FIXME why u no infer the type here Scala??
(message: Protocol) =>
if (message.transactionId == 1)
Map("txId" -> message.transactionId, "first" -> true)
else Map("txId" -> message.transactionId)) {
val behaviors = Behaviors.withMdc[Protocol](
Map("static" -> 1),
// FIXME why u no infer the type here Scala??
(message: Protocol) =>
if (message.transactionId == 1)
Map("txId" -> message.transactionId, "first" -> true)
else Map("txId" -> message.transactionId)) {
Behaviors.setup { context =>
context.log.info("Starting")
Behaviors.receiveMessage { _ =>

View file

@ -67,15 +67,17 @@ class StopSpec extends ScalaTestWithActorTestKit with WordSpecLike {
val probe = TestProbe[Done]()
spawn(Behaviors.setup[AnyRef] { _ =>
Behaviors.intercept(new BehaviorInterceptor[AnyRef, AnyRef] {
override def aroundReceive(context: typed.TypedActorContext[AnyRef],
message: AnyRef,
target: ReceiveTarget[AnyRef]): Behavior[AnyRef] = {
override def aroundReceive(
context: typed.TypedActorContext[AnyRef],
message: AnyRef,
target: ReceiveTarget[AnyRef]): Behavior[AnyRef] = {
target(context, message)
}
override def aroundSignal(context: typed.TypedActorContext[AnyRef],
signal: Signal,
target: SignalTarget[AnyRef]): Behavior[AnyRef] = {
override def aroundSignal(
context: typed.TypedActorContext[AnyRef],
signal: Signal,
target: SignalTarget[AnyRef]): Behavior[AnyRef] = {
target(context, signal)
}
})(Behaviors.stopped { () =>

View file

@ -178,8 +178,9 @@ class AdapterSpec extends AkkaSpec("""
for { _ <- 0 to 10 } {
var system: akka.actor.typed.ActorSystem[NotUsed] = null
try {
system = ActorSystem.create(Behaviors.setup[NotUsed](_ => Behavior.stopped[NotUsed]),
"AdapterSpec-stopping-guardian")
system = ActorSystem.create(
Behaviors.setup[NotUsed](_ => Behavior.stopped[NotUsed]),
"AdapterSpec-stopping-guardian")
} finally if (system != null) shutdown(system.toUntyped)
}
}

View file

@ -161,21 +161,23 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with WordSpecLik
Behaviors.withTimers(timers => idle(timers, target, after, maxSize))
}
def idle(timers: TimerScheduler[Msg],
target: ActorRef[Batch],
after: FiniteDuration,
maxSize: Int): Behavior[Msg] = {
def idle(
timers: TimerScheduler[Msg],
target: ActorRef[Batch],
after: FiniteDuration,
maxSize: Int): Behavior[Msg] = {
Behaviors.receiveMessage[Msg] { message =>
timers.startSingleTimer(TimerKey, Timeout, after)
active(Vector(message), timers, target, after, maxSize)
}
}
def active(buffer: Vector[Msg],
timers: TimerScheduler[Msg],
target: ActorRef[Batch],
after: FiniteDuration,
maxSize: Int): Behavior[Msg] = {
def active(
buffer: Vector[Msg],
timers: TimerScheduler[Msg],
target: ActorRef[Batch],
after: FiniteDuration,
maxSize: Int): Behavior[Msg] = {
Behaviors.receiveMessage[Msg] {
case Timeout =>
target ! Batch(buffer)
@ -298,10 +300,11 @@ class InteractionPatternsSpec extends ScalaTestWithActorTestKit with WordSpecLik
}
// per session actor behavior
def prepareToLeaveHome(whoIsLeaving: String,
respondTo: ActorRef[ReadyToLeaveHome],
keyCabinet: ActorRef[GetKeys],
drawer: ActorRef[GetWallet]): Behavior[NotUsed] =
def prepareToLeaveHome(
whoIsLeaving: String,
respondTo: ActorRef[ReadyToLeaveHome],
keyCabinet: ActorRef[GetKeys],
drawer: ActorRef[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 then we interact

View file

@ -133,8 +133,9 @@ object IntroSpec {
message match {
case GetSession(screenName, client) =>
// create a child actor for further interaction with the client
val ses = context.spawn(session(context.self, screenName, client),
name = URLEncoder.encode(screenName, StandardCharsets.UTF_8.name))
val ses = context.spawn(
session(context.self, screenName, client),
name = URLEncoder.encode(screenName, StandardCharsets.UTF_8.name))
client ! SessionGranted(ses)
chatRoom(ses :: sessions)
case PublishSessionMessage(screenName, message) =>
@ -144,9 +145,10 @@ object IntroSpec {
}
}
private def session(room: ActorRef[PublishSessionMessage],
screenName: String,
client: ActorRef[SessionEvent]): Behavior[SessionCommand] =
private def session(
room: ActorRef[PublishSessionMessage],
screenName: String,
client: ActorRef[SessionEvent]): Behavior[SessionCommand] =
Behaviors.receive { (context, message) =>
message match {
case PostMessage(message) =>

View file

@ -49,8 +49,9 @@ object OOIntroSpec {
message match {
case GetSession(screenName, client) =>
// create a child actor for further interaction with the client
val ses = context.spawn(session(context.self, screenName, client),
name = URLEncoder.encode(screenName, StandardCharsets.UTF_8.name))
val ses = context.spawn(
session(context.self, screenName, client),
name = URLEncoder.encode(screenName, StandardCharsets.UTF_8.name))
client ! SessionGranted(ses)
sessions = ses :: sessions
this
@ -62,9 +63,10 @@ object OOIntroSpec {
}
}
private def session(room: ActorRef[PublishSessionMessage],
screenName: String,
client: ActorRef[SessionEvent]): Behavior[SessionCommand] =
private def session(
room: ActorRef[PublishSessionMessage],
screenName: String,
client: ActorRef[SessionEvent]): Behavior[SessionCommand] =
Behaviors.receiveMessage {
case PostMessage(message) =>
// from client, publish to others via the room

View file

@ -172,10 +172,11 @@ object ActorSystem {
* Scala API: Creates a new actor system with the specified name and settings
* The core actor system settings are defined in [[BootstrapSetup]]
*/
def apply[T](guardianBehavior: Behavior[T],
name: String,
setup: ActorSystemSetup,
guardianProps: Props = Props.empty): ActorSystem[T] = {
def apply[T](
guardianBehavior: Behavior[T],
name: String,
setup: ActorSystemSetup,
guardianProps: Props = Props.empty): ActorSystem[T] = {
createInternal(name, guardianBehavior, guardianProps, setup)
}
@ -217,10 +218,11 @@ object ActorSystem {
* which runs Akka Typed [[Behavior]] on an emulation layer. In this
* system typed and untyped actors can coexist.
*/
private def createInternal[T](name: String,
guardianBehavior: Behavior[T],
guardianProps: Props,
setup: ActorSystemSetup): ActorSystem[T] = {
private def createInternal[T](
name: String,
guardianBehavior: Behavior[T],
guardianProps: Props,
setup: ActorSystemSetup): ActorSystem[T] = {
Behavior.validateAsInitial(guardianBehavior)
require(Behavior.isAlive(guardianBehavior))
@ -230,13 +232,13 @@ object ActorSystem {
val appConfig = bootstrapSettings.flatMap(_.config).getOrElse(ConfigFactory.load(cl))
val executionContext = bootstrapSettings.flatMap(_.defaultExecutionContext)
val system = new untyped.ActorSystemImpl(name,
appConfig,
cl,
executionContext,
Some(
PropsAdapter(() => guardianBehavior, guardianProps, isGuardian = true)),
setup)
val system = new untyped.ActorSystemImpl(
name,
appConfig,
cl,
executionContext,
Some(PropsAdapter(() => guardianBehavior, guardianProps, isGuardian = true)),
setup)
system.start()
system.guardian ! GuardianActorAdapter.Start

View file

@ -162,8 +162,9 @@ trait Extensions {
* implementation of the extension. Intended for tests that need to replace
* extension with stub/mock implementations.
*/
abstract class ExtensionSetup[T <: Extension](val extId: ExtensionId[T],
val createExtension: java.util.function.Function[ActorSystem[_], T])
abstract class ExtensionSetup[T <: Extension](
val extId: ExtensionId[T],
val createExtension: java.util.function.Function[ActorSystem[_], T])
extends Setup
/**

View file

@ -65,9 +65,10 @@ object SupervisorStrategy {
* random delay based on this factor is added, e.g. `0.2` adds up to `20%` delay.
* In order to skip this additional delay pass in `0`.
*/
def restartWithBackoff(minBackoff: FiniteDuration,
maxBackoff: FiniteDuration,
randomFactor: Double): BackoffSupervisorStrategy =
def restartWithBackoff(
minBackoff: FiniteDuration,
maxBackoff: FiniteDuration,
randomFactor: Double): BackoffSupervisorStrategy =
Backoff(minBackoff, maxBackoff, randomFactor, resetBackoffAfter = minBackoff)
/**
@ -97,9 +98,10 @@ object SupervisorStrategy {
* random delay based on this factor is added, e.g. `0.2` adds up to `20%` delay.
* In order to skip this additional delay pass in `0`.
*/
def restartWithBackoff(minBackoff: java.time.Duration,
maxBackoff: java.time.Duration,
randomFactor: Double): BackoffSupervisorStrategy =
def restartWithBackoff(
minBackoff: java.time.Duration,
maxBackoff: java.time.Duration,
randomFactor: Double): BackoffSupervisorStrategy =
restartWithBackoff(minBackoff.asScala, maxBackoff.asScala, randomFactor)
/**
@ -133,11 +135,12 @@ object SupervisorStrategy {
/**
* INTERNAL API
*/
@InternalApi private[akka] final case class Restart(maxRestarts: Int,
withinTimeRange: FiniteDuration,
loggingEnabled: Boolean = true,
stopChildren: Boolean = true,
stashCapacity: Int = -1)
@InternalApi private[akka] final case class Restart(
maxRestarts: Int,
withinTimeRange: FiniteDuration,
loggingEnabled: Boolean = true,
stopChildren: Boolean = true,
stashCapacity: Int = -1)
extends RestartSupervisorStrategy
with RestartOrBackoff {
@ -161,14 +164,15 @@ object SupervisorStrategy {
/**
* INTERNAL API
*/
@InternalApi private[akka] final case class Backoff(minBackoff: FiniteDuration,
maxBackoff: FiniteDuration,
randomFactor: Double,
resetBackoffAfter: FiniteDuration,
loggingEnabled: Boolean = true,
maxRestarts: Int = -1,
stopChildren: Boolean = true,
stashCapacity: Int = -1)
@InternalApi private[akka] final case class Backoff(
minBackoff: FiniteDuration,
maxBackoff: FiniteDuration,
randomFactor: Double,
resetBackoffAfter: FiniteDuration,
loggingEnabled: Boolean = true,
maxRestarts: Int = -1,
stopChildren: Boolean = true,
stashCapacity: Int = -1)
extends BackoffSupervisorStrategy
with RestartOrBackoff {

View file

@ -91,11 +91,12 @@ import akka.util.JavaDurationConverters._
}
// Java API impl
def ask[Req, Res](resClass: Class[Res],
target: RecipientRef[Req],
responseTimeout: Duration,
createRequest: JFunction[ActorRef[Res], Req],
applyToResponse: BiFunction[Res, Throwable, T]): Unit = {
def ask[Req, Res](
resClass: Class[Res],
target: RecipientRef[Req],
responseTimeout: Duration,
createRequest: JFunction[ActorRef[Res], Req],
applyToResponse: BiFunction[Res, Throwable, T]): Unit = {
import akka.actor.typed.javadsl.AskPattern
val message = new akka.japi.function.Function[ActorRef[Res], Req] {
def apply(ref: ActorRef[Res]): Req = createRequest(ref)

View file

@ -23,14 +23,16 @@ import akka.actor.typed.scaladsl.{ ActorContext => SAC }
def widened[O, I](behavior: Behavior[I], matcher: PartialFunction[O, I]): Behavior[O] =
intercept(WidenedInterceptor(matcher))(behavior)
class ReceiveBehavior[T](val onMessage: (SAC[T], T) => Behavior[T],
onSignal: PartialFunction[(SAC[T], Signal), Behavior[T]] =
Behavior.unhandledSignal.asInstanceOf[PartialFunction[(SAC[T], Signal), Behavior[T]]])
class ReceiveBehavior[T](
val onMessage: (SAC[T], T) => Behavior[T],
onSignal: PartialFunction[(SAC[T], Signal), Behavior[T]] =
Behavior.unhandledSignal.asInstanceOf[PartialFunction[(SAC[T], Signal), Behavior[T]]])
extends ExtensibleBehavior[T] {
override def receiveSignal(ctx: AC[T], msg: Signal): Behavior[T] =
onSignal.applyOrElse((ctx.asScala, msg),
Behavior.unhandledSignal.asInstanceOf[PartialFunction[(SAC[T], Signal), Behavior[T]]])
onSignal.applyOrElse(
(ctx.asScala, msg),
Behavior.unhandledSignal.asInstanceOf[PartialFunction[(SAC[T], Signal), Behavior[T]]])
override def receive(ctx: AC[T], msg: T) = onMessage(ctx.asScala, msg)
@ -42,16 +44,18 @@ import akka.actor.typed.scaladsl.{ ActorContext => SAC }
* We implement it separately in order to be able to avoid wrapping each function in
* another function which drops the context parameter.
*/
class ReceiveMessageBehavior[T](val onMessage: T => Behavior[T],
onSignal: PartialFunction[(SAC[T], Signal), Behavior[T]] = Behavior.unhandledSignal
.asInstanceOf[PartialFunction[(SAC[T], Signal), Behavior[T]]])
class ReceiveMessageBehavior[T](
val onMessage: T => Behavior[T],
onSignal: PartialFunction[(SAC[T], Signal), Behavior[T]] =
Behavior.unhandledSignal.asInstanceOf[PartialFunction[(SAC[T], Signal), Behavior[T]]])
extends ExtensibleBehavior[T] {
override def receive(ctx: AC[T], msg: T) = onMessage(msg)
override def receiveSignal(ctx: AC[T], msg: Signal): Behavior[T] =
onSignal.applyOrElse((ctx.asScala, msg),
Behavior.unhandledSignal.asInstanceOf[PartialFunction[(SAC[T], Signal), Behavior[T]]])
onSignal.applyOrElse(
(ctx.asScala, msg),
Behavior.unhandledSignal.asInstanceOf[PartialFunction[(SAC[T], Signal), Behavior[T]]])
override def toString = s"ReceiveMessage(${LineNumbers(onMessage)})"
}

View file

@ -33,8 +33,9 @@ private[akka] object InterceptorImpl {
* INTERNAL API
*/
@InternalApi
private[akka] final class InterceptorImpl[O, I](val interceptor: BehaviorInterceptor[O, I],
val nestedBehavior: Behavior[I])
private[akka] final class InterceptorImpl[O, I](
val interceptor: BehaviorInterceptor[O, I],
val nestedBehavior: Behavior[I])
extends ExtensibleBehavior[O]
with WrappingBehavior[O, I] {

View file

@ -34,14 +34,16 @@ import akka.annotation.InternalApi
* and process stashed messages before stopping.
*/
@InternalApi private[akka] final class PoisonPillInterceptor[M] extends BehaviorInterceptor[M, M] {
override def aroundReceive(ctx: TypedActorContext[M],
msg: M,
target: BehaviorInterceptor.ReceiveTarget[M]): Behavior[M] =
override def aroundReceive(
ctx: TypedActorContext[M],
msg: M,
target: BehaviorInterceptor.ReceiveTarget[M]): Behavior[M] =
target(ctx, msg)
override def aroundSignal(ctx: TypedActorContext[M],
signal: Signal,
target: BehaviorInterceptor.SignalTarget[M]): Behavior[M] = {
override def aroundSignal(
ctx: TypedActorContext[M],
signal: Signal,
target: BehaviorInterceptor.SignalTarget[M]): Behavior[M] = {
signal match {
case p: PoisonPill =>
val next = target(ctx, p)

View file

@ -33,9 +33,10 @@ import akka.util.ConstantFun
/**
* INTERNAL API
*/
@InternalApi private[akka] final class StashBufferImpl[T] private (val capacity: Int,
private var _first: StashBufferImpl.Node[T],
private var _last: StashBufferImpl.Node[T])
@InternalApi private[akka] final class StashBufferImpl[T] private (
val capacity: Int,
private var _first: StashBufferImpl.Node[T],
private var _last: StashBufferImpl.Node[T])
extends javadsl.StashBuffer[T]
with scaladsl.StashBuffer[T] {
@ -100,10 +101,11 @@ import akka.util.ConstantFun
override def unstashAll(ctx: javadsl.ActorContext[T], behavior: Behavior[T]): Behavior[T] =
unstashAll(ctx.asScala, behavior)
override def unstash(ctx: scaladsl.ActorContext[T],
behavior: Behavior[T],
numberOfMessages: Int,
wrap: T => T): Behavior[T] = {
override def unstash(
ctx: scaladsl.ActorContext[T],
behavior: Behavior[T],
numberOfMessages: Int,
wrap: T => T): Behavior[T] = {
if (isEmpty)
behavior // optimization
else {
@ -115,9 +117,10 @@ import akka.util.ConstantFun
}
}
private def interpretUnstashedMessages(behavior: Behavior[T],
ctx: TypedActorContext[T],
messages: Iterator[T]): Behavior[T] = {
private def interpretUnstashedMessages(
behavior: Behavior[T],
ctx: TypedActorContext[T],
messages: Iterator[T]): Behavior[T] = {
@tailrec def interpretOne(b: Behavior[T]): Behavior[T] = {
val b2 = Behavior.start(b, ctx)
if (!Behavior.isAlive(b2) || !messages.hasNext) b2
@ -138,10 +141,11 @@ import akka.util.ConstantFun
interpretOne(Behavior.start(behavior, ctx))
}
override def unstash(ctx: javadsl.ActorContext[T],
behavior: Behavior[T],
numberOfMessages: Int,
wrap: JFunction[T, T]): Behavior[T] =
override def unstash(
ctx: javadsl.ActorContext[T],
behavior: Behavior[T],
numberOfMessages: Int,
wrap: JFunction[T, T]): Behavior[T] =
unstash(ctx.asScala, behavior, numberOfMessages, x => wrap.apply(x))
override def toString: String =

View file

@ -144,10 +144,11 @@ private object RestartSupervisor {
/**
* Calculates an exponential back off delay.
*/
def calculateDelay(restartCount: Int,
minBackoff: FiniteDuration,
maxBackoff: FiniteDuration,
randomFactor: Double): FiniteDuration = {
def calculateDelay(
restartCount: Int,
minBackoff: FiniteDuration,
maxBackoff: FiniteDuration,
randomFactor: Double): FiniteDuration = {
val rnd = 1.0 + ThreadLocalRandom.current().nextDouble() * randomFactor
if (restartCount >= 30) // Duration overflow protection (> 100 years)
maxBackoff
@ -250,8 +251,9 @@ private class RestartSupervisor[O, T, Thr <: Throwable: ClassTag](initial: Behav
}
}
override protected def handleExceptionOnStart(ctx: TypedActorContext[O],
@unused target: PreStartTarget[T]): Catcher[Behavior[T]] = {
override protected def handleExceptionOnStart(
ctx: TypedActorContext[O],
@unused target: PreStartTarget[T]): Catcher[Behavior[T]] = {
case NonFatal(t) if isInstanceOfTheThrowableClass(t) =>
strategy match {
case _: Restart =>
@ -267,15 +269,17 @@ private class RestartSupervisor[O, T, Thr <: Throwable: ClassTag](initial: Behav
}
}
override protected def handleSignalException(ctx: TypedActorContext[O],
target: SignalTarget[T]): Catcher[Behavior[T]] = {
override protected def handleSignalException(
ctx: TypedActorContext[O],
target: SignalTarget[T]): Catcher[Behavior[T]] = {
handleException(ctx, signalRestart = {
case e: UnstashException[O] @unchecked => Behavior.interpretSignal(e.behavior, ctx, PreRestart)
case _ => target(ctx, PreRestart)
})
}
override protected def handleReceiveException(ctx: TypedActorContext[O],
target: ReceiveTarget[T]): Catcher[Behavior[T]] = {
override protected def handleReceiveException(
ctx: TypedActorContext[O],
target: ReceiveTarget[T]): Catcher[Behavior[T]] = {
handleException(ctx, signalRestart = {
case e: UnstashException[O] @unchecked => Behavior.interpretSignal(e.behavior, ctx, PreRestart)
case _ => target.signalRestart(ctx)
@ -335,9 +339,10 @@ private class RestartSupervisor[O, T, Thr <: Throwable: ClassTag](initial: Behav
strategy match {
case backoff: Backoff =>
gotScheduledRestart = false
ctx.asScala.scheduleOnce(backoff.resetBackoffAfter,
ctx.asScala.self.unsafeUpcast[Any],
ResetRestartCount(restartCount, this))
ctx.asScala.scheduleOnce(
backoff.resetBackoffAfter,
ctx.asScala.self.unsafeUpcast[Any],
ResetRestartCount(restartCount, this))
case _: Restart =>
}

View file

@ -132,10 +132,11 @@ import scala.concurrent.duration.FiniteDuration
OptionVal.Some(t.msg)
} else {
// it was from an old timer that was enqueued in mailbox before canceled
log.debug("Received timer [{}] from old generation [{}], expected generation [{}], discarding",
timerMsg.key,
timerMsg.generation,
t.generation)
log.debug(
"Received timer [{}] from old generation [{}], expected generation [{}], discarding",
timerMsg.key,
timerMsg.generation,
t.generation)
OptionVal.none // message should be ignored
}
}

View file

@ -16,9 +16,10 @@ import scala.collection.immutable.HashMap
@InternalApi private[akka] object WithMdcBehaviorInterceptor {
val noMdcPerMessage = (_: Any) => Map.empty[String, Any]
def apply[T](staticMdc: Map[String, Any],
mdcForMessage: T => Map[String, Any],
behavior: Behavior[T]): Behavior[T] = {
def apply[T](
staticMdc: Map[String, Any],
mdcForMessage: T => Map[String, Any],
behavior: Behavior[T]): Behavior[T] = {
val interceptor = new WithMdcBehaviorInterceptor[T](staticMdc, mdcForMessage)
BehaviorImpl.intercept(interceptor)(behavior)
@ -31,8 +32,9 @@ import scala.collection.immutable.HashMap
*
* INTERNAL API
*/
@InternalApi private[akka] final class WithMdcBehaviorInterceptor[T] private (staticMdc: Map[String, Any],
mdcForMessage: T => Map[String, Any])
@InternalApi private[akka] final class WithMdcBehaviorInterceptor[T] private (
staticMdc: Map[String, Any],
mdcForMessage: T => Map[String, Any])
extends BehaviorInterceptor[T, T] {
import BehaviorInterceptor._

View file

@ -277,8 +277,9 @@ private[typed] class GuardianActorAdapter[T](_initialBehavior: Behavior[T]) exte
/**
* INTERNAL API
*/
@InternalApi private[typed] final class ComposedStoppingBehavior[T](lastBehavior: Behavior[T],
stopBehavior: StoppedBehavior[T])
@InternalApi private[typed] final class ComposedStoppingBehavior[T](
lastBehavior: Behavior[T],
stopBehavior: StoppedBehavior[T])
extends ExtensibleBehavior[T] {
override def receive(ctx: TypedActorContext[T], msg: T): Behavior[T] =
throw new IllegalStateException("Stopping, should never receieve a message")

View file

@ -18,8 +18,9 @@ import scala.concurrent.duration._
/**
* INTERNAL API. Wrapping an [[akka.actor.ActorContext]] as an [[TypedActorContext]].
*/
@InternalApi private[akka] final class ActorContextAdapter[T](val untypedContext: untyped.ActorContext,
adapter: ActorAdapter[T])
@InternalApi private[akka] final class ActorContextAdapter[T](
val untypedContext: untyped.ActorContext,
adapter: ActorAdapter[T])
extends ActorContextImpl[T] {
import ActorRefAdapter.toUntyped

View file

@ -74,10 +74,11 @@ import akka.event.LoggingFilterWithMarker
}
override def dynamicAccess: untyped.DynamicAccess = untypedSystem.dynamicAccess
implicit override def executionContext: scala.concurrent.ExecutionContextExecutor = untypedSystem.dispatcher
override val log: Logger = new LoggerAdapterImpl(untypedSystem.eventStream,
getClass,
name,
LoggingFilterWithMarker.wrap(untypedSystem.logFilter))
override val log: Logger = new LoggerAdapterImpl(
untypedSystem.eventStream,
getClass,
name,
LoggingFilterWithMarker.wrap(untypedSystem.logFilter))
override def logConfiguration(): Unit = untypedSystem.logConfiguration()
override def name: String = untypedSystem.name
override def scheduler: akka.actor.Scheduler = untypedSystem.scheduler

View file

@ -85,13 +85,14 @@ private[akka] abstract class AbstractLogger extends Logger {
if (isErrorEnabled) notifyError(format(template, arg1, arg2, arg3), OptionVal.Some(cause), OptionVal.Some(marker))
}
override def error(marker: LogMarker,
cause: Throwable,
template: String,
arg1: Any,
arg2: Any,
arg3: Any,
arg4: Any): Unit = {
override def error(
marker: LogMarker,
cause: Throwable,
template: String,
arg1: Any,
arg2: Any,
arg3: Any,
arg4: Any): Unit = {
if (isErrorEnabled)
notifyError(format(template, arg1, arg2, arg3, arg4), OptionVal.Some(cause), OptionVal.Some(marker))
}
@ -169,13 +170,14 @@ private[akka] abstract class AbstractLogger extends Logger {
notifyWarning(format(template, arg1, arg2, arg3), OptionVal.Some(cause), OptionVal.Some(marker))
}
override def warning(marker: LogMarker,
cause: Throwable,
template: String,
arg1: Any,
arg2: Any,
arg3: Any,
arg4: Any): Unit = {
override def warning(
marker: LogMarker,
cause: Throwable,
template: String,
arg1: Any,
arg2: Any,
arg3: Any,
arg4: Any): Unit = {
if (isWarningEnabled)
notifyWarning(format(template, arg1, arg2, arg3, arg4), OptionVal.Some(cause), OptionVal.Some(marker))
}
@ -321,13 +323,14 @@ private[akka] abstract class AbstractLogger extends Logger {
if (isLevelEnabled(level)) notify(level, format(template, arg1, arg2, arg3), OptionVal.Some(marker))
}
override def log(level: LogLevel,
marker: LogMarker,
template: String,
arg1: Any,
arg2: Any,
arg3: Any,
arg4: Any): Unit = {
override def log(
level: LogLevel,
marker: LogMarker,
template: String,
arg1: Any,
arg2: Any,
arg3: Any,
arg4: Any): Unit = {
if (isLevelEnabled(level)) notify(level, format(template, arg1, arg2, arg3, arg4), OptionVal.Some(marker))
}
@ -378,10 +381,11 @@ private[akka] abstract class AbstractLogger extends Logger {
* INTERNAL API
*/
@InternalApi
private[akka] final class LoggerAdapterImpl(bus: LoggingBus,
logClass: Class[_],
logSource: String,
loggingFilter: LoggingFilterWithMarker)
private[akka] final class LoggerAdapterImpl(
bus: LoggingBus,
logClass: Class[_],
logSource: String,
loggingFilter: LoggingFilterWithMarker)
extends AbstractLogger {
override def isErrorEnabled = loggingFilter.isErrorEnabled(logClass, logSource)

View file

@ -13,9 +13,10 @@ import akka.annotation.InternalApi
* INTERNAL API
*/
@InternalApi private[akka] object PropsAdapter {
def apply[T](behavior: () => Behavior[T],
deploy: Props = Props.empty,
isGuardian: Boolean = false): akka.actor.Props = {
def apply[T](
behavior: () => Behavior[T],
deploy: Props = Props.empty,
isGuardian: Boolean = false): akka.actor.Props = {
val props =
if (isGuardian)
akka.actor.Props(new GuardianActorAdapter(behavior()))

View file

@ -50,8 +50,9 @@ private[akka] object LocalReceptionist extends ReceptionistBehaviorProvider {
private def behavior(serviceRegistry: LocalServiceRegistry, subscriptions: SubscriptionRegistry): Behavior[Any] = {
// Helper to create new state
def next(newRegistry: LocalServiceRegistry = serviceRegistry,
newSubscriptions: SubscriptionRegistry = subscriptions) =
def next(
newRegistry: LocalServiceRegistry = serviceRegistry,
newSubscriptions: SubscriptionRegistry = subscriptions) =
behavior(newRegistry, newSubscriptions)
/*
@ -69,8 +70,9 @@ private[akka] object LocalReceptionist extends ReceptionistBehaviorProvider {
})
// Helper that makes sure that subscribers are notified when an entry is changed
def updateRegistry(changedKeysHint: Set[AbstractServiceKey],
f: LocalServiceRegistry => LocalServiceRegistry): Behavior[Any] = {
def updateRegistry(
changedKeysHint: Set[AbstractServiceKey],
f: LocalServiceRegistry => LocalServiceRegistry): Behavior[Any] = {
val newRegistry = f(serviceRegistry)
def notifySubscribersFor[T](key: AbstractServiceKey): Unit = {

View file

@ -22,9 +22,10 @@ private[akka] object ReceptionistMessages {
// of type erasure, more type safe factory methods for each message
// is the user API below while still hiding the type parameter so that
// users don't incorrectly match against it
final case class Register[T] private[akka] (key: ServiceKey[T],
serviceInstance: ActorRef[T],
replyTo: Option[ActorRef[Receptionist.Registered]])
final case class Register[T] private[akka] (
key: ServiceKey[T],
serviceInstance: ActorRef[T],
replyTo: Option[ActorRef[Receptionist.Registered]])
extends Command
final case class Registered[T] private[akka] (key: ServiceKey[T], _serviceInstance: ActorRef[T])

View file

@ -17,9 +17,9 @@ import akka.annotation.InternalApi
* INTERNAL API
*/
@InternalApi
private[akka] final case class GroupRouterBuilder[T] private[akka] (key: ServiceKey[T],
logicFactory: () => RoutingLogic[T] = () =>
new RoutingLogics.RandomLogic[T]())
private[akka] final case class GroupRouterBuilder[T] private[akka] (
key: ServiceKey[T],
logicFactory: () => RoutingLogic[T] = () => new RoutingLogics.RandomLogic[T]())
extends javadsl.GroupRouter[T]
with scaladsl.GroupRouter[T] {

View file

@ -13,10 +13,10 @@ import akka.annotation.InternalApi
* INTERNAL API
*/
@InternalApi
private[akka] final case class PoolRouterBuilder[T](poolSize: Int,
behavior: Behavior[T],
logicFactory: () => RoutingLogic[T] = () =>
new RoutingLogics.RoundRobinLogic[T])
private[akka] final case class PoolRouterBuilder[T](
poolSize: Int,
behavior: Behavior[T],
logicFactory: () => RoutingLogic[T] = () => new RoutingLogics.RoundRobinLogic[T])
extends javadsl.PoolRouter[T]
with scaladsl.PoolRouter[T] {
if (poolSize < 1) throw new IllegalArgumentException(s"pool size must be positive, was $poolSize")
@ -36,10 +36,11 @@ private[akka] final case class PoolRouterBuilder[T](poolSize: Int,
* INTERNAL API
*/
@InternalApi
private final class PoolRouterImpl[T](ctx: ActorContext[T],
poolSize: Int,
behavior: Behavior[T],
logic: RoutingLogic[T])
private final class PoolRouterImpl[T](
ctx: ActorContext[T],
poolSize: Int,
behavior: Behavior[T],
logic: RoutingLogic[T])
extends AbstractBehavior[T] {
(1 to poolSize).foreach { _ =>

View file

@ -281,11 +281,12 @@ trait ActorContext[T] extends TypedActorContext[T] {
* @tparam Req The request protocol, what the other actor accepts
* @tparam Res The response protocol, what the other actor sends back
*/
def ask[Req, Res](resClass: Class[Res],
target: RecipientRef[Req],
responseTimeout: Duration,
createRequest: java.util.function.Function[ActorRef[Res], Req],
applyToResponse: BiFunction[Res, Throwable, T]): Unit
def ask[Req, Res](
resClass: Class[Res],
target: RecipientRef[Req],
responseTimeout: Duration,
createRequest: java.util.function.Function[ActorRef[Res], Req],
applyToResponse: BiFunction[Res, Throwable, T]): Unit
/**
* Sends the result of the given `CompletionStage` to this Actor (`self`), after adapted it with

View file

@ -30,9 +30,10 @@ import scala.compat.java8.FutureConverters._
*
*/
object AskPattern {
def ask[T, U](actor: RecipientRef[T],
message: JFunction[ActorRef[U], T],
timeout: Duration,
scheduler: Scheduler): CompletionStage[U] =
def ask[T, U](
actor: RecipientRef[T],
message: JFunction[ActorRef[U], T],
timeout: Duration,
scheduler: Scheduler): CompletionStage[U] =
(actor.ask(message.apply)(timeout.asScala, scheduler)).toJava
}

View file

@ -52,9 +52,10 @@ final class BehaviorBuilder[T] private (messageHandlers: List[Case[T, T]], signa
* @tparam M type of message to match
* @return a new behavior builder with the specified handling appended
*/
def onMessage[M <: T](`type`: Class[M],
test: JPredicate[M],
handler: JFunction2[ActorContext[T], M, Behavior[T]]): BehaviorBuilder[T] =
def onMessage[M <: T](
`type`: Class[M],
test: JPredicate[M],
handler: JFunction2[ActorContext[T], M, Behavior[T]]): BehaviorBuilder[T] =
withMessage(OptionVal.Some(`type`), OptionVal.Some((t: T) => test.test(t.asInstanceOf[M])), handler)
/**
@ -67,8 +68,9 @@ final class BehaviorBuilder[T] private (messageHandlers: List[Case[T, T]], signa
* @param handler action to apply when the type matches
* @return a new behavior builder with the specified handling appended
*/
def onMessageUnchecked[M <: T](`type`: Class[_ <: T],
handler: JFunction2[ActorContext[T], M, Behavior[T]]): BehaviorBuilder[T] =
def onMessageUnchecked[M <: T](
`type`: Class[_ <: T],
handler: JFunction2[ActorContext[T], M, Behavior[T]]): BehaviorBuilder[T] =
withMessage[M](OptionVal.Some(`type`.asInstanceOf[Class[M]]), OptionVal.None, handler)
/**
@ -79,11 +81,12 @@ final class BehaviorBuilder[T] private (messageHandlers: List[Case[T, T]], signa
* @return a new behavior builder with the specified handling appended
*/
def onMessageEquals(msg: T, handler: JFunction[ActorContext[T], Behavior[T]]): BehaviorBuilder[T] =
withMessage[T](OptionVal.Some(msg.getClass.asInstanceOf[Class[T]]),
OptionVal.Some(_.equals(msg)),
new JFunction2[ActorContext[T], T, Behavior[T]] {
override def apply(ctx: ActorContext[T], msg: T): Behavior[T] = handler.apply(ctx)
})
withMessage[T](
OptionVal.Some(msg.getClass.asInstanceOf[Class[T]]),
OptionVal.Some(_.equals(msg)),
new JFunction2[ActorContext[T], T, Behavior[T]] {
override def apply(ctx: ActorContext[T], msg: T): Behavior[T] = handler.apply(ctx)
})
/**
* Add a new case to the message handling matching any message. Subsequent `onMessage` clauses will
@ -103,8 +106,9 @@ final class BehaviorBuilder[T] private (messageHandlers: List[Case[T, T]], signa
* @tparam M type of signal to match
* @return a new behavior builder with the specified handling appended
*/
def onSignal[M <: Signal](`type`: Class[M],
handler: JFunction2[ActorContext[T], M, Behavior[T]]): BehaviorBuilder[T] =
def onSignal[M <: Signal](
`type`: Class[M],
handler: JFunction2[ActorContext[T], M, Behavior[T]]): BehaviorBuilder[T] =
withSignal(`type`, OptionVal.None, handler.asInstanceOf[JFunction2[ActorContext[T], Signal, Behavior[T]]])
/**
@ -116,12 +120,14 @@ final class BehaviorBuilder[T] private (messageHandlers: List[Case[T, T]], signa
* @tparam M type of signal to match
* @return a new behavior builder with the specified handling appended
*/
def onSignal[M <: Signal](`type`: Class[M],
test: JPredicate[M],
handler: JFunction2[ActorContext[T], M, Behavior[T]]): BehaviorBuilder[T] =
withSignal(`type`,
OptionVal.Some((t: Signal) => test.test(t.asInstanceOf[M])),
handler.asInstanceOf[JFunction2[ActorContext[T], Signal, Behavior[T]]])
def onSignal[M <: Signal](
`type`: Class[M],
test: JPredicate[M],
handler: JFunction2[ActorContext[T], M, Behavior[T]]): BehaviorBuilder[T] =
withSignal(
`type`,
OptionVal.Some((t: Signal) => test.test(t.asInstanceOf[M])),
handler.asInstanceOf[JFunction2[ActorContext[T], Signal, Behavior[T]]])
/**
* Add a new case to the signal handling matching equal signals.
@ -137,18 +143,21 @@ final class BehaviorBuilder[T] private (messageHandlers: List[Case[T, T]], signa
}
})
private def withMessage[M <: T](clazz: OptionVal[Class[M]],
test: OptionVal[M => Boolean],
handler: JFunction2[ActorContext[T], M, Behavior[T]]): BehaviorBuilder[T] = {
private def withMessage[M <: T](
clazz: OptionVal[Class[M]],
test: OptionVal[M => Boolean],
handler: JFunction2[ActorContext[T], M, Behavior[T]]): BehaviorBuilder[T] = {
val newCase = Case(clazz, test, handler)
new BehaviorBuilder[T](newCase.asInstanceOf[Case[T, T]] +: messageHandlers, signalHandlers)
}
private def withSignal[M <: Signal](`type`: Class[M],
test: OptionVal[Signal => Boolean],
handler: JFunction2[ActorContext[T], Signal, Behavior[T]]): BehaviorBuilder[T] = {
new BehaviorBuilder[T](messageHandlers,
Case(OptionVal.Some(`type`), test, handler).asInstanceOf[Case[T, Signal]] +: signalHandlers)
private def withSignal[M <: Signal](
`type`: Class[M],
test: OptionVal[Signal => Boolean],
handler: JFunction2[ActorContext[T], Signal, Behavior[T]]): BehaviorBuilder[T] = {
new BehaviorBuilder[T](
messageHandlers,
Case(OptionVal.Some(`type`), test, handler).asInstanceOf[Case[T, Signal]] +: signalHandlers)
}
}
@ -159,9 +168,10 @@ object BehaviorBuilder {
// used for both matching signals and messages so we throw away types after they are enforced by the builder API above
/** INTERNAL API */
@InternalApi
private[javadsl] final case class Case[BT, MT](`type`: OptionVal[Class[_ <: MT]],
test: OptionVal[MT => Boolean],
handler: JFunction2[ActorContext[BT], MT, Behavior[BT]])
private[javadsl] final case class Case[BT, MT](
`type`: OptionVal[Class[_ <: MT]],
test: OptionVal[MT => Boolean],
handler: JFunction2[ActorContext[BT], MT, Behavior[BT]])
/**
* @return new empty immutable behavior builder.

View file

@ -136,8 +136,9 @@ object Behaviors {
* that can potentially be different from this one. State is maintained by returning
* a new behavior that holds the new immutable state.
*/
def receive[T](onMessage: JapiFunction2[ActorContext[T], T, Behavior[T]],
onSignal: JapiFunction2[ActorContext[T], Signal, Behavior[T]]): Behavior[T] = {
def receive[T](
onMessage: JapiFunction2[ActorContext[T], 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)
})
@ -298,8 +299,9 @@ object Behaviors {
*
* See also [[akka.actor.typed.Logger.withMdc]]
*/
def withMdc[T](mdcForMessage: akka.japi.function.Function[T, java.util.Map[String, Any]],
behavior: Behavior[T]): Behavior[T] =
def withMdc[T](
mdcForMessage: akka.japi.function.Function[T, java.util.Map[String, Any]],
behavior: Behavior[T]): Behavior[T] =
withMdc(Collections.emptyMap[String, Any], mdcForMessage, behavior)
/**
@ -331,9 +333,10 @@ object Behaviors {
*
* See also [[akka.actor.typed.Logger.withMdc]]
*/
def withMdc[T](staticMdc: java.util.Map[String, Any],
mdcForMessage: akka.japi.function.Function[T, java.util.Map[String, Any]],
behavior: Behavior[T]): Behavior[T] = {
def withMdc[T](
staticMdc: java.util.Map[String, Any],
mdcForMessage: akka.japi.function.Function[T, java.util.Map[String, Any]],
behavior: Behavior[T]): Behavior[T] = {
def asScalaMap(m: java.util.Map[String, Any]): Map[String, Any] = {
if (m == null || m.isEmpty) Map.empty[String, Any]

View file

@ -20,8 +20,9 @@ import akka.util.OptionVal
*
* @tparam T the common superclass of all supported messages.
*/
final class ReceiveBuilder[T] private (private var messageHandlers: List[ReceiveBuilder.Case[T, T]],
private var signalHandlers: List[ReceiveBuilder.Case[T, Signal]]) {
final class ReceiveBuilder[T] private (
private var messageHandlers: List[ReceiveBuilder.Case[T, T]],
private var signalHandlers: List[ReceiveBuilder.Case[T, Signal]]) {
import ReceiveBuilder.Case
@ -108,9 +109,10 @@ final class ReceiveBuilder[T] private (private var messageHandlers: List[Receive
* @tparam M type of signal to match
* @return this behavior builder
*/
def onSignal[M <: Signal](`type`: Class[M],
test: JPredicate[M],
handler: JFunction[M, Behavior[T]]): ReceiveBuilder[T] =
def onSignal[M <: Signal](
`type`: Class[M],
test: JPredicate[M],
handler: JFunction[M, Behavior[T]]): ReceiveBuilder[T] =
withSignal(`type`, OptionVal.Some(test), handler)
/**
@ -127,16 +129,18 @@ final class ReceiveBuilder[T] private (private var messageHandlers: List[Receive
override def apply(param: Signal): Behavior[T] = handler.create()
})
private def withMessage[M <: T](`type`: OptionVal[Class[M]],
test: OptionVal[JPredicate[M]],
handler: JFunction[M, Behavior[T]]): ReceiveBuilder[T] = {
private def withMessage[M <: T](
`type`: OptionVal[Class[M]],
test: OptionVal[JPredicate[M]],
handler: JFunction[M, Behavior[T]]): ReceiveBuilder[T] = {
messageHandlers = Case[T, M](`type`, test, handler).asInstanceOf[Case[T, T]] +: messageHandlers
this
}
private def withSignal[M <: Signal](`type`: Class[M],
test: OptionVal[JPredicate[M]],
handler: JFunction[M, Behavior[T]]): ReceiveBuilder[T] = {
private def withSignal[M <: Signal](
`type`: Class[M],
test: OptionVal[JPredicate[M]],
handler: JFunction[M, Behavior[T]]): ReceiveBuilder[T] = {
signalHandlers = Case[T, M](OptionVal.Some(`type`), test, handler).asInstanceOf[Case[T, Signal]] +: signalHandlers
this
}
@ -149,9 +153,10 @@ object ReceiveBuilder {
/** INTERNAL API */
@InternalApi
private[javadsl] final case class Case[BT, MT](`type`: OptionVal[Class[_ <: MT]],
test: OptionVal[JPredicate[MT]],
handler: JFunction[MT, Behavior[BT]])
private[javadsl] final case class Case[BT, MT](
`type`: OptionVal[Class[_ <: MT]],
test: OptionVal[JPredicate[MT]],
handler: JFunction[MT, Behavior[BT]])
}
@ -161,8 +166,9 @@ object ReceiveBuilder {
* INTERNAL API
*/
@InternalApi
private final class BuiltReceive[T](messageHandlers: List[ReceiveBuilder.Case[T, T]],
signalHandlers: List[ReceiveBuilder.Case[T, Signal]])
private final class BuiltReceive[T](
messageHandlers: List[ReceiveBuilder.Case[T, T]],
signalHandlers: List[ReceiveBuilder.Case[T, Signal]])
extends Receive[T] {
import ReceiveBuilder.Case

View file

@ -42,9 +42,10 @@ abstract class Receptionist extends Extension {
.getObjectFor[ReceptionistBehaviorProvider]("akka.cluster.typed.internal.receptionist.ClusterReceptionist")
.recover {
case e =>
throw new RuntimeException("ClusterReceptionist could not be loaded dynamically. Make sure you have " +
"'akka-cluster-typed' in the classpath.",
e)
throw new RuntimeException(
"ClusterReceptionist could not be loaded dynamically. Make sure you have " +
"'akka-cluster-typed' in the classpath.",
e)
}
.get
} else LocalReceptionist

View file

@ -111,14 +111,16 @@ object AskPattern {
// Note: _promiseRef mustn't have a type pattern, since it can be null
private[this] val (_ref: ActorRef[U], _future: Future[U], _promiseRef) =
if (target.isTerminated)
(adapt.ActorRefAdapter[U](target.provider.deadLetters),
Future.failed[U](new TimeoutException(s"Recipient[$target] had already been terminated.")),
null)
(
adapt.ActorRefAdapter[U](target.provider.deadLetters),
Future.failed[U](new TimeoutException(s"Recipient[$target] had already been terminated.")),
null)
else if (timeout.duration.length <= 0)
(adapt.ActorRefAdapter[U](target.provider.deadLetters),
Future.failed[U](
new IllegalArgumentException(s"Timeout length must be positive, question not sent to [$target]")),
null)
(
adapt.ActorRefAdapter[U](target.provider.deadLetters),
Future.failed[U](
new IllegalArgumentException(s"Timeout length must be positive, question not sent to [$target]")),
null)
else {
// messageClassName "unknown' is set later, after applying the message factory
val a = PromiseActorRef(target.provider, timeout, target, "unknown", onTimeout = onTimeout)

View file

@ -58,9 +58,10 @@ package object adapter {
/**
* INTERNAL API
*/
@InternalApi private[akka] def internalSystemActorOf[U](behavior: Behavior[U],
name: String,
props: Props): ActorRef[U] = {
@InternalApi private[akka] def internalSystemActorOf[U](
behavior: Behavior[U],
name: String,
props: Props): ActorRef[U] = {
toUntyped.asInstanceOf[ExtendedActorSystem].systemActorOf(PropsAdapter(behavior, props), name)
}
}

View file

@ -559,9 +559,10 @@ object ByteString {
else if (remainingToDrop == 0)
new ByteStrings(bytestrings.dropRight(fullDrops), length - n)
else
new ByteStrings(bytestrings.dropRight(fullDrops + 1) :+ bytestrings(byteStringsSize - fullDrops - 1)
.dropRight1(remainingToDrop),
length - n)
new ByteStrings(
bytestrings.dropRight(fullDrops + 1) :+ bytestrings(byteStringsSize - fullDrops - 1)
.dropRight1(remainingToDrop),
length - n)
} else {
dropRightWithFullDropsAndRemainig(fullDrops + 1, remainingToDrop - bs.length)
}

View file

@ -553,9 +553,10 @@ object ByteString {
else if (remainingToDrop == 0)
new ByteStrings(bytestrings.dropRight(fullDrops), length - n)
else
new ByteStrings(bytestrings.dropRight(fullDrops + 1) :+ bytestrings(byteStringsSize - fullDrops - 1)
.dropRight1(remainingToDrop),
length - n)
new ByteStrings(
bytestrings.dropRight(fullDrops + 1) :+ bytestrings(byteStringsSize - fullDrops - 1)
.dropRight1(remainingToDrop),
length - n)
} else {
dropRightWithFullDropsAndRemainig(fullDrops + 1, remainingToDrop - bs.length)
}

View file

@ -51,9 +51,9 @@ package object ccompat {
fact: GenericCompanion[CC]): CanBuildFrom[Any, A, CC[A]] =
simpleCBF(fact.newBuilder[A])
private[akka] implicit def sortedSetCompanionToCBF[A: Ordering,
CC[X] <: c.SortedSet[X] with c.SortedSetLike[X, CC[X]]](
fact: SortedSetFactory[CC]): CanBuildFrom[Any, A, CC[A]] =
private[akka] implicit def sortedSetCompanionToCBF[
A: Ordering,
CC[X] <: c.SortedSet[X] with c.SortedSetLike[X, CC[X]]](fact: SortedSetFactory[CC]): CanBuildFrom[Any, A, CC[A]] =
simpleCBF(fact.newBuilder[A])
private[ccompat] def build[T, CC](builder: m.Builder[T, CC], source: TraversableOnce[T]): CC = {

View file

@ -93,9 +93,10 @@ abstract class AbstractFSM[S, D] extends FSM[S, D] {
* @param stateTimeout default state timeout for this state
* @param stateFunctionBuilder partial function builder describing response to input
*/
final def when(stateName: S,
stateTimeout: FiniteDuration,
stateFunctionBuilder: FSMStateFunctionBuilder[S, D]): Unit =
final def when(
stateName: S,
stateTimeout: FiniteDuration,
stateFunctionBuilder: FSMStateFunctionBuilder[S, D]): Unit =
super.when(stateName, stateTimeout)(stateFunctionBuilder.build())
/**
@ -108,9 +109,10 @@ abstract class AbstractFSM[S, D] extends FSM[S, D] {
* @param stateTimeout default state timeout for this state
* @param stateFunctionBuilder partial function builder describing response to input
*/
final def when(stateName: S,
stateTimeout: java.time.Duration,
stateFunctionBuilder: FSMStateFunctionBuilder[S, D]): Unit = {
final def when(
stateName: S,
stateTimeout: java.time.Duration,
stateFunctionBuilder: FSMStateFunctionBuilder[S, D]): Unit = {
import JavaDurationConverters._
when(stateName, stateTimeout.asScala, stateFunctionBuilder)
}
@ -199,10 +201,11 @@ abstract class AbstractFSM[S, D] extends FSM[S, D] {
* @param apply an action to apply to the event and state data if there is a match
* @return the builder with the case statement added
*/
final def matchEvent[ET, DT <: D](eventType: Class[ET],
dataType: Class[DT],
predicate: TypedPredicate2[ET, DT],
apply: Apply2[ET, DT, State]): FSMStateFunctionBuilder[S, D] =
final def matchEvent[ET, DT <: D](
eventType: Class[ET],
dataType: Class[DT],
predicate: TypedPredicate2[ET, DT],
apply: Apply2[ET, DT, State]): FSMStateFunctionBuilder[S, D] =
new FSMStateFunctionBuilder[S, D]().event(eventType, dataType, predicate, apply)
/**
@ -215,9 +218,10 @@ abstract class AbstractFSM[S, D] extends FSM[S, D] {
* @param apply an action to apply to the event and state data if there is a match
* @return the builder with the case statement added
*/
final def matchEvent[ET, DT <: D](eventType: Class[ET],
dataType: Class[DT],
apply: Apply2[ET, DT, State]): FSMStateFunctionBuilder[S, D] =
final def matchEvent[ET, DT <: D](
eventType: Class[ET],
dataType: Class[DT],
apply: Apply2[ET, DT, State]): FSMStateFunctionBuilder[S, D] =
new FSMStateFunctionBuilder[S, D]().event(eventType, dataType, apply)
/**
@ -230,9 +234,10 @@ abstract class AbstractFSM[S, D] extends FSM[S, D] {
* @param apply an action to apply to the event and state data if there is a match
* @return the builder with the case statement added
*/
final def matchEvent[ET](eventType: Class[ET],
predicate: TypedPredicate2[ET, D],
apply: Apply2[ET, D, State]): FSMStateFunctionBuilder[S, D] =
final def matchEvent[ET](
eventType: Class[ET],
predicate: TypedPredicate2[ET, D],
apply: Apply2[ET, D, State]): FSMStateFunctionBuilder[S, D] =
new FSMStateFunctionBuilder[S, D]().event(eventType, predicate, apply)
/**
@ -256,8 +261,9 @@ abstract class AbstractFSM[S, D] extends FSM[S, D] {
* @param apply an action to apply to the event and state data if there is a match
* @return the builder with the case statement added
*/
final def matchEvent(predicate: TypedPredicate2[AnyRef, D],
apply: Apply2[AnyRef, D, State]): FSMStateFunctionBuilder[S, D] =
final def matchEvent(
predicate: TypedPredicate2[AnyRef, D],
apply: Apply2[AnyRef, D, State]): FSMStateFunctionBuilder[S, D] =
new FSMStateFunctionBuilder[S, D]().event(predicate, apply)
/**
@ -271,9 +277,10 @@ abstract class AbstractFSM[S, D] extends FSM[S, D] {
* @param apply an action to apply to the event and state data if there is a match
* @return the builder with the case statement added
*/
final def matchEvent[DT <: D](eventMatches: JList[AnyRef],
dataType: Class[DT],
apply: Apply2[AnyRef, DT, State]): FSMStateFunctionBuilder[S, D] =
final def matchEvent[DT <: D](
eventMatches: JList[AnyRef],
dataType: Class[DT],
apply: Apply2[AnyRef, DT, State]): FSMStateFunctionBuilder[S, D] =
new FSMStateFunctionBuilder[S, D]().event(eventMatches, dataType, apply)
/**
@ -299,9 +306,10 @@ abstract class AbstractFSM[S, D] extends FSM[S, D] {
* @param apply an action to apply to the event and state data if there is a match
* @return the builder with the case statement added
*/
final def matchEventEquals[E, DT <: D](event: E,
dataType: Class[DT],
apply: Apply2[E, DT, State]): FSMStateFunctionBuilder[S, D] =
final def matchEventEquals[E, DT <: D](
event: E,
dataType: Class[DT],
apply: Apply2[E, DT, State]): FSMStateFunctionBuilder[S, D] =
new FSMStateFunctionBuilder[S, D]().eventEquals(event, dataType, apply)
/**
@ -387,9 +395,10 @@ abstract class AbstractFSM[S, D] extends FSM[S, D] {
* @param predicate a predicate that will be evaluated on the reason if the type matches
* @return the builder with the case statement added
*/
final def matchStop[RT <: Reason](reasonType: Class[RT],
predicate: TypedPredicate[RT],
apply: UnitApply3[RT, S, D]): FSMStopBuilder[S, D] =
final def matchStop[RT <: Reason](
reasonType: Class[RT],
predicate: TypedPredicate[RT],
apply: UnitApply3[RT, S, D]): FSMStopBuilder[S, D] =
new FSMStopBuilder[S, D]().stop(reasonType, predicate, apply)
/**
@ -410,9 +419,10 @@ abstract class AbstractFSM[S, D] extends FSM[S, D] {
* @param apply an action to apply to the argument if the type and predicate matches
* @return a builder with the case statement added
*/
final def matchData[DT <: D](dataType: Class[DT],
predicate: TypedPredicate[DT],
apply: UnitApply[DT]): UnitPFBuilder[D] =
final def matchData[DT <: D](
dataType: Class[DT],
predicate: TypedPredicate[DT],
apply: UnitApply[DT]): UnitPFBuilder[D] =
UnitMatch.`match`(dataType, predicate, apply)
/**

View file

@ -116,8 +116,9 @@ final case class ActorIdentity(correlationId: Any, ref: Option[ActorRef]) {
* that the remote node hosting the watched actor was detected as unreachable
*/
@SerialVersionUID(1L)
final case class Terminated private[akka] (@BeanProperty actor: ActorRef)(@BeanProperty val existenceConfirmed: Boolean,
@BeanProperty val addressTerminated: Boolean)
final case class Terminated private[akka] (@BeanProperty actor: ActorRef)(
@BeanProperty val existenceConfirmed: Boolean,
@BeanProperty val addressTerminated: Boolean)
extends AutoReceivedMessage
with PossiblyHarmful
with DeadLetterSuppression
@ -217,10 +218,11 @@ object ActorInitializationException {
* @param messageOption is the message which was optionally passed into preRestart()
*/
@SerialVersionUID(1L)
final case class PreRestartException private[akka] (actor: ActorRef,
cause: Throwable,
originalCause: Throwable,
messageOption: Option[Any])
final case class PreRestartException private[akka] (
actor: ActorRef,
cause: Throwable,
originalCause: Throwable,
messageOption: Option[Any])
extends ActorInitializationException(
actor,
"exception in preRestart(" +
@ -288,9 +290,10 @@ class ActorInterruptedException private[akka] (cause: Throwable) extends AkkaExc
* This message is published to the EventStream whenever an Actor receives a message it doesn't understand
*/
@SerialVersionUID(1L)
final case class UnhandledMessage(@BeanProperty message: Any,
@BeanProperty sender: ActorRef,
@BeanProperty recipient: ActorRef)
final case class UnhandledMessage(
@BeanProperty message: Any,
@BeanProperty sender: ActorRef,
@BeanProperty recipient: ActorRef)
extends NoSerializationVerificationNeeded
/**

View file

@ -706,9 +706,10 @@ private[akka] class ActorCell(
publish(Debug(self.path.toString, clazz(actor), "now supervising " + child))
case None =>
publish(
Error(self.path.toString,
clazz(actor),
"received Supervise from unregistered child " + child + ", this will not end well"))
Error(
self.path.toString,
clazz(actor),
"received Supervise from unregistered child " + child + ", this will not end well"))
}
}

View file

@ -257,9 +257,10 @@ sealed trait ActorPath extends Comparable[ActorPath] with Serializable {
*/
@SerialVersionUID(1L)
final case class RootActorPath(address: Address, name: String = "/") extends ActorPath {
require(name.length == 1 || name.indexOf('/', 1) == -1,
("/ may only exist at the beginning of the root actors name, " +
"it is a path separator and is not legal in ActorPath names: [%s]").format(name))
require(
name.length == 1 || name.indexOf('/', 1) == -1,
("/ may only exist at the beginning of the root actors name, " +
"it is a path separator and is not legal in ActorPath names: [%s]").format(name))
require(name.indexOf('#') == -1, "# is a fragment separator and is not legal in ActorPath names: [%s]".format(name))
override def parent: ActorPath = this
@ -393,10 +394,11 @@ final class ChildActorPath private[akka] (val parent: ActorPath, val name: Strin
* @param diff difference in offset for each child element, due to different address
* @param rootString function to construct the root element string
*/
private def buildToString(sb: JStringBuilder,
length: Int,
diff: Int,
rootString: RootActorPath => String): JStringBuilder = {
private def buildToString(
sb: JStringBuilder,
length: Int,
diff: Int,
rootString: RootActorPath => String): JStringBuilder = {
@tailrec
def rec(p: ActorPath): JStringBuilder = p match {
case r: RootActorPath =>

View file

@ -299,12 +299,13 @@ private[akka] case object Nobody extends MinimalActorRef {
*
* INTERNAL API
*/
private[akka] class LocalActorRef private[akka] (_system: ActorSystemImpl,
_props: Props,
_dispatcher: MessageDispatcher,
_mailboxType: MailboxType,
_supervisor: InternalActorRef,
override val path: ActorPath)
private[akka] class LocalActorRef private[akka] (
_system: ActorSystemImpl,
_props: Props,
_dispatcher: MessageDispatcher,
_mailboxType: MailboxType,
_supervisor: InternalActorRef,
override val path: ActorPath)
extends ActorRefWithCell
with LocalRef {
@ -321,11 +322,12 @@ private[akka] class LocalActorRef private[akka] (_system: ActorSystemImpl,
private val actorCell: ActorCell = newActorCell(_system, this, _props, _dispatcher, _supervisor)
actorCell.init(sendSupervise = true, _mailboxType)
protected def newActorCell(system: ActorSystemImpl,
ref: InternalActorRef,
props: Props,
dispatcher: MessageDispatcher,
supervisor: InternalActorRef): ActorCell =
protected def newActorCell(
system: ActorSystemImpl,
ref: InternalActorRef,
props: Props,
dispatcher: MessageDispatcher,
supervisor: InternalActorRef): ActorCell =
new ActorCell(system, ref, props, dispatcher, supervisor)
protected def actorContext: ActorContext = actorCell
@ -524,9 +526,10 @@ private[akka] object DeadLetterActorRef {
*
* INTERNAL API
*/
private[akka] class EmptyLocalActorRef(override val provider: ActorRefProvider,
override val path: ActorPath,
val eventStream: EventStream)
private[akka] class EmptyLocalActorRef(
override val provider: ActorRefProvider,
override val path: ActorPath,
val eventStream: EventStream)
extends MinimalActorRef {
@deprecated("Use context.watch(actor) and receive Terminated(actor)", "2.2")
@ -607,10 +610,11 @@ private[akka] class DeadLetterActorRef(_provider: ActorRefProvider, _path: Actor
*
* INTERNAL API
*/
private[akka] class VirtualPathContainer(override val provider: ActorRefProvider,
override val path: ActorPath,
override val getParent: InternalActorRef,
val log: MarkerLoggingAdapter)
private[akka] class VirtualPathContainer(
override val provider: ActorRefProvider,
override val path: ActorPath,
override val getParent: InternalActorRef,
val log: MarkerLoggingAdapter)
extends MinimalActorRef {
private val children = new ConcurrentHashMap[String, InternalActorRef]
@ -624,9 +628,10 @@ private[akka] class VirtualPathContainer(override val provider: ActorRefProvider
require(elements.nonEmpty)
def emptyRef =
new EmptyLocalActorRef(provider,
path / sel.elements.map(_.toString),
provider.systemGuardian.underlying.system.eventStream)
new EmptyLocalActorRef(
provider,
path / sel.elements.map(_.toString),
provider.systemGuardian.underlying.system.eventStream)
elements.head match {
case SelectChildName(name) =>
@ -717,10 +722,11 @@ private[akka] class VirtualPathContainer(override val provider: ActorRefProvider
* [[FunctionRef#unwatch]] must be called to avoid a resource leak, which is different
* from an ordinary actor.
*/
private[akka] final class FunctionRef(override val path: ActorPath,
override val provider: ActorRefProvider,
system: ActorSystem,
f: (ActorRef, Any) => Unit)
private[akka] final class FunctionRef(
override val path: ActorPath,
override val provider: ActorRefProvider,
system: ActorSystem,
f: (ActorRef, Any) => Unit)
extends MinimalActorRef {
override def !(message: Any)(implicit sender: ActorRef = Actor.noSender): Unit = {
@ -827,9 +833,10 @@ private[akka] final class FunctionRef(override val path: ActorPath,
}
} else if (!watcheeSelf && watcherSelf) {
publish(
Logging.Warning(path.toString,
classOf[FunctionRef],
s"externally triggered watch from $watcher to $watchee is illegal on FunctionRef"))
Logging.Warning(
path.toString,
classOf[FunctionRef],
s"externally triggered watch from $watcher to $watchee is illegal on FunctionRef"))
} else {
publish(
Logging.Error(path.toString, classOf[FunctionRef], s"BUG: illegal Watch($watchee,$watcher) for $this"))
@ -859,9 +866,10 @@ private[akka] final class FunctionRef(override val path: ActorPath,
}
} else if (!watcheeSelf && watcherSelf) {
publish(
Logging.Warning(path.toString,
classOf[FunctionRef],
s"externally triggered unwatch from $watcher to $watchee is illegal on FunctionRef"))
Logging.Warning(
path.toString,
classOf[FunctionRef],
s"externally triggered unwatch from $watcher to $watchee is illegal on FunctionRef"))
} else {
publish(
Logging.Error(path.toString, classOf[FunctionRef], s"BUG: illegal Unwatch($watchee,$watcher) for $this"))

View file

@ -111,14 +111,15 @@ import akka.util.OptionVal
* but it should be overridable from external configuration; the lookup of
* the latter can be suppressed by setting ``lookupDeploy`` to ``false``.
*/
private[akka] def actorOf(system: ActorSystemImpl,
props: Props,
supervisor: InternalActorRef,
path: ActorPath,
systemService: Boolean,
deploy: Option[Deploy],
lookupDeploy: Boolean,
async: Boolean): InternalActorRef
private[akka] def actorOf(
system: ActorSystemImpl,
props: Props,
supervisor: InternalActorRef,
path: ActorPath,
systemService: Boolean,
deploy: Option[Deploy],
lookupDeploy: Boolean,
async: Boolean): InternalActorRef
/**
* INTERNAL API
@ -475,19 +476,21 @@ private[akka] object LocalActorRefProvider {
*
* Depending on this class is not supported, only the [[ActorRefProvider]] interface is supported.
*/
private[akka] class LocalActorRefProvider private[akka] (_systemName: String,
override val settings: ActorSystem.Settings,
val eventStream: EventStream,
val dynamicAccess: DynamicAccess,
override val deployer: Deployer,
_deadLetters: Option[ActorPath => InternalActorRef])
private[akka] class LocalActorRefProvider private[akka] (
_systemName: String,
override val settings: ActorSystem.Settings,
val eventStream: EventStream,
val dynamicAccess: DynamicAccess,
override val deployer: Deployer,
_deadLetters: Option[ActorPath => InternalActorRef])
extends ActorRefProvider {
// this is the constructor needed for reflectively instantiating the provider
def this(_systemName: String,
settings: ActorSystem.Settings,
eventStream: EventStream,
dynamicAccess: DynamicAccess) =
def this(
_systemName: String,
settings: ActorSystem.Settings,
eventStream: EventStream,
dynamicAccess: DynamicAccess) =
this(_systemName, settings, eventStream, dynamicAccess, new Deployer(settings, dynamicAccess), None)
override val rootPath: ActorPath = RootActorPath(Address("akka", _systemName))
@ -605,12 +608,13 @@ private[akka] class LocalActorRefProvider private[akka] (_systemName: String,
private lazy val defaultMailbox = system.mailboxes.lookup(Mailboxes.DefaultMailboxId)
override lazy val rootGuardian: LocalActorRef =
new LocalActorRef(system,
Props(classOf[LocalActorRefProvider.Guardian], rootGuardianStrategy),
defaultDispatcher,
defaultMailbox,
theOneWhoWalksTheBubblesOfSpaceTime,
rootPath) {
new LocalActorRef(
system,
Props(classOf[LocalActorRefProvider.Guardian], rootGuardianStrategy),
defaultDispatcher,
defaultMailbox,
theOneWhoWalksTheBubblesOfSpaceTime,
rootPath) {
override def getParent: InternalActorRef = this
override def getSingleChild(name: String): InternalActorRef = name match {
case "temp" => tempContainer
@ -641,12 +645,13 @@ private[akka] class LocalActorRefProvider private[akka] (_systemName: String,
override lazy val systemGuardian: LocalActorRef = {
val cell = rootGuardian.underlying
cell.reserveChild("system")
val ref = new LocalActorRef(system,
Props(classOf[LocalActorRefProvider.SystemGuardian], systemGuardianStrategy, guardian),
defaultDispatcher,
defaultMailbox,
rootGuardian,
rootPath / "system")
val ref = new LocalActorRef(
system,
Props(classOf[LocalActorRefProvider.SystemGuardian], systemGuardianStrategy, guardian),
defaultDispatcher,
defaultMailbox,
rootGuardian,
rootPath / "system")
cell.initChild(ref)
ref.start()
ref
@ -718,9 +723,10 @@ private[akka] class LocalActorRefProvider private[akka] (_systemName: String,
def resolveActorRef(path: ActorPath): ActorRef = {
if (path.root == rootPath) resolveActorRef(rootGuardian, path.elements)
else {
log.debug("Resolve (deserialization) of foreign path [{}] doesn't match root path [{}], using deadLetters.",
path,
rootPath)
log.debug(
"Resolve (deserialization) of foreign path [{}] doesn't match root path [{}], using deadLetters.",
path,
rootPath)
deadLetters
}
}
@ -736,21 +742,23 @@ private[akka] class LocalActorRefProvider private[akka] (_systemName: String,
ref.getChild(pathElements.iterator) match {
case Nobody =>
if (log.isDebugEnabled)
log.debug("Resolve (deserialization) of path [{}] doesn't match an active actor. " +
"It has probably been stopped, using deadLetters.",
pathElements.mkString("/"))
log.debug(
"Resolve (deserialization) of path [{}] doesn't match an active actor. " +
"It has probably been stopped, using deadLetters.",
pathElements.mkString("/"))
new EmptyLocalActorRef(system.provider, ref.path / pathElements, eventStream)
case x => x
}
def actorOf(system: ActorSystemImpl,
props: Props,
supervisor: InternalActorRef,
path: ActorPath,
systemService: Boolean,
deploy: Option[Deploy],
lookupDeploy: Boolean,
async: Boolean): InternalActorRef = {
def actorOf(
system: ActorSystemImpl,
props: Props,
supervisor: InternalActorRef,
path: ActorPath,
systemService: Boolean,
deploy: Option[Deploy],
lookupDeploy: Boolean,
async: Boolean): InternalActorRef = {
props.deploy.routerConfig match {
case NoRouter =>
if (settings.DebugRouterMisconfiguration) {
@ -803,9 +811,10 @@ private[akka] class LocalActorRefProvider private[akka] (_systemName: String,
if (!system.dispatchers.hasDispatcher(r.routerDispatcher))
throw new ConfigurationException(s"Dispatcher [${p.dispatcher}] not configured for router of $path")
val routerProps = Props(p.deploy.copy(dispatcher = p.routerConfig.routerDispatcher),
classOf[RoutedActorCell.RouterActorCreator],
Vector(p.routerConfig))
val routerProps = Props(
p.deploy.copy(dispatcher = p.routerConfig.routerDispatcher),
classOf[RoutedActorCell.RouterActorCreator],
Vector(p.routerConfig))
val routeeProps = p.withRouter(NoRouter)
try {

View file

@ -43,9 +43,10 @@ abstract class ActorSelection extends Serializable {
* Pass [[ActorRef#noSender]] or `null` as sender if there is nobody to reply to
*/
def tell(msg: Any, sender: ActorRef): Unit =
ActorSelection.deliverSelection(anchor.asInstanceOf[InternalActorRef],
sender,
ActorSelectionMessage(msg, path, wildcardFanOut = false))
ActorSelection.deliverSelection(
anchor.asInstanceOf[InternalActorRef],
sender,
ActorSelectionMessage(msg, path, wildcardFanOut = false))
/**
* Forwards the message and passes the original sender actor as the sender.
@ -235,9 +236,10 @@ object ActorSelection {
ref match {
case refWithCell: ActorRefWithCell =>
def emptyRef =
new EmptyLocalActorRef(refWithCell.provider,
anchor.path / sel.elements.map(_.toString),
refWithCell.underlying.system.eventStream)
new EmptyLocalActorRef(
refWithCell.provider,
anchor.path / sel.elements.map(_.toString),
refWithCell.underlying.system.eventStream)
iter.next() match {
case SelectParent =>
@ -271,8 +273,9 @@ object ActorSelection {
if (matchingChildren.isEmpty && !sel.wildcardFanOut)
emptyRef.tell(sel, sender)
else {
val m = sel.copy(elements = iter.toVector,
wildcardFanOut = sel.wildcardFanOut || matchingChildren.size > 1)
val m = sel.copy(
elements = iter.toVector,
wildcardFanOut = sel.wildcardFanOut || matchingChildren.size > 1)
matchingChildren.foreach(c => deliverSelection(c.asInstanceOf[InternalActorRef], sender, m))
}
}
@ -305,9 +308,10 @@ trait ScalaActorSelection {
* message is delivered by traversing the various actor paths involved.
*/
@SerialVersionUID(2L) // it has protobuf serialization in akka-remote
private[akka] final case class ActorSelectionMessage(msg: Any,
elements: immutable.Iterable[SelectionPathElement],
wildcardFanOut: Boolean)
private[akka] final case class ActorSelectionMessage(
msg: Any,
elements: immutable.Iterable[SelectionPathElement],
wildcardFanOut: Boolean)
extends AutoReceivedMessage
with PossiblyHarmful {

Some files were not shown because too many files have changed in this diff Show more