Upgrade to Scala 2.13.5 (#30072)

This commit is contained in:
Johan Andrén 2021-03-30 20:57:23 +02:00 committed by GitHub
parent 846359919f
commit c5655a9ce6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
264 changed files with 1071 additions and 538 deletions

View file

@ -0,0 +1,2 @@
# 2 new methods, TestProbe is not for user extension
ProblemFilters.exclude[ReversedMissingMethodProblem]("akka.actor.testkit.typed.scaladsl.TestProbe.fishForMessagePF")

View file

@ -105,6 +105,7 @@ private[akka] final class TestProbeImpl[M](name: String, system: ActorSystem[_])
case x if x eq Duration.Undefined => duration
case x if !x.isFinite => throw new IllegalArgumentException("`end` cannot be infinite")
case f: FiniteDuration => f - now
case _ => throw new RuntimeException() // compiler exhaustiveness check pleaser
}
override def getRemainingOr(duration: JDuration): JDuration =
@ -266,9 +267,16 @@ private[akka] final class TestProbeImpl[M](name: String, system: ActorSystem[_])
override def fishForMessage(max: FiniteDuration, hint: String)(fisher: M => FishingOutcome): immutable.Seq[M] =
fishForMessage_internal(max.dilated, hint, fisher)
override def fishForMessagePF(max: FiniteDuration, hint: String)(
fisher: PartialFunction[M, FishingOutcome]): immutable.Seq[M] =
fishForMessage(max, hint)(fisher)
override def fishForMessage(max: FiniteDuration)(fisher: M => FishingOutcome): immutable.Seq[M] =
fishForMessage(max, "")(fisher)
override def fishForMessagePF(max: FiniteDuration)(fisher: PartialFunction[M, FishingOutcome]): immutable.Seq[M] =
fishForMessage(max)(fisher)
override def fishForMessage(max: JDuration, fisher: java.util.function.Function[M, FishingOutcome]): JList[M] =
fishForMessage(max, "", fisher)

View file

