Skip to content

Commit

Permalink
Added test and logic to prevent Any handler from being added twice
Browse files Browse the repository at this point in the history
  • Loading branch information
mhbuck committed Feb 10, 2025
1 parent 8480ac6 commit 9dd025c
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
35 changes: 33 additions & 2 deletions src/core/Akka.Tests/Actor/ReceiveActorTests.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// <copyright file="ReceiveActorTests.cs" company="Akka.NET Project">
// Copyright (C) 2009-2022 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2025 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------

using System;
using System.Threading;
using System.Threading.Tasks;
using Akka.Actor;
using Akka.Event;
Expand Down Expand Up @@ -138,6 +139,22 @@ public async Task Given_an_actor_which_overrides_PreStart_When_sending_a_message
await ExpectMsgAsync(4711);
}

[Fact]
public async Task Given_an_actor_which_adds_any_handler_twice_should_throw_exception()
{
// Handling the scenario where the actor adds an any handler twice. This should not be allowed.
// Given
var system = ActorSystem.Create("test");
var actor = system.ActorOf<AnyAddedTwiceActor>("addedtwice");

// When
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3));
var terminated = await actor.WatchAsync(cts.Token);

// Then
Assert.True(terminated);
}

private class NoReceiveActor : ReceiveActor
{
}
Expand All @@ -150,7 +167,6 @@ public EchoReceiveActor()
}
}


private class PreStartEchoReceiveActor : ReceiveActor
{
public PreStartEchoReceiveActor()
Expand Down Expand Up @@ -238,6 +254,21 @@ public ReceiveAnyActor()
}
}

private class AnyAddedTwiceActor : ReceiveActor
{
public AnyAddedTwiceActor()
{
ReceiveAny(o =>
{
Sender.Tell("any:" + o, Self);
});
ReceiveAny(o =>
{
Sender.Tell("not allowed any:" + o, Self);
});
}
}

}
}

6 changes: 6 additions & 0 deletions src/core/Akka/Actor/ReceiveActor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,12 @@ protected void ReceiveAny(Action<object> handler)
{
EnsureMayConfigureMessageHandlers();
var handlers = _handlersStack.Peek();

if (handlers.HandleAny != null)
{
throw new InvalidOperationException("A handler that catches all messages has been added. No handler can be added after that.");
}

handlers.HandleAny = handler;
}

Expand Down

0 comments on commit 9dd025c

Please sign in to comment.