@ -198,11 +198,21 @@ object TestProbe {
*/
def fishForMessage(max: FiniteDuration, hint: String)(fisher: M => FishingOutcome): immutable.Seq[M]
/**
* Same as `fishForMessage` but accepting a partial function and failing for non-matches
*/
def fishForMessagePF(max: FiniteDuration, hint: String)(fisher: PartialFunction[M, FishingOutcome]): immutable.Seq[M]
/**
* Same as the other `fishForMessage` but with no hint
*/
def fishForMessage(max: FiniteDuration)(fisher: M => FishingOutcome): immutable.Seq[M]
/**
* Same as `fishForMessage` but with no hint, accepting a partial function and failing for non-matches
*/
def fishForMessagePF(max: FiniteDuration)(fisher: PartialFunction[M, FishingOutcome]): immutable.Seq[M]
/**
* Expect the given actor to be stopped or stop within the given timeout or
* throw an [[AssertionError]].

View file

@ -138,6 +138,8 @@ object BehaviorTestKitSpec {
case IsTimerActive(key, replyTo) =>
replyTo ! timers.isTimerActive(key)
Behaviors.same
case unexpected =>
throw new RuntimeException(s"Unexpected command: $unexpected")
}
}
.receiveSignal {

View file

@ -105,7 +105,7 @@ class TestProbeSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with
probe.ref ! "two"
intercept[AssertionError] {
probe.fishForMessage(shortDuration) {
probe.fishForMessagePF(shortDuration) {
case "one" => FishingOutcomes.continue
}
}
@ -117,7 +117,7 @@ class TestProbeSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with
probe.ref ! "one"
intercept[AssertionError] {
probe.fishForMessage(shortDuration) {
probe.fishForMessagePF(shortDuration) {
case "one" => FishingOutcomes.continue
}
}

View file

@ -51,6 +51,7 @@ class ActorSelectionSpec extends AkkaSpec with DefaultTimeout {
def empty(path: String) =
new EmptyLocalActorRef(sysImpl.provider, path match {
case RelativeActorPath(elems) => sysImpl.lookupRoot.path / elems
case _ => throw new RuntimeException()
}, system.eventStream)
val idProbe = TestProbe()
@ -79,6 +80,7 @@ class ActorSelectionSpec extends AkkaSpec with DefaultTimeout {
Await.result(node ? query, timeout.duration) match {
case ref: ActorRef => Some(ref)
case selection: ActorSelection => identify(selection)
case _ => throw new RuntimeException()
}
}
@ -365,8 +367,13 @@ class ActorSelectionSpec extends AkkaSpec with DefaultTimeout {
val probe = TestProbe()
system.actorSelection("/user/a/*").tell(Identify(1), probe.ref)
probe.receiveN(2).map { case ActorIdentity(1, r) => r }.toSet should ===(
Set[Option[ActorRef]](Some(b1), Some(b2)))
probe
.receiveN(2)
.map {
case ActorIdentity(1, r) => r
case _ => throw new IllegalArgumentException()
}
.toSet should ===(Set[Option[ActorRef]](Some(b1), Some(b2)))
probe.expectNoMessage()
system.actorSelection("/user/a/b1/*").tell(Identify(2), probe.ref)

View file

@ -94,6 +94,7 @@ object ActorSystemSpec {
TestKit.awaitCond(mbox.actor.actor != null, 1.second)
mbox.actor.actor match {
case FastActor(latch, _) => Await.ready(latch, 1.second)
case _ => throw new IllegalStateException()
}
}
ret

View file

@ -14,7 +14,7 @@ object Chameneos {
final case class MeetingCount(count: Int) extends ChameneosEvent
case object Exit extends ChameneosEvent
abstract class Colour
abstract sealed class Colour
case object RED extends Colour
case object YELLOW extends Colour
case object BLUE extends Colour

View file

@ -683,6 +683,7 @@ object SupervisorHierarchySpec {
if (depth > 0) {
l.underlying.children.foreach(getErrors(_, depth - 1))
}
case _ => throw new IllegalArgumentException()
}
}
@ -694,6 +695,7 @@ object SupervisorHierarchySpec {
case _ => errors :+= target -> ErrorLog("fetched", stateCache.get(target.path).log)
}
if (target != hierarchy) getErrorsUp(l.getParent)
case _ => throw new IllegalArgumentException()
}
}

View file

@ -212,6 +212,7 @@ object TypedActorSpec {
override def onReceive(msg: Any, sender: ActorRef): Unit = {
ensureContextAvailable(msg match {
case "pigdog" => sender ! "dogpig"
case _ =>
})
}
}

View file

@ -122,6 +122,7 @@ abstract class MailboxSpec extends AkkaSpec with BeforeAndAfterAll with BeforeAn
config match {
case BoundedMailbox(capacity, _) => aQueue.remainingCapacity should ===(capacity)
case UnboundedMailbox() => aQueue.remainingCapacity should ===(Int.MaxValue)
case _ => fail()
}
case _ =>
}
@ -187,6 +188,7 @@ class DefaultMailboxSpec extends MailboxSpec {
def factory = {
case u: UnboundedMailbox => u.create(None, None)
case b: BoundedMailbox => b.create(None, None)
case _ => throw new RuntimeException() // compiler exhaustiveness check pleaser
}
}
@ -197,6 +199,7 @@ class PriorityMailboxSpec extends MailboxSpec {
case UnboundedMailbox() => new UnboundedPriorityMailbox(comparator).create(None, None)
case BoundedMailbox(capacity, pushTimeOut) =>
new BoundedPriorityMailbox(comparator, capacity, pushTimeOut).create(None, None)
case _ => throw new RuntimeException() // compiler exhaustiveness check pleaser
}
}
@ -207,6 +210,7 @@ class StablePriorityMailboxSpec extends MailboxSpec {
case UnboundedMailbox() => new UnboundedStablePriorityMailbox(comparator).create(None, None)
case BoundedMailbox(capacity, pushTimeOut) =>
new BoundedStablePriorityMailbox(comparator, capacity, pushTimeOut).create(None, None)
case _ => throw new RuntimeException() // compiler exhaustiveness check pleaser
}
}
@ -216,6 +220,7 @@ class ControlAwareMailboxSpec extends MailboxSpec {
case UnboundedMailbox() => new UnboundedControlAwareMailbox().create(None, None)
case BoundedMailbox(capacity, pushTimeOut) =>
new BoundedControlAwareMailbox(capacity, pushTimeOut).create(None, None)
case _ => throw new RuntimeException() // compiler exhaustiveness check pleaser
}
}
@ -258,6 +263,7 @@ class SingleConsumerOnlyMailboxSpec extends MailboxSpec {
def factory = {
case _: UnboundedMailbox => SingleConsumerOnlyUnboundedMailbox().create(None, None)
case _ @BoundedMailbox(capacity, _) => NonBlockingBoundedMailbox(capacity).create(None, None)
case _ => throw new RuntimeException() // compiler exhaustiveness check pleaser
}
}

View file

@ -30,12 +30,14 @@ object PriorityDispatcherSpec {
extends UnboundedPriorityMailbox(PriorityGenerator({
case i: Int => i //Reverse order
case Result => Int.MaxValue
case _ => throw new RuntimeException() // compiler exhaustiveness check pleaser
}: Any => Int))
class Bounded(@unused settings: ActorSystem.Settings, @unused config: Config)
extends BoundedPriorityMailbox(PriorityGenerator({
case i: Int => i //Reverse order
case Result => Int.MaxValue
case _ => throw new RuntimeException() // compiler exhaustiveness check pleaser
}: Any => Int), 1000, 10 seconds)
}

View file

@ -30,6 +30,7 @@ object StablePriorityDispatcherSpec {
case i: Int if i <= 100 => i // Small integers have high priority
case _: Int => 101 // Don't care for other integers
case Result => Int.MaxValue
case _ => throw new RuntimeException() // compiler exhaustiveness check pleaser
}: Any => Int))
class Bounded(@unused settings: ActorSystem.Settings, @unused config: Config)
@ -37,6 +38,7 @@ object StablePriorityDispatcherSpec {
case i: Int if i <= 100 => i // Small integers have high priority
case _: Int => 101 // Don't care for other integers
case Result => Int.MaxValue
case _ => throw new RuntimeException() // compiler exhaustiveness check pleaser
}: Any => Int), 1000, 10 seconds)
}

View file

@ -6,7 +6,6 @@ package akka.io
import java.net.DatagramSocket
import java.net.InetSocketAddress
import akka.actor.ActorRef
import akka.io.Inet._
import akka.io.Udp._
@ -64,7 +63,9 @@ class UdpIntegrationSpec extends AkkaSpec("""
}
"be able to send several packet back and forth with binding" in {
val Seq(serverAddress, clientAddress) = temporaryServerAddresses(2, udp = true)
val addresses = temporaryServerAddresses(2, udp = true)
val serverAddress = addresses(0)
val clientAddress = addresses(1)
val server = bindUdp(serverAddress, testActor)
val client = bindUdp(clientAddress, testActor)
val data = ByteString("Fly little packet!")

View file

@ -37,7 +37,10 @@ class AsyncDnsManagerSpec extends AkkaSpec("""
"support ipv6" in {
dns ! Resolve("::1") // ::1 will short circuit the resolution
val Resolved("::1", Seq(AAAARecord("::1", Ttl.effectivelyForever, _)), Nil) = expectMsgType[Resolved]
expectMsgType[Resolved] match {
case Resolved("::1", Seq(AAAARecord("::1", Ttl.effectivelyForever, _)), Nil) =>
case other => fail(other.toString)
}
}
"support ipv6 also using the old protocol" in {

View file

@ -123,8 +123,9 @@ class AsyncDnsResolverSpec extends AkkaSpec("""
r ! Resolve(name)
dnsClient1.expectNoMessage(50.millis)
val answer = senderProbe.expectMsgType[Resolved]
val Seq(aaaaRecord) = answer.records.collect {
case r: AAAARecord => r
val aaaaRecord = answer.records match {
case Seq(r: AAAARecord) => r
case _ => throw new RuntimeException() // compiler exhaustiveness check pleaser
}
aaaaRecord.name should be("1:2:3:0:0:0:0:0")
aaaaRecord.ttl should be(Ttl.effectivelyForever)

View file

@ -113,7 +113,9 @@ class ConfiguredLocalRoutingSpec
r.underlying match {
case c: RoutedActorCell => c.routerConfig
case _: UnstartedCell => awaitCond(r.isStarted, 1 second, 10 millis); routerConfig(ref)
case _ => throw new IllegalArgumentException(s"Unexpected underlying cell ${r.underlying}")
}
case _ => throw new IllegalArgumentException(s"Unexpected actorref $ref")
}
def collectRouteePaths(probe: TestProbe, router: ActorRef, n: Int): immutable.Seq[ActorPath] = {

View file

@ -6,11 +6,8 @@ package akka.serialization
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CompletionStage
import scala.concurrent.Future
import com.typesafe.config.ConfigFactory
import akka.actor.ExtendedActorSystem
import akka.testkit.{ AkkaSpec, EventFilter }
@ -45,6 +42,7 @@ object AsyncSerializeSpec {
o match {
case Message1(msg) => Future.successful(msg.getBytes)
case Message2(msg) => Future.successful(msg.getBytes)
case _ => throw new IllegalArgumentException(s"Unknown type $o")
}
}
@ -52,6 +50,7 @@ object AsyncSerializeSpec {
manifest match {
case "1" => Future.successful(Message1(new String(bytes)))
case "2" => Future.successful(Message2(new String(bytes)))
case _ => throw new IllegalArgumentException(s"Unknown manifest $manifest")
}
}
@ -60,6 +59,7 @@ object AsyncSerializeSpec {
override def manifest(o: AnyRef): String = o match {
case _: Message1 => "1"
case _: Message2 => "2"
case _ => throw new IllegalArgumentException(s"Unknown type $o")
}
}
@ -69,6 +69,7 @@ object AsyncSerializeSpec {
o match {
case Message3(msg) => CompletableFuture.completedFuture(msg.getBytes)
case Message4(msg) => CompletableFuture.completedFuture(msg.getBytes)
case _ => throw new IllegalArgumentException(s"Unknown type $o")
}
}
@ -76,6 +77,7 @@ object AsyncSerializeSpec {
manifest match {
case "1" => CompletableFuture.completedFuture(Message3(new String(bytes)))
case "2" => CompletableFuture.completedFuture(Message4(new String(bytes)))
case _ => throw new IllegalArgumentException(s"Unknown manifest $manifest")
}
}
@ -84,6 +86,7 @@ object AsyncSerializeSpec {
override def manifest(o: AnyRef): String = o match {
case _: Message3 => "1"
case _: Message4 => "2"
case _ => throw new IllegalArgumentException(s"Unknown type $o")
}
}

View file

@ -621,7 +621,7 @@ trait CustomContainsMatcher {
(remainingTruth, remainingSequence) match {
case (_, Nil) => matchResult(true)
case (Nil, _) => matchResult(false)
case (x :: xs, y :: ys) if x.equals(y) => attemptMatch(xs, ys)
case (x :: xs, y :: ys) if x == y => attemptMatch(xs, ys)
case (_ :: xs, ys) => attemptMatch(xs, ys)
}

View file

@ -55,6 +55,7 @@ object InterceptSpec {
val wrapped = msg match {
case c: Command => InternalProtocol.WrappedCommand(c)
case r: ExternalResponse => InternalProtocol.WrappedExternalResponse(r)
case unexpected => throw new RuntimeException(s"Unexpected: $unexpected")
}
target(ctx, wrapped)
}
@ -63,7 +64,7 @@ object InterceptSpec {
def apply(probe: ActorRef[String]): Behavior[Command] = {
Behaviors
.intercept(() => new ProtocolTransformer)(Behaviors.receiveMessage[InternalProtocol] {
.intercept(() => new ProtocolTransformer)(Behaviors.receiveMessagePartial[InternalProtocol] {
case InternalProtocol.WrappedCommand(cmd) =>
probe ! cmd.s
Behaviors.same
@ -396,6 +397,7 @@ class InterceptSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with
signal match {
case PostStop =>
probe.ref ! "interceptor-post-stop"
case _ =>
}
target(ctx, signal)
}

View file

@ -38,7 +38,9 @@ class MailboxSelectorSpec extends ScalaTestWithActorTestKit("""
adapter.classicContext match {
case cell: ActorCell =>
cell.mailbox.messageQueue
case unexpected => throw new RuntimeException(s"Unexpected: $unexpected")
}
case unexpected => throw new RuntimeException(s"Unexpected: $unexpected")
}
replyTo ! mailbox

View file

@ -1195,6 +1195,7 @@ class SupervisionSpec extends ScalaTestWithActorTestKit("""
case "boom" =>
probe.ref ! context.self
Behaviors.stopped
case unexpected => throw new RuntimeException(s"Unexpected: $unexpected")
}
})
context.watch(child)
@ -1420,7 +1421,7 @@ class SupervisionSpec extends ScalaTestWithActorTestKit("""
Behaviors.stopped
} else {
stopInSetup.set(true)
Behaviors.receiveMessage {
Behaviors.receiveMessagePartial {
case "boom" => throw TestException("boom")
}
}

View file

@ -21,10 +21,12 @@ class TerminatedSpec extends AnyWordSpec with Matchers with LogCapturing {
(childFailed match {
case Terminated(r) => r
case unexpected => throw new RuntimeException(s"Unexpected: $unexpected")
}) shouldEqual probe.ref
(childFailed match {
case ChildFailed(ref, e) => (ref, e)
case unexpected => throw new RuntimeException(s"Unexpected: $unexpected")
}) shouldEqual ((probe.ref, ex))
}

View file

@ -19,7 +19,7 @@ import akka.testkit.TestProbe
object ProbedBehavior {
def behavior(probe: u.ActorRef): Behavior[String] = {
Behaviors
.receiveMessage[String] {
.receiveMessagePartial[String] {
case "throw" => throw TestException("oh dear")
}
.receiveSignal {

View file

@ -5,14 +5,11 @@
package akka.actor.typed.delivery
import java.nio.charset.StandardCharsets
import scala.concurrent.duration.Duration
import scala.concurrent.duration.FiniteDuration
import scala.concurrent.duration._
import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory
import akka.actor.typed.ActorRef
import akka.actor.typed.Behavior
import akka.actor.typed.delivery.ConsumerController.SequencedMessage
@ -21,6 +18,8 @@ import akka.actor.typed.scaladsl.ActorContext
import akka.actor.typed.scaladsl.Behaviors
import akka.serialization.SerializerWithStringManifest
import java.io.NotSerializableException
object TestConsumer {
final case class Job(payload: String)
@ -140,6 +139,7 @@ class TestSerializer extends SerializerWithStringManifest {
override def toBinary(o: AnyRef): Array[Byte] =
o match {
case TestConsumer.Job(payload) => payload.getBytes(StandardCharsets.UTF_8)
case unexpected => throw new NotSerializableException(s"Unexpected: $unexpected")
}
override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef =

View file

@ -55,7 +55,7 @@ class TestDurableProducerQueue[A](
private def active(state: State[A]): Behavior[Command[A]] = {
stateHolder.set(state)
Behaviors.receiveMessage {
Behaviors.receiveMessagePartial {
case cmd: LoadState[A] @unchecked =>
maybeFail(cmd)
if (delay == Duration.Zero) cmd.replyTo ! state else context.scheduleOnce(delay, cmd.replyTo, state)

View file

@ -15,7 +15,7 @@ import akka.actor.typed.scaladsl.Behaviors
object TestProducer {
trait Command
sealed trait Command
final case class RequestNext(sendTo: ActorRef[TestConsumer.Job]) extends Command
private case object Tick extends Command
@ -62,14 +62,12 @@ object TestProducer {
}
private def activeNoDelay(n: Int): Behavior[Command] = {
Behaviors.receive { (ctx, msg) =>
msg match {
case RequestNext(sendTo) =>
Behaviors.receivePartial {
case (ctx, RequestNext(sendTo)) =>
sendMessage(n, sendTo, ctx)
activeNoDelay(n + 1)
}
}
}
private def sendMessage(n: Int, sendTo: ActorRef[TestConsumer.Job], ctx: ActorContext[Command]): Unit = {
val msg = s"msg-$n"

View file

@ -43,27 +43,24 @@ object TestProducerWithAsk {
}
private def idle(n: Int, replyProbe: ActorRef[Long]): Behavior[Command] = {
Behaviors.receive { (ctx, msg) =>
msg match {
case Tick => Behaviors.same
case RequestNext(sendTo) => active(n + 1, replyProbe, sendTo)
case Confirmed(seqNr) =>
Behaviors.receivePartial {
case (_, Tick) => Behaviors.same
case (_, RequestNext(sendTo)) => active(n + 1, replyProbe, sendTo)
case (_, Confirmed(seqNr)) =>
replyProbe ! seqNr
Behaviors.same
case AskTimeout =>
case (ctx, AskTimeout) =>
ctx.log.warn("Timeout")
Behaviors.same
}
}
}
private def active(
n: Int,
replyProbe: ActorRef[Long],
sendTo: ActorRef[ProducerController.MessageWithConfirmation[TestConsumer.Job]]): Behavior[Command] = {
Behaviors.receive { (ctx, msg) =>
msg match {
case Tick =>
Behaviors.receivePartial {
case (ctx, Tick) =>
val msg = s"msg-$n"
ctx.log.info("sent {}", msg)
ctx.ask(
@ -75,19 +72,19 @@ object TestProducerWithAsk {
}
idle(n, replyProbe)
case RequestNext(_) =>
case (_, RequestNext(_)) =>
throw new IllegalStateException("Unexpected RequestNext, already got one.")
case Confirmed(seqNr) =>
case (ctx, Confirmed(seqNr)) =>
ctx.log.info("Reply Confirmed [{}]", seqNr)
replyProbe ! seqNr
Behaviors.same
case AskTimeout =>
case (ctx, AskTimeout) =>
ctx.log.warn("Timeout")
Behaviors.same
}
}
}
}

View file

@ -33,25 +33,23 @@ object TestProducerWorkPulling {
}
private def idle(n: Int): Behavior[Command] = {
Behaviors.receiveMessage {
Behaviors.receiveMessagePartial {
case Tick => Behaviors.same
case RequestNext(sendTo) => active(n + 1, sendTo)
}
}
private def active(n: Int, sendTo: ActorRef[TestConsumer.Job]): Behavior[Command] = {
Behaviors.receive { (ctx, msg) =>
msg match {
case Tick =>
Behaviors.receivePartial {
case (ctx, Tick) =>
val msg = s"msg-$n"
ctx.log.info("sent {}", msg)
sendTo ! TestConsumer.Job(msg)
idle(n)
case RequestNext(_) =>
case (_, RequestNext(_)) =>
throw new IllegalStateException("Unexpected RequestNext, already got one.")
}
}
}
}

View file

@ -86,6 +86,7 @@ class AdaptationFailureSpec extends ScalaTestWithActorTestKit with AnyWordSpecLi
case (_, Terminated(`ref`)) =>
probe.ref ! "actor-stopped"
Behaviors.same
case _ => Behaviors.unhandled
}
})

View file

@ -68,7 +68,7 @@ object ReceptionistApiSpec {
// to cover as much of the API as possible
context.system.receptionist ! Receptionist.Register(key, context.self.narrow, context.self.narrow)
Behaviors.receiveMessage {
Behaviors.receiveMessagePartial {
case key.Listing(services) =>
services.foreach(_ ! "woho")
Behaviors.same

View file

@ -79,12 +79,11 @@ class ActorContextAskSpec
case class Ping(respondTo: ActorRef[Pong.type]) extends Protocol
case object Pong extends Protocol
val pingPong = spawn(Behaviors.receive[Protocol]((_, message) =>
message match {
val pingPong = spawn(Behaviors.receiveMessagePartial[Protocol] {
case Ping(respondTo) =>
respondTo ! Pong
Behaviors.same
}))
})
val snitch = Behaviors.setup[AnyRef] { context =>
context.ask(pingPong, Ping) {
@ -93,7 +92,7 @@ class ActorContextAskSpec
}
Behaviors
.receive[AnyRef] {
.receivePartial[AnyRef] {
case (_, message) =>
probe.ref ! message
Behaviors.same

View file

@ -93,7 +93,7 @@ class MessageAdapterSpec
case class Wrapped(qualifier: String, response: Response)
val pingPong = spawn(Behaviors.receiveMessage[Ping] {
val pingPong = spawn(Behaviors.receiveMessagePartial[Ping] {
case Ping1(sender) =>
sender ! Pong1("hello-1")
Behaviors.same
@ -131,10 +131,10 @@ class MessageAdapterSpec
}
"not break if wrong/unknown response type" in {
trait Ping
sealed trait Ping
case class Ping1(sender: ActorRef[Pong1]) extends Ping
case class Ping2(sender: ActorRef[Pong2]) extends Ping
trait Response
sealed trait Response
case class Pong1(greeting: String) extends Response
case class Pong2(greeting: String) extends Response

View file

@ -39,7 +39,7 @@ final class OnSignalSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike
}, s"$i")
}
Behaviors
.receiveMessage[String] {
.receiveMessagePartial[String] {
case "stop" =>
Behaviors.stopped
}

View file

@ -119,7 +119,7 @@ class RoutersSpec extends ScalaTestWithActorTestKit("""
case object BCast extends Cmd
def behavior(replyTo: ActorRef[AnyRef]) = Behaviors.setup[Cmd] { ctx =>
Behaviors.receiveMessage[Cmd] {
Behaviors.receiveMessagePartial[Cmd] {
case ReplyWithAck | BCast =>
val reply = ctx.self.path
replyTo ! reply

View file

@ -299,7 +299,7 @@ class UnstashingSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with
Behaviors.same
}
Behaviors.receiveMessage[String] {
Behaviors.receiveMessagePartial[String] {
case msg if msg.startsWith("stash") =>
stash.stash(msg)
Behaviors.same
@ -635,14 +635,14 @@ class UnstashingSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with
stash.stash("handled")
def unstashing(n: Int): Behavior[String] =
Behaviors.receiveMessage {
Behaviors.receiveMessagePartial {
case "unhandled" => Behaviors.unhandled
case "handled" =>
probe.ref ! s"handled $n"
unstashing(n + 1)
}
Behaviors.receiveMessage {
Behaviors.receiveMessagePartial {
case "unstash" =>
stash.unstashAll(unstashing(1))
}
@ -665,7 +665,7 @@ class UnstashingSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with
val ref = spawn(Behaviors.withStash[String](10) { stash =>
stash.stash("one")
Behaviors.receiveMessage {
Behaviors.receiveMessagePartial {
case "unstash" =>
stash.unstashAll(Behaviors.stopped)
}
@ -683,7 +683,7 @@ class UnstashingSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with
stash.stash("one")
stash.stash("two")
Behaviors.receiveMessage {
Behaviors.receiveMessagePartial {
case "unstash" =>
stash.unstashAll(Behaviors.receiveMessage { unstashed =>
probe.ref ! unstashed

View file

@ -32,7 +32,7 @@ class StopSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with LogCa
"execute the post stop" in {
val probe = TestProbe[Done]()
val ref = spawn(Behaviors.receiveMessage[String] {
val ref = spawn(Behaviors.receiveMessagePartial[String] {
case "stop" =>
Behaviors.stopped { () =>
probe.ref ! Done
@ -46,7 +46,7 @@ class StopSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike with LogCa
val probe = TestProbe[String]()
val ref = spawn(
Behaviors
.receiveMessage[String] {
.receiveMessagePartial[String] {
case "stop" =>
Behaviors.stopped { () =>
probe.ref ! "callback"

View file

@ -32,8 +32,8 @@ object Aggregator {
def collecting(replies: immutable.IndexedSeq[Reply]): Behavior[Command] = {
Behaviors.receiveMessage {
case WrappedReply(reply: Reply) =>
val newReplies = replies :+ reply
case WrappedReply(reply) =>
val newReplies = replies :+ reply.asInstanceOf[Reply]
if (newReplies.size == expectedReplies) {
val result = aggregateReplies(newReplies)
replyTo ! result

View file

@ -51,6 +51,7 @@ object AggregatorSpec {
.map {
case Hotel1.Quote(hotel, price) => Quote(hotel, price)
case Hotel2.Price(hotel, price) => Quote(hotel, price)
case unknown => throw new RuntimeException(s"Unknown reply $unknown")
}
.sortBy(_.price)
.toList),

View file

@ -145,7 +145,7 @@ object IntroSpec {
final case class SessionDenied(reason: String) extends SessionEvent
final case class MessagePosted(screenName: String, message: String) extends SessionEvent
trait SessionCommand
sealed trait SessionCommand
final case class PostMessage(message: String) extends SessionCommand
private final case class NotifyClient(message: MessagePosted) extends SessionCommand
//#chatroom-protocol

View file

@ -39,7 +39,7 @@ object OOIntroSpec {
final case class SessionDenied(reason: String) extends SessionEvent
final case class MessagePosted(screenName: String, message: String) extends SessionEvent
trait SessionCommand
sealed trait SessionCommand
final case class PostMessage(message: String) extends SessionCommand
private final case class NotifyClient(message: MessagePosted) extends SessionCommand
//#chatroom-protocol
@ -84,7 +84,7 @@ object OOIntroSpec {
client: ActorRef[SessionEvent])
extends AbstractBehavior[SessionCommand](context) {
override def onMessage(msg: SessionCommand): Behavior[SessionCommand] = {
override def onMessage(msg: SessionCommand): Behavior[SessionCommand] =
msg match {
case PostMessage(message) =>
// from client, publish to others via the room
@ -96,7 +96,6 @@ object OOIntroSpec {
Behaviors.same
}
}
}
//#chatroom-protocol
}
//#chatroom-protocol

View file

@ -471,7 +471,8 @@ object StyleGuideDocExamples {
private def counterWithGuard(remaining: Int): Behavior[Command] = {
//#pattern-match-guard
// no exhaustiveness check because of guard condition
Behaviors.receiveMessage {
// FIXME not true anymore since Scala 2.13.5
Behaviors.receiveMessagePartial {
case Down if remaining == 1 =>
notifyWhenZero.tell(Done)
zero

View file

@ -31,8 +31,8 @@ object TailChopping {
def waiting(requestCount: Int): Behavior[Command] = {
Behaviors.receiveMessage {
case WrappedReply(reply: Reply) =>
replyTo ! reply
case WrappedReply(reply) =>
replyTo ! reply.asInstanceOf[Reply]
Behaviors.stopped
case RequestTimeout =>

View file

@ -0,0 +1,2 @@
# Java API with classtag so have likely not been used from Java
ProblemFilters.exclude[DirectMissingMethodProblem]("akka.actor.typed.delivery.WorkPullingProducerController.apply")

View file

@ -237,7 +237,7 @@ object WorkPullingProducerController {
/**
* Java API
*/
def apply[A: ClassTag](
def apply[A](
messageClass: Class[A],
producerId: String,
workerServiceKey: ServiceKey[ConsumerController.Command[A]],

View file

@ -193,7 +193,7 @@ object ProducerControllerImpl {
.narrow
}
private def askLoadState[A: ClassTag](
private def askLoadState[A](
context: ActorContext[InternalCommand],
durableQueueBehavior: Option[Behavior[DurableProducerQueue.Command[A]]],
settings: ProducerController.Settings): Option[ActorRef[DurableProducerQueue.Command[A]]] = {
@ -206,7 +206,7 @@ object ProducerControllerImpl {
}
}
private def askLoadState[A: ClassTag](
private def askLoadState[A](
context: ActorContext[InternalCommand],
durableQueue: Option[ActorRef[DurableProducerQueue.Command[A]]],
settings: ProducerController.Settings,
@ -222,11 +222,11 @@ object ProducerControllerImpl {
}
}
private def createInitialState[A: ClassTag](hasDurableQueue: Boolean) = {
private def createInitialState[A](hasDurableQueue: Boolean) = {
if (hasDurableQueue) None else Some(DurableProducerQueue.State.empty[A])
}
private def createState[A: ClassTag](
private def createState[A](
self: ActorRef[InternalCommand],
producerId: String,
send: SequencedMessage[A] => Unit,
@ -825,6 +825,9 @@ private class ProducerControllerImpl[A: ClassTag](
case DurableQueueTerminated =>
throw new IllegalStateException("DurableQueue was unexpectedly terminated.")
case unexpected =>
throw new RuntimeException(s"Unexpected message: $unexpected")
}
}

View file

@ -140,7 +140,7 @@ import akka.util.Timeout
.narrow
}
private def createInitialState[A: ClassTag](hasDurableQueue: Boolean) = {
private def createInitialState[A](hasDurableQueue: Boolean) = {
if (hasDurableQueue) None else Some(DurableProducerQueue.State.empty[A])
}
@ -158,6 +158,7 @@ import akka.util.Timeout
s.unconfirmed.foreach {
case DurableProducerQueue.MessageSent(oldSeqNr, msg, _, oldConfirmationQualifier, _) =>
context.self ! ResendDurableMsg(msg, oldConfirmationQualifier, oldSeqNr)
case _ => // please compiler exhaustiveness check
}
val msgAdapter: ActorRef[A] = context.messageAdapter(msg => Msg(msg, wasStashed = false, replyTo = None))
@ -220,12 +221,12 @@ import akka.util.Timeout
}
}
private def checkStashFull[A: ClassTag](stashBuffer: StashBuffer[InternalCommand]): Unit = {
private def checkStashFull[A](stashBuffer: StashBuffer[InternalCommand]): Unit = {
if (stashBuffer.isFull)
throw new IllegalArgumentException(s"Buffer is full, size [${stashBuffer.size}].")
}
private def askLoadState[A: ClassTag](
private def askLoadState[A](
context: ActorContext[InternalCommand],
durableQueueBehavior: Option[Behavior[DurableProducerQueue.Command[A]]],
settings: WorkPullingProducerController.Settings): Option[ActorRef[DurableProducerQueue.Command[A]]] = {
@ -238,7 +239,7 @@ import akka.util.Timeout
}
}
private def askLoadState[A: ClassTag](
private def askLoadState[A](
context: ActorContext[InternalCommand],
durableQueue: Option[ActorRef[DurableProducerQueue.Command[A]]],
settings: WorkPullingProducerController.Settings,
@ -658,6 +659,8 @@ private class WorkPullingProducerControllerImpl[A: ClassTag](
case DurableQueueTerminated =>
throw new IllegalStateException("DurableQueue was unexpectedly terminated.")
case unexpected =>
throw new RuntimeException(s"Unexpected message: $unexpected")
}
}

View file

@ -105,7 +105,7 @@ import scala.util.Success
// context-shared timer needed to allow for nested timer usage
def timer: TimerSchedulerCrossDslSupport[T] = _timer match {
case OptionVal.Some(timer) => timer
case OptionVal.None =>
case _ =>
checkCurrentActorThread()
val timer = mkTimer()
_timer = OptionVal.Some(timer)
@ -152,7 +152,7 @@ import scala.util.Success
// lazy init of logging setup
_logging match {
case OptionVal.Some(l) => l
case OptionVal.None =>
case _ =>
val logClass = LoggerClass.detectLoggerClassFromStack(classOf[Behavior[_]])
val logger = LoggerFactory.getLogger(logClass.getName)
val l = LoggingContext(logger, classicActorContext.props.deploy.tags, this)
@ -216,6 +216,7 @@ import scala.util.Success
case Success(StatusReply.Success(t: Res)) => mapResponse(Success(t))
case Success(StatusReply.Error(why)) => mapResponse(Failure(why))
case fail: Failure[_] => mapResponse(fail.asInstanceOf[Failure[Res]])
case _ => throw new RuntimeException() // won't happen, compiler exhaustiveness check pleaser
}
// Java API impl
@ -247,6 +248,7 @@ import scala.util.Success
case StatusReply.Success(value: Res) => applyToResponse(value, null)
case StatusReply.Error(why) => applyToResponse(null.asInstanceOf[Res], why)
case null => applyToResponse(null.asInstanceOf[Res], failure)
case _ => throw new RuntimeException() // won't happen, compiler exhaustiveness check pleaser
})
}
@ -295,7 +297,7 @@ import scala.util.Success
_messageAdapters.filterNot { case (cls, _) => cls == boxedMessageClass }
val ref = messageAdapterRef match {
case OptionVal.Some(ref) => ref.asInstanceOf[ActorRef[U]]
case OptionVal.None =>
case _ =>
// AdaptMessage is not really a T, but that is erased
val ref =
internalSpawnMessageAdapter[Any](msg => AdaptWithRegisteredMessageAdapter(msg).asInstanceOf[T], "adapter")
@ -315,12 +317,12 @@ import scala.util.Success
*/
@InternalApi private[akka] def setCurrentActorThread(): Unit = {
_currentActorThread match {
case OptionVal.None =>
_currentActorThread = OptionVal.Some(Thread.currentThread())
case OptionVal.Some(t) =>
throw new IllegalStateException(
s"Invalid access by thread from the outside of $self. " +
s"Current message is processed by $t, but also accessed from ${Thread.currentThread()}.")
case _ =>
_currentActorThread = OptionVal.Some(Thread.currentThread())
}
}
@ -343,7 +345,7 @@ import scala.util.Success
s"Unsupported access to ActorContext operation from the outside of $self. " +
s"Current message is processed by $t, but ActorContext was called from $callerThread.")
}
case OptionVal.None =>
case _ =>
throw new UnsupportedOperationException(
s"Unsupported access to ActorContext from the outside of $self. " +
s"No message is currently processed by the actor, but ActorContext was called from $callerThread.")

View file

@ -97,7 +97,7 @@ private[akka] object BehaviorTags {
def onPostStop(ctx: TypedActorContext[T]): Unit = {
postStop match {
case OptionVal.Some(callback) => callback(ctx)
case OptionVal.None =>
case _ =>
}
}

View file

@ -92,7 +92,8 @@ private[akka] trait ExtensionsImpl extends Extensions { self: ActorSystem[_] wit
.getOrElse(ext.createExtension(self))
instance match {
case null => throw new IllegalStateException(s"Extension instance created as 'null' for extension [$ext]")
case instance: T @unchecked =>
case nonNull =>
val instance = nonNull.asInstanceOf[T]
// Replace our in process signal with the initialized extension
extensions.replace(ext, inProcessOfRegistration, instance)
instance

View file

@ -219,8 +219,8 @@ import java.util.function.Predicate
throw new IllegalArgumentException("Cannot unstash with unhandled as starting behavior")
else if (started == BehaviorImpl.same) {
currentBehaviorWhenUnstashInProgress match {
case OptionVal.None => ctx.asScala.currentBehavior
case OptionVal.Some(c) => c
case _ => ctx.asScala.currentBehavior
}
} else started

View file

@ -193,14 +193,12 @@ private class RestartSupervisor[T, Thr <: Throwable: ClassTag](initial: Behavior
private var deadline: OptionVal[Deadline] = OptionVal.None
private def deadlineHasTimeLeft: Boolean = deadline match {
case OptionVal.None => true
case OptionVal.Some(d) => d.hasTimeLeft()
case _ => true
}
override def aroundSignal(ctx: TypedActorContext[Any], signal: Signal, target: SignalTarget[T]): Behavior[T] = {
restartingInProgress match {
case OptionVal.None =>
super.aroundSignal(ctx, signal, target)
case OptionVal.Some((stashBuffer, children)) =>
signal match {
case Terminated(ref) if strategy.stopChildren && children(ref) =>
@ -219,6 +217,8 @@ private class RestartSupervisor[T, Thr <: Throwable: ClassTag](initial: Behavior
stashBuffer.stash(signal)
Behaviors.same
}
case _ =>
super.aroundSignal(ctx, signal, target)
}
}
@ -235,7 +235,7 @@ private class RestartSupervisor[T, Thr <: Throwable: ClassTag](initial: Behavior
} else
restartCompleted(ctx)
case OptionVal.None =>
case _ =>
throw new IllegalStateException("Unexpected ScheduledRestart when restart not in progress")
}
} else {
@ -254,18 +254,19 @@ private class RestartSupervisor[T, Thr <: Throwable: ClassTag](initial: Behavior
target(ctx, msg.asInstanceOf[T])
}
case m: T @unchecked =>
case msg =>
val m = msg.asInstanceOf[T]
restartingInProgress match {
case OptionVal.None =>
try {
target(ctx, m)
} catch handleReceiveException(ctx, target)
case OptionVal.Some((stashBuffer, _)) =>
if (stashBuffer.isFull)
dropped(ctx, m)
else
stashBuffer.stash(m)
Behaviors.same
case _ =>
try {
target(ctx, m)
} catch handleReceiveException(ctx, target)
}
}
}
@ -371,10 +372,10 @@ private class RestartSupervisor[T, Thr <: Throwable: ClassTag](initial: Behavior
try {
val newBehavior = Behavior.validateAsInitial(Behavior.start(initial, ctx.asInstanceOf[TypedActorContext[T]]))
val nextBehavior = restartingInProgress match {
case OptionVal.None => newBehavior
case OptionVal.Some((stashBuffer, _)) =>
restartingInProgress = OptionVal.None
stashBuffer.unstashAll(newBehavior.unsafeCast)
case _ => newBehavior
}
nextBehavior.narrow
} catch handleException(ctx, signalRestart = {

View file

@ -102,8 +102,9 @@ import akka.util.OptionVal
adaptAndHandle(msg)
case signal: Signal =>
handleSignal(signal)
case msg: T @unchecked =>
handleMessage(msg)
case msg =>
val t = msg.asInstanceOf[T]
handleMessage(t)
}
} finally {
ctx.clearCurrentActorThread()
@ -119,9 +120,9 @@ import akka.util.OptionVal
case timerMsg: TimerMsg =>
//we can only get this kind of message if the timer is of this concrete class
c.timer.asInstanceOf[TimerSchedulerImpl[T]].interceptTimerMsg(ctx.log, timerMsg) match {
case OptionVal.None => // means TimerMsg not applicable, discard
case OptionVal.Some(m) =>
next(Behavior.interpretMessage(behavior, c, m), m)
case _ => // means TimerMsg not applicable, discard
}
case _ =>
next(Behavior.interpretMessage(behavior, c, msg), msg)

View file

@ -88,6 +88,7 @@ import akka.annotation.InternalApi
case DispatcherDefault(_) => system.dispatcher
case DispatcherFromConfig(str, _) => system.dispatchers.lookup(str)
case DispatcherSameAsParent(_) => system.dispatcher
case unknown => throw new RuntimeException(s"Unsupported dispatcher selector: $unknown")
}
override def shutdown(): Unit = () // there was no shutdown in classic Akka
}

View file

@ -25,6 +25,7 @@ import akka.dispatch.Mailboxes
case _: DispatcherDefault => classicProps
case DispatcherFromConfig(name, _) => classicProps.withDispatcher(name)
case _: DispatcherSameAsParent => classicProps.withDispatcher(Deploy.DispatcherSameAsParent)
case unknown => throw new RuntimeException(s"Unsupported dispatcher selector: $unknown")
}).withDeploy(Deploy.local) // disallow remote deployment for typed actors
val mailboxProps = props.firstOrElse[MailboxSelector](MailboxSelector.default()) match {
@ -34,6 +35,7 @@ import akka.dispatch.Mailboxes
dispatcherProps.withMailbox(s"${Mailboxes.BoundedCapacityPrefix}$capacity")
case MailboxFromConfigSelector(path, _) =>
dispatcherProps.withMailbox(path)
case unknown => throw new RuntimeException(s"Unsupported mailbox selector: $unknown")
}
val localDeploy = mailboxProps.withDeploy(Deploy.local) // disallow remote deployment for typed actors

View file

@ -69,6 +69,7 @@ private[akka] final class TopicImpl[T](topicName: String, context: ActorContext[
private val receptionist = context.system.receptionist
private val receptionistAdapter = context.messageAdapter[Receptionist.Listing] {
case topicServiceKey.Listing(topics) => TopicInstancesUpdated(topics)
case _ => throw new IllegalArgumentException() // FIXME exhaustiveness check fails on receptionist listing match
}
receptionist ! Receptionist.Subscribe(topicServiceKey, receptionistAdapter)
@ -139,5 +140,9 @@ private[akka] final class TopicImpl[T](topicName: String, context: ActorContext[
case GetTopicStats(replyTo) =>
replyTo ! TopicStats(localSubscribers.size, topicInstances.size)
this
case other =>
// can't do exhaustiveness check correctly because of protocol internal/public design
throw new IllegalArgumentException(s"Unexpected command type ${other.getClass}")
}
}

View file

@ -218,6 +218,10 @@ private[akka] object LocalReceptionist extends ReceptionistBehaviorProvider {
replyWithListing(key, subscriber)
behavior(state.subscriberAdded(key)(subscriber))
case other =>
// compiler does not know about our division into public and internal commands
throw new IllegalArgumentException(s"Unexpected command type ${other.getClass}")
}
def onInternal(ctx: ActorContext[Any], cmd: InternalCommand): Behavior[Any] = cmd match {

View file

@ -41,11 +41,11 @@ abstract class AbstractBehavior[T](context: ActorContext[T]) extends ExtensibleB
private var _receive: OptionVal[Receive[T]] = OptionVal.None
private def receive: Receive[T] = _receive match {
case OptionVal.None =>
case OptionVal.Some(r) => r
case _ =>
val receive = createReceive
_receive = OptionVal.Some(receive)
receive
case OptionVal.Some(r) => r
}
protected def getContext: ActorContext[T] = context

View file

@ -82,7 +82,7 @@ final class BehaviorBuilder[T] private (messageHandlers: List[Case[T, T]], signa
def onMessageEquals(msg: T, handler: Creator[Behavior[T]]): BehaviorBuilder[T] =
withMessage[T](
OptionVal.Some(msg.getClass.asInstanceOf[Class[T]]),
OptionVal.Some(_.equals(msg)),
OptionVal.Some(_ == msg),
(_: T) => handler.create())
/**

View file

@ -5,15 +5,15 @@
package akka.util
import java.nio.{ ByteBuffer, ByteOrder }
import scala.annotation.tailrec
import scala.collection.BufferedIterator
import scala.collection.LinearSeq
import scala.collection.mutable.ListBuffer
import scala.reflect.ClassTag
import akka.util.Collections.EmptyImmutableSeq
import scala.annotation.nowarn
object ByteIterator {
object ByteArrayIterator {
@ -48,24 +48,25 @@ object ByteIterator {
final override def size: Int = { val l = len; clear(); l }
final override def ++(that: IterableOnce[Byte]): ByteIterator = that match {
case that: ByteIterator =>
if (that.isEmpty) this
else if (this.isEmpty) that
case byteIterator: ByteIterator =>
if (byteIterator.isEmpty) this
else if (this.isEmpty) byteIterator
else
that match {
case that: ByteArrayIterator =>
if ((this.array eq that.array) && (this.until == that.from)) {
this.until = that.until
that.clear()
byteIterator match {
case bai: ByteArrayIterator =>
if ((this.array eq bai.array) && (this.until == bai.from)) {
this.until = bai.until
bai.clear()
this
} else {
val result = MultiByteArrayIterator(List(this, that))
val result = MultiByteArrayIterator(List(this, bai))
this.clear()
result
}
case that: MultiByteArrayIterator => this ++: that
case mbai: MultiByteArrayIterator => this ++: mbai
case bi => super.++(bi)
}
case _ => super.++(that)
case io => super.++(io)
}
final override def clone: ByteArrayIterator = new ByteArrayIterator(array, from, until)
@ -99,9 +100,11 @@ object ByteIterator {
this
}
@nowarn("msg=deprecated")
override def copyToArray[B >: Byte](xs: Array[B], start: Int): Int =
this.copyToArray(xs, start, xs.length)
@nowarn("msg=deprecated")
override def copyToArray[B >: Byte](xs: Array[B]): Int =
this.copyToArray(xs, 0, xs.length)
@ -234,22 +237,23 @@ object ByteIterator {
}
final override def ++(that: IterableOnce[Byte]): ByteIterator = that match {
case that: ByteIterator =>
if (that.isEmpty) this
else if (this.isEmpty) that
case bi: ByteIterator =>
if (bi.isEmpty) this
else if (this.isEmpty) bi
else {
that match {
case that: ByteArrayIterator =>
iterators = this.iterators :+ that
that.clear()
bi match {
case bai: ByteArrayIterator =>
iterators = this.iterators :+ bai
bai.clear()
this
case that: MultiByteArrayIterator =>
iterators = this.iterators ++ that.iterators
that.clear()
case mbai: MultiByteArrayIterator =>
iterators = this.iterators ++ mbai.iterators
mbai.clear()
this
case bi => super.++(bi)
}
}
case _ => super.++(that)
case io => super.++(io)
}
final override def clone: MultiByteArrayIterator = {

View file

@ -833,6 +833,7 @@ sealed abstract class ByteString
array
}
@nowarn("msg=deprecated")
final override def copyToArray[B >: Byte](xs: Array[B], start: Int): Int = {
// super uses byteiterator
copyToArray(xs, start, size.min(xs.size))

View file

@ -65,6 +65,8 @@ private[akka] trait AbstractProps {
case c: Class[_] if c == coc =>
throw new IllegalArgumentException(
"erased Creator types (e.g. lambdas) are unsupported, use Props.create(actorClass, creator) instead")
case unexpected =>
throw new IllegalArgumentException(s"unexpected type: $unexpected")
}
create(classOf[CreatorConsumer], actorClass, creator)
}

View file

@ -565,6 +565,8 @@ private[akka] class ActorCell(
case PoisonPill => self.stop()
case sel: ActorSelectionMessage => receiveSelection(sel)
case Identify(messageId) => sender() ! ActorIdentity(messageId, Some(self))
case unexpected =>
throw new RuntimeException(s"Unexpected message for autoreceive: $unexpected") // for exhaustiveness check, will not happen
}
}

View file

@ -241,6 +241,8 @@ private[akka] trait RepointableRef extends ActorRefScope {
case i: InternalActorRef =>
(i.isLocal && i.isInstanceOf[PromiseActorRef]) ||
(!i.isLocal && i.path.elements.head == "temp")
case unexpected =>
throw new IllegalArgumentException(s"ActorRef is not internal: $unexpected") // will not happen, for exhaustiveness check
}
}
@ -924,8 +926,9 @@ private[akka] class VirtualPathContainer(
(oldWatching, wBy)
case OptionVal.None =>
case _ =>
(ActorCell.emptyActorRefSet, ActorCell.emptyActorRefSet)
}
}
@ -949,14 +952,14 @@ private[akka] class VirtualPathContainer(
val toNotify = this.synchronized {
// cleanup watchedBy since we know they are dead
_watchedBy match {
case OptionVal.None =>
// terminated
ActorCell.emptyActorRefSet
case OptionVal.Some(watchedBy) =>
maintainAddressTerminatedSubscription(OptionVal.None) {
_watchedBy = OptionVal.Some(watchedBy.filterNot(_.path.address == address))
}
watching
case _ =>
// terminated
ActorCell.emptyActorRefSet
}
}
@ -978,8 +981,6 @@ private[akka] class VirtualPathContainer(
private def addWatcher(watchee: ActorRef, watcher: ActorRef): Unit = {
val selfTerminated = this.synchronized {
_watchedBy match {
case OptionVal.None =>
true
case OptionVal.Some(watchedBy) =>
val watcheeSelf = watchee == this
val watcherSelf = watcher == this
@ -1001,6 +1002,8 @@ private[akka] class VirtualPathContainer(
Logging.Error(path.toString, classOf[FunctionRef], s"BUG: illegal Watch($watchee,$watcher) for $this"))
}
false
case _ =>
true
}
}
// outside of synchronized block
@ -1012,7 +1015,6 @@ private[akka] class VirtualPathContainer(
private def remWatcher(watchee: ActorRef, watcher: ActorRef): Unit = this.synchronized {
_watchedBy match {
case OptionVal.None => // do nothing...
case OptionVal.Some(watchedBy) =>
val watcheeSelf = watchee == this
val watcherSelf = watcher == this
@ -1033,6 +1035,8 @@ private[akka] class VirtualPathContainer(
publish(
Logging.Error(path.toString, classOf[FunctionRef], s"BUG: illegal Unwatch($watchee,$watcher) for $this"))
}
case _ => // do nothing...
}
}
@ -1097,7 +1101,7 @@ private[akka] class VirtualPathContainer(
def watchedByOrEmpty: Set[ActorRef] =
_watchedBy match {
case OptionVal.Some(watchedBy) => watchedBy
case OptionVal.None => ActorCell.emptyActorRefSet
case _ => ActorCell.emptyActorRefSet
}
change match {

View file

@ -756,7 +756,7 @@ private[akka] class LocalActorRefProvider private[akka] (
Serialization.Information(getDefaultAddress, system)
serializationInformationCache match {
case OptionVal.Some(info) => info
case OptionVal.None =>
case _ =>
if (system eq null)
throw new IllegalStateException("Too early access of serializationInformation")
else {
@ -773,7 +773,7 @@ private[akka] class LocalActorRefProvider private[akka] (
override private[akka] def addressString: String = {
_addressString match {
case OptionVal.Some(addr) => addr
case OptionVal.None =>
case _ =>
val addr = getDefaultAddress.toString
_addressString = OptionVal.Some(addr)
addr

View file

@ -69,6 +69,8 @@ class ReflectiveDynamicAccess(val classLoader: ClassLoader) extends DynamicAcces
case null => throw new NullPointerException
case x if !t.isInstance(x) => throw new ClassCastException(fqcn + " is not a subtype of " + t)
case x: T => x
case unexpected =>
throw new IllegalArgumentException(s"Unexpected module field: $unexpected") // will not happen, for exhaustiveness check
}
}.recover { case i: InvocationTargetException if i.getTargetException ne null => throw i.getTargetException }
}

View file

@ -50,7 +50,7 @@ trait Timers extends Actor {
actorCell.currentMessage = actorCell.currentMessage.copy(message = m)
}
super.aroundReceive(receive, m)
case OptionVal.None => // discard
case _ => // discard
}
case _ =>
super.aroundReceive(receive, msg)

View file

@ -33,6 +33,8 @@ private[akka] trait DeathWatch { this: ActorCell =>
checkWatchingSame(a, None)
}
a
case unexpected =>
throw new IllegalArgumentException(s"ActorRef is not internal: $unexpected") // will not happen, for exhaustiveness check
}
override final def watchWith(subject: ActorRef, msg: Any): ActorRef = subject match {
@ -46,6 +48,8 @@ private[akka] trait DeathWatch { this: ActorCell =>
checkWatchingSame(a, Some(msg))
}
a
case unexpected =>
throw new IllegalArgumentException(s"ActorRef is not internal: $unexpected") // will not happen, for exhaustiveness check
}
override final def unwatch(subject: ActorRef): ActorRef = subject match {
@ -58,6 +62,8 @@ private[akka] trait DeathWatch { this: ActorCell =>
}
terminatedQueued -= a
a
case unexpected =>
throw new IllegalArgumentException(s"ActorRef is not internal: $unexpected") // will not happen, for exhaustiveness check
}
protected def receivedTerminated(t: Terminated): Unit =

View file

@ -186,6 +186,8 @@ abstract class MessageDispatcher(val configurator: MessageDispatcherConfigurator
if (updateShutdownSchedule(SCHEDULED, RESCHEDULED)) ()
else ifSensibleToDoSoThenScheduleShutdown()
case RESCHEDULED =>
case unexpected =>
throw new IllegalArgumentException(s"Unexpected actor class marker: $unexpected") // will not happen, for exhaustiveness check
}
}
@ -245,6 +247,8 @@ abstract class MessageDispatcher(val configurator: MessageDispatcherConfigurator
if (updateShutdownSchedule(RESCHEDULED, SCHEDULED)) scheduleShutdownAction()
else run()
case UNSCHEDULED =>
case unexpected =>
throw new IllegalArgumentException(s"Unexpected actor class marker: $unexpected") // will not happen, for exhaustiveness check
}
}
}

View file

@ -108,6 +108,8 @@ private[akka] class Mailboxes(
case x =>
throw new IllegalArgumentException(s"no wildcard type allowed in RequireMessageQueue argument (was [$x])")
}
case unexpected =>
throw new IllegalArgumentException(s"Unexpected actor class marker: $unexpected") // will not happen, for exhaustiveness check
}
// dont care if this happens twice
@ -131,6 +133,8 @@ private[akka] class Mailboxes(
throw new IllegalArgumentException(
s"no wildcard type allowed in ProducesMessageQueue argument (was [$x])")
}
case unexpected =>
throw new IllegalArgumentException(s"Unexpected message queue type marker: $unexpected") // will not happen, for exhaustiveness check
}
}

View file

@ -100,6 +100,8 @@ private[io] class UdpListener(val udp: UdpExt, channelRegistry: ChannelRegistry,
handler ! Received(ByteString(buffer), sender)
if (readsLeft > 0) innerReceive(readsLeft - 1, buffer)
case null => // null means no data was available
case unexpected =>
throw new RuntimeException(s"Unexpected address in buffer: $unexpected") // will not happen, for exhaustiveness check
}
}

View file

@ -136,9 +136,12 @@ object DnsSettings {
/**
* INTERNAL API
*/
@InternalApi private[akka] def parseNameserverAddress(str: String): InetSocketAddress = {
val inetSocketAddress(host, port) = str
@InternalApi private[akka] def parseNameserverAddress(str: String): InetSocketAddress =
str match {
case inetSocketAddress(host, port) =>
new InetSocketAddress(host, Option(port).fold(DnsFallbackPort)(_.toInt))
case unexpected =>
throw new IllegalArgumentException(s"Unparseable address string: $unexpected") // will not happen, for exhaustiveness check
}
/**

View file

@ -94,6 +94,7 @@ private[io] final class AsyncDnsResolver(
val record = address match {
case _: Inet4Address => ARecord(name, Ttl.effectivelyForever, address)
case ipv6address: Inet6Address => AAAARecord(name, Ttl.effectivelyForever, ipv6address)
case unexpected => throw new IllegalArgumentException(s"Unexpected address: $unexpected")
}
DnsProtocol.Resolved(name, record :: Nil)
}

View file

@ -20,8 +20,8 @@ private[akka] object RecordTypeSerializer {
def parse(it: ByteIterator): RecordType = {
val id = it.getShort
RecordType(id) match {
case OptionVal.None => throw new IllegalArgumentException(s"Illegal id [$id] for DnsRecordType")
case OptionVal.Some(t) => t
case _ => throw new IllegalArgumentException(s"Illegal id [$id] for DnsRecordType")
}
}

View file

@ -604,6 +604,7 @@ private[akka] final class PromiseActorRef private (
updateState(Stopped, StoppedWithPath(provider.tempPath()))
path
case Registering => path // spin until registration is completed
case unexpected => throw new IllegalStateException(s"Unexpected state: $unexpected")
}
override def !(message: Any)(implicit sender: ActorRef = Actor.noSender): Unit = state match {
@ -668,6 +669,7 @@ private[akka] final class PromiseActorRef private (
} else stop()
case Stopped | _: StoppedWithPath => // already stopped
case Registering => stop() // spin until registration is completed before stopping
case unexpected => throw new IllegalStateException(s"Unexpected state: $unexpected")
}
}

View file

@ -164,6 +164,8 @@ object StatusReply {
s match {
case StatusReply.Success(v) => ScalaSuccess(v.asInstanceOf[T])
case StatusReply.Error(ex) => ScalaFailure[T](ex)
case unexpected =>
ScalaFailure(new IllegalArgumentException(s"Unexpected status reply success value: ${unexpected}"))
}
case fail @ ScalaFailure(_) => fail.asInstanceOf[Try[T]]
}(ExecutionContexts.parasitic)

View file

@ -219,6 +219,8 @@ final case class ConsistentHashingRoutingLogic(
case bytes: Array[Byte] => currentConsistenHash.nodeFor(bytes).routee
case str: String => currentConsistenHash.nodeFor(str).routee
case x: AnyRef => currentConsistenHash.nodeFor(SerializationExtension(system).serialize(x).get).routee
case unexpected =>
throw new IllegalArgumentException(s"Unexpected hashdata: $unexpected") // will not happen, for exhaustiveness check
}
} catch {
case NonFatal(e) =>

View file

@ -168,6 +168,7 @@ import akka.util.ByteString
val flag = o match {
case TRUE => TrueB
case FALSE => FalseB
case b => throw new IllegalArgumentException(s"Non boolean flag: $b")
}
buf.put(flag)
}
@ -176,6 +177,7 @@ import akka.util.ByteString
buf.get() match {
case TrueB => TRUE
case FalseB => FALSE
case b => throw new IllegalArgumentException(s"Non boolean flag byte: $b")
}
}
@ -183,6 +185,7 @@ import akka.util.ByteString
val flag = o match {
case TRUE => TrueB
case FALSE => FalseB
case b => throw new IllegalArgumentException(s"Non boolean flag: $b")
}
val result = new Array[Byte](1)
result(0) = flag
@ -193,6 +196,7 @@ import akka.util.ByteString
bytes(0) match {
case TrueB => TRUE
case FalseB => FALSE
case b => throw new IllegalArgumentException(s"Non boolean flag byte: $b")
}
}
}

View file

@ -40,6 +40,8 @@ object HashCode {
else if (!isArray(value)) result = hash(result, value.hashCode())
else for (id <- 0 until JArray.getLength(value)) result = hash(result, JArray.get(value, id)) // is an array
result
case unexpected =>
throw new IllegalArgumentException(s"Unexpected hash parameter: $unexpected") // will not happen, for exhaustiveness check
}
def hash(seed: Int, value: Boolean): Int = firstTerm(seed) + (if (value) 1 else 0)
def hash(seed: Int, value: Char): Int = firstTerm(seed) + value.asInstanceOf[Int]

View file

@ -95,7 +95,7 @@ object TypedBenchmarkActors {
val startNanoTime = System.nanoTime()
pairs.foreach(_ ! Message)
var interactionsLeft = numPairs
Behaviors.receiveMessage {
Behaviors.receiveMessagePartial {
case Done =>
interactionsLeft -= 1
if (interactionsLeft == 0) {

View file

@ -41,7 +41,7 @@ object Producer {
val requestNextAdapter =
context.messageAdapter[ProducerController.RequestNext[Consumer.Command]](WrappedRequestNext(_))
Behaviors.receiveMessage {
Behaviors.receiveMessagePartial {
case WrappedRequestNext(next) =>
if (next.confirmedSeqNr >= numberOfMessages) {
context.log.info("Completed {} messages", numberOfMessages)
@ -114,7 +114,7 @@ object WorkPullingProducer {
var remaining = numberOfMessages + context.system.settings.config
.getInt("akka.reliable-delivery.consumer-controller.flow-control-window")
Behaviors.receiveMessage {
Behaviors.receiveMessagePartial {
case WrappedRequestNext(next) =>
remaining -= 1
if (remaining == 0) {
@ -183,6 +183,9 @@ object Guardian {
consumers.foreach(context.stop)
replyTo ! Done
Behaviors.same
case msg =>
throw new RuntimeException(s"Unexpected message $msg")
}
}
}

View file

@ -489,6 +489,7 @@ private[metrics] class WeightedRoutees(
val a = routee match {
case ActorRefRoutee(ref) => ref.path.address
case ActorSelectionRoutee(sel) => sel.anchor.path.address
case _ => throw new RuntimeException()
}
a match {
case Address(_, _, None, None) => selfAddress

View file

@ -156,7 +156,7 @@ abstract class AdaptiveLoadBalancingRouterSpec
// it may take some time until router receives cluster member events
awaitAssert { currentRoutees(router).size should ===(roles.size) }
val routees = currentRoutees(router)
routees.map { case ActorRefRoutee(ref) => fullAddress(ref) }.toSet should ===(roles.map(address).toSet)
routees.collect { case ActorRefRoutee(ref) => fullAddress(ref) }.toSet should ===(roles.map(address).toSet)
router
}
@ -235,7 +235,7 @@ abstract class AdaptiveLoadBalancingRouterSpec
// it may take some time until router receives cluster member events
awaitAssert { currentRoutees(router3).size should ===(9) }
val routees = currentRoutees(router3)
routees.map { case ActorRefRoutee(ref) => fullAddress(ref) }.toSet should ===(Set(address(node1)))
routees.collect { case ActorRefRoutee(ref) => fullAddress(ref) }.toSet should ===(Set(address(node1)))
}
enterBarrier("after-4")
}
@ -246,7 +246,7 @@ abstract class AdaptiveLoadBalancingRouterSpec
// it may take some time until router receives cluster member events
awaitAssert { currentRoutees(router4).size should ===(6) }
val routees = currentRoutees(router4)
routees.map { case ActorRefRoutee(ref) => fullAddress(ref) }.toSet should ===(
routees.collect { case ActorRefRoutee(ref) => fullAddress(ref) }.toSet should ===(
Set(address(node1), address(node2), address(node3)))
}
enterBarrier("after-5")

View file

@ -82,6 +82,7 @@ class ClusterMetricsExtensionSpec
loadAverageMock.get should ===(loadAverageEwma +- epsilon)
cpuCombinedMock.get should ===(cpuCombinedEwma +- epsilon)
cpuStolenMock.get should ===(cpuStolenEwma +- epsilon)
case _ => fail()
}
}
}

View file

@ -125,7 +125,7 @@ import akka.util.Timeout
.narrow
}
private def createInitialState[A: ClassTag](hasDurableQueue: Boolean) = {
private def createInitialState[A](hasDurableQueue: Boolean) = {
if (hasDurableQueue) None else Some(DurableProducerQueue.State.empty[A])
}
@ -226,12 +226,12 @@ import akka.util.Timeout
}
}
private def checkStashFull[A: ClassTag](stashBuffer: StashBuffer[InternalCommand]): Unit = {
private def checkStashFull[A](stashBuffer: StashBuffer[InternalCommand]): Unit = {
if (stashBuffer.isFull)
throw new IllegalArgumentException(s"Buffer is full, size [${stashBuffer.size}].")
}
private def askLoadState[A: ClassTag](
private def askLoadState[A](
context: ActorContext[InternalCommand],
durableQueueBehavior: Option[Behavior[DurableProducerQueue.Command[A]]],
settings: ShardingProducerController.Settings): Option[ActorRef[DurableProducerQueue.Command[A]]] = {
@ -244,7 +244,7 @@ import akka.util.Timeout
}
}
private def askLoadState[A: ClassTag](
private def askLoadState[A](
context: ActorContext[InternalCommand],
durableQueue: Option[ActorRef[DurableProducerQueue.Command[A]]],
settings: ShardingProducerController.Settings,
@ -565,6 +565,8 @@ private class ShardingProducerControllerImpl[A: ClassTag](
case DurableQueueTerminated =>
throw new IllegalStateException("DurableQueue was unexpectedly terminated.")
case unexpected =>
throw new RuntimeException(s"Unexpected message: $unexpected")
}
}

View file

@ -55,7 +55,7 @@ import akka.util.JavaDurationConverters._
message match {
case ShardingEnvelope(entityId, _) => entityId //also covers ClassicStartEntity in ShardingEnvelope
case ClassicStartEntity(entityId) => entityId
case msg: E @unchecked => delegate.entityId(msg)
case msg => delegate.entityId(msg.asInstanceOf[E])
}
}
@ -69,8 +69,8 @@ import akka.util.JavaDurationConverters._
case msg: ClassicStartEntity =>
// not really of type M, but erased and StartEntity is only handled internally, not delivered to the entity
msg.asInstanceOf[M]
case msg: E @unchecked =>
delegate.unwrapMessage(msg)
case msg =>
delegate.unwrapMessage(msg.asInstanceOf[E])
}
}

View file

@ -39,7 +39,7 @@ object ShardedDaemonProcessSpec extends MultiNodeConfig {
val snitchRouter = ctx.spawn(Routers.group(SnitchServiceKey), "router")
snitchRouter ! ProcessActorEvent(id, "Started")
Behaviors.receiveMessage {
Behaviors.receiveMessagePartial {
case Stop =>
snitchRouter ! ProcessActorEvent(id, "Stopped")
Behaviors.stopped

View file

@ -77,7 +77,7 @@ object DeliveryThroughputSpec extends MultiNodeConfig {
}
object Consumer {
trait Command
sealed trait Command
case object TheMessage extends Command with CborSerializable
case object Stop extends Command
@ -122,7 +122,7 @@ object DeliveryThroughputSpec extends MultiNodeConfig {
}
object Producer {
trait Command
sealed trait Command
case object Run extends Command
private case class WrappedRequestNext(r: ProducerController.RequestNext[Consumer.Command]) extends Command
@ -180,7 +180,7 @@ object DeliveryThroughputSpec extends MultiNodeConfig {
def serviceKey(testName: String) = ServiceKey[ConsumerController.Command[Consumer.Command]](testName)
object WorkPullingProducer {
trait Command
sealed trait Command
case object Run extends Command
private case class WrappedRequestNext(r: WorkPullingProducerController.RequestNext[Consumer.Command])
@ -225,7 +225,7 @@ object DeliveryThroughputSpec extends MultiNodeConfig {
def typeKey(testName: String) = EntityTypeKey[ConsumerController.SequencedMessage[Consumer.Command]](testName)
object ShardingProducer {
trait Command
sealed trait Command
case object Run extends Command
private case class WrappedRequestNext(r: ShardingProducerController.RequestNext[Consumer.Command]) extends Command

View file

@ -70,7 +70,7 @@ object ReplicatedShardingSpec {
val AllReplicas = Set(ReplicaId("DC-A"), ReplicaId("DC-B"))
object MyReplicatedStringSet {
trait Command extends CborSerializable
sealed trait Command extends CborSerializable
case class Add(text: String) extends Command
case class GetTexts(replyTo: ActorRef[Texts]) extends Command
@ -122,7 +122,7 @@ object ReplicatedShardingSpec {
}
object MyReplicatedIntSet {
trait Command extends CborSerializable
sealed trait Command extends CborSerializable
case class Add(text: Int) extends Command
case class GetInts(replyTo: ActorRef[Ints]) extends Command
case class Ints(ints: Set[Int]) extends CborSerializable

View file

@ -40,7 +40,7 @@ object ReliableDeliveryShardingSpec {
object TestShardingProducer {
trait Command
sealed trait Command
final case class RequestNext(sendToRef: ActorRef[ShardingEnvelope[TestConsumer.Job]]) extends Command
private case object Tick extends Command

View file

@ -38,7 +38,7 @@ object ShardedDaemonProcessSpec {
""")
object MyActor {
trait Command
sealed trait Command
case object Stop extends Command
case class Started(id: Int, selfRef: ActorRef[Command])

View file

@ -50,7 +50,7 @@ object HelloWorldPersistentEntityExample {
object HelloWorld {
// Command
trait Command extends CborSerializable
sealed trait Command extends CborSerializable
final case class Greet(whom: String)(val replyTo: ActorRef[Greeting]) extends Command
// Response
final case class Greeting(whom: String, numberOfPeople: Int) extends CborSerializable

View file

@ -67,7 +67,7 @@ object WorkPullingDocExample {
import akka.actor.typed.scaladsl.StashBuffer
object ImageWorkManager {
trait Command
sealed trait Command
final case class Convert(fromFormat: String, toFormat: String, image: Array[Byte]) extends Command
private case class WrappedRequestNext(r: WorkPullingProducerController.RequestNext[ImageConverter.ConversionJob])
extends Command
@ -137,7 +137,7 @@ object WorkPullingDocExample {
import ImageWorkManager._
private def waitForNext(): Behavior[Command] = {
Behaviors.receiveMessage {
Behaviors.receiveMessagePartial {
case WrappedRequestNext(next) =>
stashBuffer.unstashAll(active(next))
case c: Convert =>
@ -156,7 +156,7 @@ object WorkPullingDocExample {
private def active(
next: WorkPullingProducerController.RequestNext[ImageConverter.ConversionJob]): Behavior[Command] = {
Behaviors.receiveMessage {
Behaviors.receiveMessagePartial {
case Convert(from, to, image) =>
val resultId = UUID.randomUUID()
next.sendNextTo ! ImageConverter.ConversionJob(resultId, from, to, image)
@ -178,7 +178,7 @@ object WorkPullingDocExample {
implicit val askTimeout: Timeout = 5.seconds
private def waitForNext(): Behavior[Command] = {
Behaviors.receiveMessage {
Behaviors.receiveMessagePartial {
case WrappedRequestNext(next) =>
stashBuffer.unstashAll(active(next))
case c: ConvertRequest =>
@ -201,7 +201,7 @@ object WorkPullingDocExample {
private def active(
next: WorkPullingProducerController.RequestNext[ImageConverter.ConversionJob]): Behavior[Command] = {
Behaviors.receiveMessage {
Behaviors.receiveMessagePartial {
case ConvertRequest(from, to, image, originalReplyTo) =>
val resultId = UUID.randomUUID()
context.ask[MessageWithConfirmation[ImageConverter.ConversionJob], Done](

View file

@ -301,7 +301,7 @@ class ClusterSharding(system: ExtendedActorSystem) extends Extension {
extractShardId,
allocationStrategy,
handOffStopMessage)
val Started(shardRegion) = Await.result(guardian ? startMsg, timeout.duration)
val shardRegion = Await.result((guardian ? startMsg).mapTo[Started], timeout.duration).shardRegion
regions.put(typeName, shardRegion)
shardRegion
case ref => ref // already started, use cached ActorRef
@ -545,7 +545,7 @@ class ClusterSharding(system: ExtendedActorSystem) extends Extension {
implicit val timeout = system.settings.CreationTimeout
val settings = ClusterShardingSettings(system).withRole(role)
val startMsg = StartProxy(typeName, dataCenter, settings, extractEntityId, extractShardId)
val Started(shardRegion) = Await.result(guardian ? startMsg, timeout.duration)
val shardRegion = Await.result((guardian ? startMsg).mapTo[Started], timeout.duration).shardRegion
// it must be possible to start several proxies, one per data center
proxies.put(proxyName(typeName, dataCenter), shardRegion)
shardRegion
@ -777,6 +777,8 @@ private[akka] class ClusterShardingGuardian extends Actor {
new EventSourcedRememberEntitiesProvider(typeName, settings)
case ClusterShardingSettings.RememberEntitiesStoreCustom =>
new CustomStateStoreModeProvider(typeName, context.system, settings)
case unknown =>
throw new IllegalArgumentException(s"Unknown store type: $unknown") // compiler exhaustiveness check pleaser
})
}

View file

@ -960,7 +960,7 @@ private[akka] class Shard(
entityId,
unexpected)
}
case OptionVal.None =>
case _ =>
log.warning("{}: Unexpected entity terminated: {}", typeName, ref)
}
}
@ -982,7 +982,7 @@ private[akka] class Shard(
entity ! stopMessage
flightRecorder.entityPassivate(id)
}
case OptionVal.None =>
case _ =>
log.debug("{}: Unknown entity passivating [{}]. Not sending stopMessage back to entity", typeName, entity)
}
}
@ -1108,7 +1108,7 @@ private[akka] class Shard(
def getOrCreateEntity(id: EntityId): ActorRef = {
entities.entity(id) match {
case OptionVal.Some(child) => child
case OptionVal.None =>
case _ =>
val name = URLEncoder.encode(id, "utf-8")
val a = context.actorOf(entityProps(id), name)
context.watchWith(a, EntityTerminated(a))

View file

@ -70,6 +70,7 @@ final private[external] class ExternalShardAllocationClientImpl(system: ActorSys
case UpdateSuccess(_, _) => Future.successful(Done)
case UpdateTimeout =>
Future.failed(new ClientTimeoutException(s"Unable to update shard location after ${timeout.duration.pretty}"))
case _ => throw new IllegalArgumentException() // compiler exhaustiveness check pleaser
}
}
@ -86,6 +87,7 @@ final private[external] class ExternalShardAllocationClientImpl(system: ActorSys
Future.successful(Map.empty[ShardId, ShardLocation])
case GetFailure(_, _) =>
Future.failed((new ClientTimeoutException(s"Unable to get shard locations after ${timeout.duration.pretty}")))
case _ => throw new IllegalArgumentException() // compiler exhaustiveness check pleaser
}
.map { locations =>
new ShardLocations(locations)
@ -104,6 +106,7 @@ final private[external] class ExternalShardAllocationClientImpl(system: ActorSys
case UpdateSuccess(_, _) => Future.successful(Done)
case UpdateTimeout =>
Future.failed(new ClientTimeoutException(s"Unable to update shard location after ${timeout.duration.pretty}"))
case _ => throw new IllegalArgumentException() // compiler exhaustiveness check pleaser
}
}

View file

@ -31,9 +31,9 @@ object GlobalRegistry {
case id: Int => (id.toString, id)
}
val extractShardId: ShardRegion.ExtractShardId = msg =>
msg match {
val extractShardId: ShardRegion.ExtractShardId = {
case id: Int => (id % 10).toString
case _ => throw new IllegalArgumentException()
}
}

View file

@ -42,6 +42,7 @@ object ClusterShardCoordinatorDowning2Spec {
val extractShardId: ShardRegion.ExtractShardId = {
case Ping(id: String) => id.charAt(0).toString
case _ => throw new IllegalArgumentException()
}
}

View file

@ -42,6 +42,7 @@ object ClusterShardCoordinatorDowningSpec {
val extractShardId: ShardRegion.ExtractShardId = {
case Ping(id: String) => id.charAt(0).toString
case _ => throw new IllegalArgumentException()
}
}

View file

@ -46,6 +46,7 @@ object ClusterShardingFailureSpec {
case Get(id) => id.charAt(0).toString
case Add(id, _) => id.charAt(0).toString
case StartEntity(id) => id
case _ => throw new IllegalArgumentException()
}
}

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