diff --git a/src/.nuget/NuGet.exe b/src/.nuget/NuGet.exe index 9f8781de0db..324daa842c5 100644 Binary files a/src/.nuget/NuGet.exe and b/src/.nuget/NuGet.exe differ diff --git a/src/Akka.sln b/src/Akka.sln index 80cdfe49a89..7da27222e6c 100644 --- a/src/Akka.sln +++ b/src/Akka.sln @@ -232,27 +232,6 @@ EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Akka.Serialization.TestKit", "contrib\serializers\Akka.Serialization.TestKit\Akka.Serialization.TestKit.csproj", "{CAA97041-CFC0-4081-9BD2-8B139E62A611}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Akka.Serialization.WireTests", "contrib\serializers\Akka.Serialization.WireTests\Akka.Serialization.WireTests.csproj", "{402FA351-D6C6-40FD-8868-F07156035919}" -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Cluster", "Cluster", "{76F58DC4-19F1-43EF-A6E2-EC1CC8395AC5}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Akka.Cluster.Sharding", "contrib\cluster\Akka.Cluster.Sharding\Akka.Cluster.Sharding.csproj", "{A05C31E8-0246-46A1-B3BC-4D6FE7A9AA49}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Akka.Cluster.Tools", "contrib\cluster\Akka.Cluster.Tools\Akka.Cluster.Tools.csproj", "{5CF8A8BE-B634-473F-BB01-EBA878746BD4}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Akka.Cluster.Tools.Tests", "contrib\cluster\Akka.Cluster.Tools.Tests\Akka.Cluster.Tools.Tests.csproj", "{9D8D62C7-7B4B-4CDF-8FE8-675DB71F6B21}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Akka.Cluster.Sharding.Tests", "contrib\cluster\Akka.Cluster.Sharding.Tests\Akka.Cluster.Sharding.Tests.csproj", "{B369F314-4D37-4AC1-B4FB-64FF671AF0BC}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ClusterTools", "ClusterTools", "{B1DDEC01-8525-4C38-B820-7C44F5A2930B}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ClusterSharding", "ClusterSharding", "{21E02199-F0E0-4818-A7D6-CBF28F79920D}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ClusterSharding.Node", "examples\Cluster\ClusterSharding\ClusterSharding.Node\ClusterSharding.Node.csproj", "{30A0B17D-B913-49AB-8CBB-8DF383AB7A52}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ClusterToolsExample.Shared", "examples\Cluster\ClusterTools\ClusterToolsExample.Shared\ClusterToolsExample.Shared.csproj", "{88D7D845-2F50-4D37-9026-B0A8353D0E8D}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ClusterToolsExample.Seed", "examples\Cluster\ClusterTools\ClusterToolsExample.Seed\ClusterToolsExample.Seed.csproj", "{ED00E6F4-2B5C-4F16-ADE4-45E4A73C17B8}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ClusterToolsExample.Node", "examples\Cluster\ClusterTools\ClusterToolsExample.Node\ClusterToolsExample.Node.csproj", "{337A85B5-4A7C-4883-8634-46E7E52A765F}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -875,70 +854,6 @@ Global {402FA351-D6C6-40FD-8868-F07156035919}.Release Mono|Any CPU.Build.0 = Release|Any CPU {402FA351-D6C6-40FD-8868-F07156035919}.Release|Any CPU.ActiveCfg = Release|Any CPU {402FA351-D6C6-40FD-8868-F07156035919}.Release|Any CPU.Build.0 = Release|Any CPU - {A05C31E8-0246-46A1-B3BC-4D6FE7A9AA49}.Debug Mono|Any CPU.ActiveCfg = Debug|Any CPU - {A05C31E8-0246-46A1-B3BC-4D6FE7A9AA49}.Debug Mono|Any CPU.Build.0 = Debug|Any CPU - {A05C31E8-0246-46A1-B3BC-4D6FE7A9AA49}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A05C31E8-0246-46A1-B3BC-4D6FE7A9AA49}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A05C31E8-0246-46A1-B3BC-4D6FE7A9AA49}.Release Mono|Any CPU.ActiveCfg = Release|Any CPU - {A05C31E8-0246-46A1-B3BC-4D6FE7A9AA49}.Release Mono|Any CPU.Build.0 = Release|Any CPU - {A05C31E8-0246-46A1-B3BC-4D6FE7A9AA49}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A05C31E8-0246-46A1-B3BC-4D6FE7A9AA49}.Release|Any CPU.Build.0 = Release|Any CPU - {5CF8A8BE-B634-473F-BB01-EBA878746BD4}.Debug Mono|Any CPU.ActiveCfg = Debug|Any CPU - {5CF8A8BE-B634-473F-BB01-EBA878746BD4}.Debug Mono|Any CPU.Build.0 = Debug|Any CPU - {5CF8A8BE-B634-473F-BB01-EBA878746BD4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5CF8A8BE-B634-473F-BB01-EBA878746BD4}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5CF8A8BE-B634-473F-BB01-EBA878746BD4}.Release Mono|Any CPU.ActiveCfg = Release|Any CPU - {5CF8A8BE-B634-473F-BB01-EBA878746BD4}.Release Mono|Any CPU.Build.0 = Release|Any CPU - {5CF8A8BE-B634-473F-BB01-EBA878746BD4}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5CF8A8BE-B634-473F-BB01-EBA878746BD4}.Release|Any CPU.Build.0 = Release|Any CPU - {9D8D62C7-7B4B-4CDF-8FE8-675DB71F6B21}.Debug Mono|Any CPU.ActiveCfg = Debug|Any CPU - {9D8D62C7-7B4B-4CDF-8FE8-675DB71F6B21}.Debug Mono|Any CPU.Build.0 = Debug|Any CPU - {9D8D62C7-7B4B-4CDF-8FE8-675DB71F6B21}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {9D8D62C7-7B4B-4CDF-8FE8-675DB71F6B21}.Debug|Any CPU.Build.0 = Debug|Any CPU - {9D8D62C7-7B4B-4CDF-8FE8-675DB71F6B21}.Release Mono|Any CPU.ActiveCfg = Release|Any CPU - {9D8D62C7-7B4B-4CDF-8FE8-675DB71F6B21}.Release Mono|Any CPU.Build.0 = Release|Any CPU - {9D8D62C7-7B4B-4CDF-8FE8-675DB71F6B21}.Release|Any CPU.ActiveCfg = Release|Any CPU - {9D8D62C7-7B4B-4CDF-8FE8-675DB71F6B21}.Release|Any CPU.Build.0 = Release|Any CPU - {B369F314-4D37-4AC1-B4FB-64FF671AF0BC}.Debug Mono|Any CPU.ActiveCfg = Debug|Any CPU - {B369F314-4D37-4AC1-B4FB-64FF671AF0BC}.Debug Mono|Any CPU.Build.0 = Debug|Any CPU - {B369F314-4D37-4AC1-B4FB-64FF671AF0BC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {B369F314-4D37-4AC1-B4FB-64FF671AF0BC}.Debug|Any CPU.Build.0 = Debug|Any CPU - {B369F314-4D37-4AC1-B4FB-64FF671AF0BC}.Release Mono|Any CPU.ActiveCfg = Release|Any CPU - {B369F314-4D37-4AC1-B4FB-64FF671AF0BC}.Release Mono|Any CPU.Build.0 = Release|Any CPU - {B369F314-4D37-4AC1-B4FB-64FF671AF0BC}.Release|Any CPU.ActiveCfg = Release|Any CPU - {B369F314-4D37-4AC1-B4FB-64FF671AF0BC}.Release|Any CPU.Build.0 = Release|Any CPU - {30A0B17D-B913-49AB-8CBB-8DF383AB7A52}.Debug Mono|Any CPU.ActiveCfg = Debug|Any CPU - {30A0B17D-B913-49AB-8CBB-8DF383AB7A52}.Debug Mono|Any CPU.Build.0 = Debug|Any CPU - {30A0B17D-B913-49AB-8CBB-8DF383AB7A52}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {30A0B17D-B913-49AB-8CBB-8DF383AB7A52}.Debug|Any CPU.Build.0 = Debug|Any CPU - {30A0B17D-B913-49AB-8CBB-8DF383AB7A52}.Release Mono|Any CPU.ActiveCfg = Release|Any CPU - {30A0B17D-B913-49AB-8CBB-8DF383AB7A52}.Release Mono|Any CPU.Build.0 = Release|Any CPU - {30A0B17D-B913-49AB-8CBB-8DF383AB7A52}.Release|Any CPU.ActiveCfg = Release|Any CPU - {30A0B17D-B913-49AB-8CBB-8DF383AB7A52}.Release|Any CPU.Build.0 = Release|Any CPU - {88D7D845-2F50-4D37-9026-B0A8353D0E8D}.Debug Mono|Any CPU.ActiveCfg = Debug|Any CPU - {88D7D845-2F50-4D37-9026-B0A8353D0E8D}.Debug Mono|Any CPU.Build.0 = Debug|Any CPU - {88D7D845-2F50-4D37-9026-B0A8353D0E8D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {88D7D845-2F50-4D37-9026-B0A8353D0E8D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {88D7D845-2F50-4D37-9026-B0A8353D0E8D}.Release Mono|Any CPU.ActiveCfg = Release|Any CPU - {88D7D845-2F50-4D37-9026-B0A8353D0E8D}.Release Mono|Any CPU.Build.0 = Release|Any CPU - {88D7D845-2F50-4D37-9026-B0A8353D0E8D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {88D7D845-2F50-4D37-9026-B0A8353D0E8D}.Release|Any CPU.Build.0 = Release|Any CPU - {ED00E6F4-2B5C-4F16-ADE4-45E4A73C17B8}.Debug Mono|Any CPU.ActiveCfg = Debug|Any CPU - {ED00E6F4-2B5C-4F16-ADE4-45E4A73C17B8}.Debug Mono|Any CPU.Build.0 = Debug|Any CPU - {ED00E6F4-2B5C-4F16-ADE4-45E4A73C17B8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {ED00E6F4-2B5C-4F16-ADE4-45E4A73C17B8}.Debug|Any CPU.Build.0 = Debug|Any CPU - {ED00E6F4-2B5C-4F16-ADE4-45E4A73C17B8}.Release Mono|Any CPU.ActiveCfg = Release|Any CPU - {ED00E6F4-2B5C-4F16-ADE4-45E4A73C17B8}.Release Mono|Any CPU.Build.0 = Release|Any CPU - {ED00E6F4-2B5C-4F16-ADE4-45E4A73C17B8}.Release|Any CPU.ActiveCfg = Release|Any CPU - {ED00E6F4-2B5C-4F16-ADE4-45E4A73C17B8}.Release|Any CPU.Build.0 = Release|Any CPU - {337A85B5-4A7C-4883-8634-46E7E52A765F}.Debug Mono|Any CPU.ActiveCfg = Debug|Any CPU - {337A85B5-4A7C-4883-8634-46E7E52A765F}.Debug Mono|Any CPU.Build.0 = Debug|Any CPU - {337A85B5-4A7C-4883-8634-46E7E52A765F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {337A85B5-4A7C-4883-8634-46E7E52A765F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {337A85B5-4A7C-4883-8634-46E7E52A765F}.Release Mono|Any CPU.ActiveCfg = Release|Any CPU - {337A85B5-4A7C-4883-8634-46E7E52A765F}.Release Mono|Any CPU.Build.0 = Release|Any CPU - {337A85B5-4A7C-4883-8634-46E7E52A765F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {337A85B5-4A7C-4883-8634-46E7E52A765F}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -1042,16 +957,5 @@ Global {B47CA568-40CF-48DE-B87E-31BD400EBB08} = {0E55F1F8-E212-43D7-A0C0-ACEA9794B0D7} {CAA97041-CFC0-4081-9BD2-8B139E62A611} = {0E55F1F8-E212-43D7-A0C0-ACEA9794B0D7} {402FA351-D6C6-40FD-8868-F07156035919} = {0E55F1F8-E212-43D7-A0C0-ACEA9794B0D7} - {76F58DC4-19F1-43EF-A6E2-EC1CC8395AC5} = {588C1513-FAB6-42C3-B6FC-3485F13620CF} - {A05C31E8-0246-46A1-B3BC-4D6FE7A9AA49} = {76F58DC4-19F1-43EF-A6E2-EC1CC8395AC5} - {5CF8A8BE-B634-473F-BB01-EBA878746BD4} = {76F58DC4-19F1-43EF-A6E2-EC1CC8395AC5} - {9D8D62C7-7B4B-4CDF-8FE8-675DB71F6B21} = {76F58DC4-19F1-43EF-A6E2-EC1CC8395AC5} - {B369F314-4D37-4AC1-B4FB-64FF671AF0BC} = {76F58DC4-19F1-43EF-A6E2-EC1CC8395AC5} - {B1DDEC01-8525-4C38-B820-7C44F5A2930B} = {DCE4B11E-6A5F-4AC8-A089-037F0B14BFAB} - {21E02199-F0E0-4818-A7D6-CBF28F79920D} = {DCE4B11E-6A5F-4AC8-A089-037F0B14BFAB} - {30A0B17D-B913-49AB-8CBB-8DF383AB7A52} = {21E02199-F0E0-4818-A7D6-CBF28F79920D} - {88D7D845-2F50-4D37-9026-B0A8353D0E8D} = {B1DDEC01-8525-4C38-B820-7C44F5A2930B} - {ED00E6F4-2B5C-4F16-ADE4-45E4A73C17B8} = {B1DDEC01-8525-4C38-B820-7C44F5A2930B} - {337A85B5-4A7C-4883-8634-46E7E52A765F} = {B1DDEC01-8525-4C38-B820-7C44F5A2930B} EndGlobalSection EndGlobal diff --git a/src/SharedAssemblyInfo.cs b/src/SharedAssemblyInfo.cs index 41fdd7e5345..fcb5f369368 100644 --- a/src/SharedAssemblyInfo.cs +++ b/src/SharedAssemblyInfo.cs @@ -4,5 +4,5 @@ [assembly: AssemblyCompanyAttribute("Akka.NET Team")] [assembly: AssemblyCopyrightAttribute("Copyright © 2013-2015 Akka.NET Team")] [assembly: AssemblyTrademarkAttribute("")] -[assembly: AssemblyVersionAttribute("1.0.6.0")] -[assembly: AssemblyFileVersionAttribute("1.0.6.0")] +[assembly: AssemblyVersionAttribute("1.0.5.0")] +[assembly: AssemblyFileVersionAttribute("1.0.5.0")] diff --git a/src/contrib/cluster/Akka.Cluster.Sharding.Tests/Akka.Cluster.Sharding.Tests.csproj b/src/contrib/cluster/Akka.Cluster.Sharding.Tests/Akka.Cluster.Sharding.Tests.csproj deleted file mode 100644 index 22441ab6469..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Sharding.Tests/Akka.Cluster.Sharding.Tests.csproj +++ /dev/null @@ -1,135 +0,0 @@ - - - - - Debug - AnyCPU - {B369F314-4D37-4AC1-B4FB-64FF671AF0BC} - Library - Properties - Akka.Cluster.Sharding.Tests - Akka.Cluster.Sharding.Tests - v4.5 - 512 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - - ..\..\..\packages\System.Collections.Immutable.1.1.37\lib\dotnet\System.Collections.Immutable.dll - True - - - - - - - - - - ..\..\..\packages\xunit.abstractions.2.0.0\lib\net35\xunit.abstractions.dll - True - - - ..\..\..\packages\xunit.assert.2.1.0\lib\dotnet\xunit.assert.dll - True - - - ..\..\..\packages\xunit.extensibility.core.2.1.0\lib\dotnet\xunit.core.dll - True - - - ..\..\..\packages\xunit.extensibility.execution.2.1.0\lib\net45\xunit.execution.desktop.dll - True - - - - - - - - - - - - - {a05c31e8-0246-46a1-b3bc-4d6fe7a9aa49} - Akka.Cluster.Sharding - - - {5CF8A8BE-B634-473F-BB01-EBA878746BD4} - Akka.Cluster.Tools - - - {3b9e6211-9488-4db5-b714-24248693b38f} - Akka.Persistence.Sql.Common - - - {453efd22-7c53-4887-9dbf-fcfc9172e909} - Akka.Persistence.Sqlite - - - {7dbd5c17-5e9d-40c4-9201-d092751532a7} - Akka.TestKit.Xunit2 - - - {f0781bea-5ba0-4af0-bb15-e3f209b681f5} - Akka.Cluster.Tests.MultiNode - - - {6ab00f61-269a-4501-b06a-026707f000a7} - Akka.Cluster - - - {fca84dea-c118-424b-9eb8-34375dfef18a} - Akka.Persistence - - - {e5957c3e-2b1e-469f-a680-7953b4dea31b} - Akka.Remote.TestKit - - - {c9105c76-b084-4da1-9348-1c74a8f22f6b} - Akka.Remote.Tests.MultiNode - - - {ea4ff8fd-7c53-49c8-b9aa-02e458b3e6a7} - Akka.Remote - - - {0d3cbad0-bbdb-43e5-afc4-ed1d3ecdc224} - Akka.TestKit - - - {5deddf90-37f0-48d3-a0b0-a5cbd8a7e377} - Akka - - - - - - - - \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Sharding.Tests/ClusterShardingFailureSpec.cs b/src/contrib/cluster/Akka.Cluster.Sharding.Tests/ClusterShardingFailureSpec.cs deleted file mode 100644 index 7971a2373d1..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Sharding.Tests/ClusterShardingFailureSpec.cs +++ /dev/null @@ -1,316 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using System.IO; -using System.Linq; -using Akka.Actor; -using Akka.Cluster.Tests.MultiNode; -using Akka.Configuration; -using Akka.Persistence.Journal; -using Akka.Remote.TestKit; -using Akka.Remote.Transport; -using Xunit; - -namespace Akka.Cluster.Sharding.Tests -{ - public class ClusterShardingFailureSpecConfig : MultiNodeConfig - { - public ClusterShardingFailureSpecConfig() - { - var controller = Role("controller"); - var first = Role("first"); - var second = Role("second"); - - CommonConfig = ConfigurationFactory.ParseString(@" - akka.loglevel = INFO - akka.actor.provider = ""Akka.Cluster.ClusterActorRefProvider"" - akka.remote.log-remote-lifecycle-events = off - akka.cluster.auto-down-unreachable-after = 0s - akka.cluster.down-removal-margin = 5s - akka.cluster.roles = [""backend""] - akka.persistence.journal.plugin = ""akka.persistence.journal.in-mem"" - akka.persistence.journal.in-mem { - timeout = 5s - store { - native = off - dir = ""target/journal-ClusterShardingFailureSpec"" - } - } - akka.persistence.snapshot-store.plugin = ""akka.persistence.snapshot-store.local"" - akka.persistence.snapshot-store.local.dir = ""target/snapshots-ClusterShardingFailureSpec"" - akka.cluster.sharding.coordinator-failure-backoff = 3s - akka.cluster.sharding.shard-failure-backoff = 3s - "); - - TestTransport = true; - } - } - - public class ClusterShardingFailureNode1 : ClusterShardingFailureSpec { } - public class ClusterShardingFailureNode2 : ClusterShardingFailureSpec { } - public class ClusterShardingFailureNode3 : ClusterShardingFailureSpec { } - - public abstract class ClusterShardingFailureSpec : MultiNodeClusterSpec - { - #region setup - - [Serializable] - internal sealed class Get - { - public readonly string Id; - public Get(string id) - { - Id = id; - } - } - - [Serializable] - internal sealed class Add - { - public readonly string Id; - public readonly int I; - public Add(string id, int i) - { - Id = id; - I = i; - } - } - - [Serializable] - internal sealed class Value - { - public readonly string Id; - public readonly int N; - public Value(string id, int n) - { - Id = id; - N = n; - } - } - - internal class Entity : ReceiveActor - { - private int _n = 0; - - public Entity() - { - Receive(get => Sender.Tell(new Value(get.Id, _n))); - Receive(add => _n += add.I); - } - } - - internal IdExtractor extractEntityId = message => - { - if (message is Get) return Tuple.Create((message as Get).Id, message); - if (message is Add) return Tuple.Create((message as Add).Id, message); - return null; - }; - - internal ShardResolver extractShardId = message => - { - if (message is Get) return (message as Get).Id[0].ToString(); - if (message is Add) return (message as Add).Id[0].ToString(); - return null; - }; - - private DirectoryInfo[] _storageLocations; - private Lazy _region; - private RoleName _first; - private RoleName _second; - private RoleName _controller; - - protected ClusterShardingFailureSpec() : base(new ClusterShardingFailureSpecConfig()) - { - _storageLocations = new[] - { - "akka.persistence.journal.leveldb.dir", - "akka.persistence.journal.leveldb-shared.store.dir", - "akka.persistence.snapshot-store.local.dir" - }.Select(s => new DirectoryInfo(Sys.Settings.Config.GetString(s))).ToArray(); - - _region = new Lazy(() => ClusterSharding.Get(Sys).ShardRegion("Entity")); - - _controller = new RoleName("controller"); - _first = new RoleName("first"); - _second = new RoleName("second"); - } - - - protected override void AtStartup() - { - base.AtStartup(); - RunOn(() => - { - foreach (var location in _storageLocations) if (location.Exists) location.Delete(); - }, _first); - } - - protected override void AfterTermination() - { - base.AfterTermination(); - RunOn(() => - { - foreach (var location in _storageLocations) if (location.Exists) location.Delete(); - }, _first); - } - - #endregion - - private void Join(RoleName from, RoleName to) - { - RunOn(() => - { - Cluster.Join(Node(to).Address); - StartSharding(); - }, from); - EnterBarrier(from.Name + "-joined"); - } - - private void StartSharding() - { - ClusterSharding.Get(Sys).Start( - typeName: "Entity", - entityProps: Props.Create(), - settings: ClusterShardingSettings.Create(Sys), - idExtractor: extractEntityId, - shardResolver: extractShardId); - } - - [MultiNodeFact(Skip = "TODO")] - public void ClusterSharding_with_flaky_journal_should_setup_shared_journal() - { - // start the Persistence extension - Persistence.Persistence.Instance.Apply(Sys); - RunOn(() => - { - Sys.ActorOf(Props.Create(), "store"); - }, _controller); - EnterBarrier("persistence-started"); - - RunOn(() => - { - Sys.ActorSelection(Node(_first) / "user" / "store").Tell(new Identify(null)); - var sharedStore = ExpectMsg().Subject; - //TODO: SharedLeveldbJournal.setStore(sharedStore, system) - }, _first, _second); - EnterBarrier("after-1"); - } - - [MultiNodeFact(Skip = "TODO")] - public void ClusterSharding_with_flaky_journal_should_join_cluster() - { - ClusterSharding_with_flaky_journal_should_setup_shared_journal(); - - Within(TimeSpan.FromSeconds(20), () => - { - Join(_first, _first); - Join(_second, _first); - - RunOn(() => - { - var region = _region.Value; - region.Tell(new Add("10", 1)); - region.Tell(new Add("20", 2)); - region.Tell(new Add("21", 3)); - region.Tell(new Get("10")); - ExpectMsg(v => v.Id == "10" && v.N == 1); - region.Tell(new Get("20")); - ExpectMsg(v => v.Id == "20" && v.N == 2); - region.Tell(new Get("21")); - ExpectMsg(v => v.Id == "21" && v.N == 3); - }, _first); - EnterBarrier("after-2"); - }); - } - - [MultiNodeFact(Skip = "TODO")] - public void ClusterSharding_with_flaky_journal_should_recover_after_journal_failure() - { - ClusterSharding_with_flaky_journal_should_join_cluster(); - - Within(TimeSpan.FromSeconds(20), () => - { - RunOn(() => - { - TestConductor.Blackhole(_controller, _first, ThrottleTransportAdapter.Direction.Both).Wait(); - TestConductor.Blackhole(_controller, _second, ThrottleTransportAdapter.Direction.Both).Wait(); - }, _controller); - EnterBarrier("journal-backholded"); - - RunOn(() => - { - // try with a new shard, will not reply until journal is available again - var region = _region.Value; - region.Tell(new Add("40", 4)); - var probe = CreateTestProbe(); - region.Tell(new Get("40"), probe.Ref); - probe.ExpectNoMsg(TimeSpan.FromSeconds(1)); - }, _first); - EnterBarrier("first-delayed"); - - RunOn(() => - { - TestConductor.PassThrough(_controller, _first, ThrottleTransportAdapter.Direction.Both).Wait(); - TestConductor.PassThrough(_controller, _second, ThrottleTransportAdapter.Direction.Both).Wait(); - }, _controller); - EnterBarrier("journal-ok"); - - RunOn(() => - { - var region = _region.Value; - region.Tell(new Get("21")); - ExpectMsg(v => v.Id == "21" && v.N == 3); - var entity21 = LastSender; - var shard2 = Sys.ActorSelection(entity21.Path.Parent); - - - //Test the PersistentShardCoordinator allocating shards during a journal failure - region.Tell(new Add("30", 3)); - - //Test the Shard starting entities and persisting during a journal failure - region.Tell(new Add("11", 1)); - - //Test the Shard passivate works during a journal failure - shard2.Tell(new ShardRegion.Passivate(PoisonPill.Instance), entity21); - region.Tell(new Add("21", 1)); - - region.Tell(new Get("21")); - ExpectMsg(v => v.Id == "21" && v.N == 1); - - region.Tell(new Get("30")); - ExpectMsg(v => v.Id == "30" && v.N == 3); - - region.Tell(new Get("11")); - ExpectMsg(v => v.Id == "11" && v.N == 1); - - region.Tell(new Get("40")); - ExpectMsg(v => v.Id == "40" && v.N == 4); - }, _first); - EnterBarrier("verified-first"); - - RunOn(() => - { - var region = _region.Value; - region.Tell(new Add("10", 1)); - region.Tell(new Add("20", 2)); - region.Tell(new Add("30", 3)); - region.Tell(new Add("11", 4)); - region.Tell(new Get("10")); - ExpectMsg(v => v.Id == "10" && v.N == 2); - region.Tell(new Get("11")); - ExpectMsg(v => v.Id == "11" && v.N == 5); - region.Tell(new Get("20")); - ExpectMsg(v => v.Id == "20" && v.N == 4); - region.Tell(new Get("30")); - ExpectMsg(v => v.Id == "30" && v.N == 6); - }, _second); - EnterBarrier("after-3"); - }); - } - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Sharding.Tests/ClusterShardingGracefulShutdownSpec.cs b/src/contrib/cluster/Akka.Cluster.Sharding.Tests/ClusterShardingGracefulShutdownSpec.cs deleted file mode 100644 index 6434035881e..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Sharding.Tests/ClusterShardingGracefulShutdownSpec.cs +++ /dev/null @@ -1,241 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using System.IO; -using System.Linq; -using Akka.Actor; -using Akka.Cluster.Tests.MultiNode; -using Akka.Configuration; -using Akka.Persistence.Journal; -using Akka.Remote.TestKit; -using Xunit; - -namespace Akka.Cluster.Sharding.Tests -{ - public class ClusterShardingGracefulShutdownSpecConfig : MultiNodeConfig - { - public ClusterShardingGracefulShutdownSpecConfig() - { - var first = Role("first"); - var second = Role("second"); - - CommonConfig = ConfigurationFactory.ParseString(@" - akka.loglevel = INFO - akka.actor.provider = ""Akka.Cluster.ClusterActorRefProvider"" - akka.remote.log-remote-lifecycle-events = off - akka.persistence.journal.plugin = ""Akka.Persistence.Journal.in-mem"" - akka.persistence.journal.in-mem { - timeout = 5s - store { - native = off - dir = ""target/journal-ClusterShardingGracefulShutdownSpec"" - } - } - akka.persistence.snapshot-store.plugin = ""akka.persistence.snapshot-store.local"" - akka.persistence.snapshot-store.local.dir = ""target/snapshots-ClusterShardingGracefulShutdownSpec"" - "); - } - } - - public class ClusterShardingGracefulShutdownNode1 : ClusterShardingGracefulShutdownSpec { } - public class ClusterShardingGracefulShutdownNode2 : ClusterShardingGracefulShutdownSpec { } - - public abstract class ClusterShardingGracefulShutdownSpec : MultiNodeClusterSpec - { - #region setup - - [Serializable] - internal sealed class StopEntity - { - public static readonly StopEntity Instance = new StopEntity(); - - private StopEntity() - { - } - } - - internal class Entity : ReceiveActor - { - public Entity() - { - Receive(id => Sender.Tell(id)); - Receive(_ => Context.Stop(Self)); - } - } - - internal class IllustrateGracefulShutdown : UntypedActor - { - private readonly Cluster _cluster; - private readonly IActorRef _region; - public IllustrateGracefulShutdown() - { - _cluster = Cluster.Get(Context.System); - _region = ClusterSharding.Get(Context.System).ShardRegion("Entity"); - } - - protected override void OnReceive(object message) - { - Terminated terminated; - if (message.Equals("leave")) - { - Context.Watch(_region); - _region.Tell(ShardRegion.GracefulShutdown.Instance); - } - else if ((terminated = message as Terminated) != null && terminated.ActorRef.Equals(_region)) - { - //_cluster.RegisterOnMemberRemoved(() => Context.System.Shutdown()); - _cluster.Leave(_cluster.SelfAddress); - } - } - } - - internal IdExtractor extractEntityId = message => message is int ? Tuple.Create(message.ToString(), message) : null; - - internal ShardResolver extractShardId = message => message is int ? message.ToString() : null; - - private readonly Lazy _region; - - private readonly DirectoryInfo[] _storageLocations; - private readonly RoleName _first; - private readonly RoleName _second; - - protected ClusterShardingGracefulShutdownSpec() : base(new ClusterShardingGracefulShutdownSpecConfig()) - { - _storageLocations = new[] - { - "akka.persistence.journal.leveldb.dir", - "akka.persistence.journal.leveldb-shared.store.dir", - "akka.persistence.snapshot-store.local.dir" - }.Select(s => new DirectoryInfo(Sys.Settings.Config.GetString(s))).ToArray(); - - _region = new Lazy(() => ClusterSharding.Get(Sys).ShardRegion("Entity")); - - _first = new RoleName("first"); - _second = new RoleName("second"); - } - - protected override void AtStartup() - { - base.AtStartup(); - RunOn(() => - { - foreach (var location in _storageLocations) if (location.Exists) location.Delete(); - }, _first); - } - - protected override void AfterTermination() - { - base.AfterTermination(); - RunOn(() => - { - foreach (var location in _storageLocations) if (location.Exists) location.Delete(); - }, _first); - } - - #endregion - - private void Join(RoleName from, RoleName to) - { - RunOn(() => - { - Cluster.Join(Node(to).Address); - StartSharding(); - }, from); - EnterBarrier(from.Name + "-joined"); - } - - private void StartSharding() - { - var allocationStrategy = new LeastShardAllocationStrategy(2, 1); - ClusterSharding.Get(Sys).Start( - typeName: "Entity", - entityProps: Props.Create(), - settings: ClusterShardingSettings.Create(Sys), - idExtractor: extractEntityId, - shardResolver: extractShardId, - allocationStrategy: allocationStrategy, - handOffStopMessage: StopEntity.Instance); - } - - [MultiNodeFact(Skip = "TODO")] - public void ClusterSharding_should_setup_shared_journal() - { - // start the Persistence extension - Persistence.Persistence.Instance.Apply(Sys); - RunOn(() => - { - Sys.ActorOf(Props.Create(), "store"); - }, _first); - EnterBarrier("persistence-started"); - - RunOn(() => - { - Sys.ActorSelection(Node(_first) / "user" / "store").Tell(new Identify(null)); - var sharedStore = ExpectMsg().Subject; - //TODO: SharedLeveldbJournal.setStore(sharedStore, system) - }, _first, _second); - EnterBarrier("after-1"); - } - - [MultiNodeFact(Skip = "TODO")] - public void ClusterSharding_should_start_some_shards_in_both_regions() - { - ClusterSharding_should_setup_shared_journal(); - - Join(_first, _first); - Join(_second, _first); - - AwaitAssert(() => - { - var probe = CreateTestProbe(); - var regionAddresses = Enumerable.Range(1, 100) - .Select(n => - { - _region.Value.Tell(n, probe.Ref); - probe.ExpectMsg(n, TimeSpan.FromSeconds(1)); - return probe.LastSender.Path.Address; - }) - .ToArray(); - - Assert.Equal(2, regionAddresses.Length); - }); - EnterBarrier("after-2"); - } - - [MultiNodeFact(Skip = "TODO")] - public void ClusterSharding_should_gracefully_shutdown_a_region() - { - ClusterSharding_should_start_some_shards_in_both_regions(); - - RunOn(() => - { - _region.Value.Tell(ShardRegion.GracefulShutdown.Instance); - }, _second); - - RunOn(() => - { - var probe = CreateTestProbe(); - for (int i = 1; i <= 200; i++) - { - _region.Value.Tell(i, probe.Ref); - probe.ExpectMsg(i, TimeSpan.FromSeconds(1)); - Assert.Equal(_region.Value.Path / i.ToString() / i.ToString(), probe.LastSender.Path); - } - }, _first); - EnterBarrier("handoff-completed"); - - RunOn(() => - { - var region = _region.Value; - Watch(region); - ExpectTerminated(region); - }, _second); - EnterBarrier("after-3"); - } - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Sharding.Tests/ClusterShardingLeavingSpec.cs b/src/contrib/cluster/Akka.Cluster.Sharding.Tests/ClusterShardingLeavingSpec.cs deleted file mode 100644 index 95aba86cd39..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Sharding.Tests/ClusterShardingLeavingSpec.cs +++ /dev/null @@ -1,288 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using Akka.Actor; -using Akka.Cluster.Tests.MultiNode; -using Akka.Configuration; -using Akka.Persistence.Journal; -using Akka.Remote.TestKit; -using Xunit; - -namespace Akka.Cluster.Sharding.Tests -{ - public class ClusterShardingLeavingSpecConfig : MultiNodeConfig - { - public ClusterShardingLeavingSpecConfig() - { - var first = Role("first"); - var second = Role("second"); - var third = Role("third"); - var fourth = Role("fourth"); - - CommonConfig = ConfigurationFactory.ParseString(@" - akka.loglevel = INFO - akka.actor.provider = ""Akka.Cluster.ClusterActorRefProvider"" - akka.remote.log-remote-lifecycle-events = off - akka.cluster.auto-down-unreachable-after = 0s - akka.cluster.down-removal-margin = 5s - akka.persistence.journal.plugin = ""Akka.Persistence.Journal.in-mem"" - akka.persistence.journal.in-mem { - timeout = 5s - store { - native = off - dir = ""target/journal-ClusterShardingLeavingSpec"" - } - } - akka.persistence.snapshot-store.plugin = ""akka.persistence.snapshot-store.local"" - akka.persistence.snapshot-store.local.dir = ""target/snapshots-ClusterShardingLeavingSpec"" - "); - } - } - - public class ClusterShardingLeavingNode1 : ClusterShardinLeavingSpec { } - public class ClusterShardingLeavingNode2 : ClusterShardinLeavingSpec { } - public class ClusterShardingLeavingNode3 : ClusterShardinLeavingSpec { } - public class ClusterShardingLeavingNode4 : ClusterShardinLeavingSpec { } - - public abstract class ClusterShardinLeavingSpec : MultiNodeClusterSpec - { - #region setup - - [Serializable] - internal sealed class Ping - { - public readonly string Id; - - public Ping(string id) - { - Id = id; - } - } - - [Serializable] - internal sealed class GetLocations - { - public static readonly GetLocations Instance = new GetLocations(); - - private GetLocations() - { - } - } - - [Serializable] - internal sealed class Locations - { - public readonly IDictionary LocationMap; - public Locations(IDictionary locationMap) - { - LocationMap = locationMap; - } - } - - internal class Entity : ReceiveActor - { - public Entity() - { - Receive(_ => Sender.Tell(Self)); - } - } - - internal class ShardLocations : ReceiveActor - { - private Locations _locations = null; - - public ShardLocations() - { - Receive(_ => Sender.Tell(_locations)); - Receive(l => _locations = l); - } - } - - internal IdExtractor extractEntityId = message => message is Ping ? Tuple.Create((message as Ping).Id, message) : null; - internal ShardResolver extractShardId = message => message is Ping ? (message as Ping).Id[0].ToString() : null; - - private readonly DirectoryInfo[] _storageLocations; - private readonly Lazy _region; - - private readonly RoleName _first; - private readonly RoleName _second; - private readonly RoleName _third; - private readonly RoleName _fourth; - - protected ClusterShardinLeavingSpec() : base(new ClusterShardingLeavingSpecConfig()) - { - _storageLocations = new[] - { - "akka.persistence.journal.leveldb.dir", - "akka.persistence.journal.leveldb-shared.store.dir", - "akka.persistence.snapshot-store.local.dir" - }.Select(s => new DirectoryInfo(Sys.Settings.Config.GetString(s))).ToArray(); - - _first = new RoleName("first"); - _second = new RoleName("second"); - _third = new RoleName("third"); - _fourth = new RoleName("fourth"); - - _region = new Lazy(() => ClusterSharding.Get(Sys).ShardRegion("Entity")); - } - - protected override int InitialParticipantsValueFactory { get { return Roles.Count; } } - - protected override void AtStartup() - { - base.AtStartup(); - RunOn(() => - { - foreach (var location in _storageLocations) if (location.Exists) location.Delete(); - }, _first); - } - - protected override void AfterTermination() - { - base.AfterTermination(); - RunOn(() => - { - foreach (var location in _storageLocations) if (location.Exists) location.Delete(); - }, _first); - } - - #endregion - - private void Join(RoleName from, RoleName to) - { - RunOn(() => - { - Cluster.Join(Node(to).Address); - StartSharding(); - Within(TimeSpan.FromSeconds(5), () => - { - AwaitAssert(() => Assert.True(Cluster.ReadView.State.Members.Any(m => m.UniqueAddress == Cluster.SelfUniqueAddress && m.Status == MemberStatus.Up))); - }); - }, from); - EnterBarrier(from.Name + "-joined"); - } - - private void StartSharding() - { - ClusterSharding.Get(Sys).Start( - typeName: "Entity", - entityProps: Props.Create(), - settings: ClusterShardingSettings.Create(Sys), - idExtractor: extractEntityId, - shardResolver: extractShardId); - } - - [MultiNodeFact(Skip = "TODO")] - public void ClusterSharding_with_leaving_member_should_setup_shared_journal() - { - // start the Persistence extension - Persistence.Persistence.Instance.Apply(Sys); - RunOn(() => - { - Sys.ActorOf(Props.Create(), "store"); - }, _first); - EnterBarrier("persistence-started"); - - Sys.ActorSelection(Node(_first) / "user" / "store").Tell(new Identify(null)); - var sharedStore = ExpectMsg().Subject; - - //SharedLeveldbJournal.setStore(sharedStore, system) - EnterBarrier("after-1"); - } - - [MultiNodeFact(Skip = "TODO")] - public void ClusterSharding_with_leaving_member_should_join_cluster() - { - ClusterSharding_with_leaving_member_should_setup_shared_journal(); - - Within(TimeSpan.FromSeconds(20), () => - { - Join(_first, _first); - Join(_second, _first); - Join(_third, _first); - Join(_fourth, _first); - - EnterBarrier("after-2"); - }); - } - - [MultiNodeFact(Skip = "TODO")] - public void ClusterSharding_with_leaving_member_should_initialize_shards() - { - ClusterSharding_with_leaving_member_should_join_cluster(); - - RunOn(() => - { - var shardLocations = Sys.ActorOf(Props.Create(), "shardLocations"); - var locations = Enumerable.Range(1, 10) - .Select(n => - { - var id = n.ToString(); - _region.Value.Tell(new Ping(id)); - return new KeyValuePair(id, ExpectMsg()); - }) - .ToDictionary(kv => kv.Key, kv => kv.Value); - - shardLocations.Tell(new Locations(locations)); - }, _first); - EnterBarrier("after-3"); - } - - [MultiNodeFact(Skip = "TODO")] - public void ClusterSharding_with_leaving_member_should_recover_after_leaving_coordinator_node() - { - ClusterSharding_with_leaving_member_should_initialize_shards(); - - Within(TimeSpan.FromSeconds(30), () => - { - RunOn(() => - { - Cluster.Leave(Node(_first).Address); - }, _third); - - RunOn(() => - { - var region = _region.Value; - Watch(region); - ExpectTerminated(region, TimeSpan.FromSeconds(15)); - }, _first); - EnterBarrier("stopped"); - - RunOn(() => - { - Sys.ActorSelection(Node(_first) / "user" / "sharedLocations").Tell(GetLocations.Instance); - var locations = ExpectMsg(); - var firstAddress = Node(_first).Address; - AwaitAssert(() => - { - var region = _region.Value; - var probe = CreateTestProbe(); - foreach (var kv in locations.LocationMap) - { - var id = kv.Key; - var r = kv.Value; - region.Tell(new Ping(id), probe.Ref); - if (r.Path.Address.Equals(firstAddress)) - { - Assert.NotEqual(r, probe.ExpectMsg(TimeSpan.FromSeconds(1))); - } - else - { - probe.ExpectMsg(r, TimeSpan.FromSeconds(1)); // should not move - } - } - }); - }, _second, _third, _fourth); - EnterBarrier("after-4"); - }); - } - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Sharding.Tests/ClusterShardingSpec.cs b/src/contrib/cluster/Akka.Cluster.Sharding.Tests/ClusterShardingSpec.cs deleted file mode 100644 index f727619722d..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Sharding.Tests/ClusterShardingSpec.cs +++ /dev/null @@ -1,1090 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading; -using Akka.Cluster.Sharding; -using Akka.Configuration; -using Akka.Persistence; -using Akka.Remote.TestKit; -using Akka.Actor; -using Akka.Cluster.Tests.MultiNode; -using Akka.Cluster.Tools.Singleton; -using Akka.Pattern; -using Akka.Persistence.Journal; -using Akka.TestKit; -using Akka.TestKit.Internal.StringMatcher; -using Akka.TestKit.TestEvent; -using Xunit; - -namespace Akka.Cluster.Sharding.Tests -{ - public class ClusterShardingSpecConfig : MultiNodeConfig - { - public ClusterShardingSpecConfig() - { - var controller = Role("controller"); - var first = Role("first"); - var second = Role("second"); - var third = Role("third"); - var fourth = Role("fourth"); - var fifth = Role("fifth"); - var sixth = Role("sixth"); - - CommonConfig = ConfigurationFactory.ParseString(@" - akka.loglevel = INFO - akka.actor.provider = ""Akka.Cluster.ClusterActorRefProvider"" - akka.remote.log-remote-lifecycle-events = off - akka.cluster.auto-down-unreachable-after = 0s - akka.cluster.down-removal-margin = 5s - akka.cluster.roles = [""backend""] - akka.persistence.journal.plugin = ""akka.persistence.journal.leveldb-shared"" - akka.persistence.journal.leveldb-shared.store { - native = off - dir = ""target/journal-ClusterShardingSpec"" - } - akka.persistence.snapshot-store.plugin = ""akka.persistence.snapshot-store.local"" - akka.persistence.snapshot-store.local.dir = ""target/snapshots-ClusterShardingSpec"" - akka.cluster.sharding { - retry-interval = 1 s - handoff-timeout = 10 s - shard-start-timeout = 5s - entity-restart-backoff = 1s - rebalance-interval = 2 s - least-shard-allocation-strategy { - rebalance-threshold = 2 - max-simultaneous-rebalance = 1 - } - }"); - - NodeConfig(new[] { sixth }, new[] { ConfigurationFactory.ParseString(@"akka.cluster.roles = [""frontend""]") }); - } - } - - internal class Counter : PersistentActor - { - #region messages - - [Serializable] - public sealed class Increment - { - public static readonly Increment Instance = new Increment(); - - private Increment() - { - } - } - - [Serializable] - public sealed class Decrement - { - public static readonly Decrement Instance = new Decrement(); - - private Decrement() - { - } - } - - [Serializable] - public sealed class Get - { - public readonly long CounterId; - public Get(long counterId) - { - CounterId = counterId; - } - } - - [Serializable] - public sealed class EntityEnvelope - { - public readonly long Id; - public readonly object Payload; - public EntityEnvelope(long id, object payload) - { - Id = id; - Payload = payload; - } - } - - [Serializable] - public sealed class CounterChanged - { - public readonly int Delta; - public CounterChanged(int delta) - { - Delta = delta; - } - } - - [Serializable] - public sealed class Stop - { - public static readonly Stop Instance = new Stop(); - - private Stop() - { - } - } - - #endregion - - public static readonly IdExtractor ExtractEntityId = message => - { - if (message is EntityEnvelope) - { - var env = (EntityEnvelope)message; - return Tuple.Create(env.Id.ToString(), env.Payload); - } - if (message is Get) - { - return Tuple.Create(((Get)message).CounterId.ToString(), message); - } - return null; - }; - - public static readonly ShardResolver ExtractShardId = message => - { - if (message is EntityEnvelope) - return (((EntityEnvelope)message).Id % ShardsCount).ToString(); - if (message is Get) - return (((Get)message).CounterId % ShardsCount).ToString(); - return null; - - }; - - public const int ShardsCount = 12; - private int _count = 0; - - public Counter() - { - Context.SetReceiveTimeout(TimeSpan.FromMinutes(2)); - } - - protected override void PostStop() - { - base.PostStop(); - // Simulate that the passivation takes some time, to verify passivation buffering - Thread.Sleep(500); - } - - public override string PersistenceId { get { return Self.Path.Parent.Name + "-" + Self.Path.Name; } } - protected override bool ReceiveRecover(object message) - { - return message.Match() - .With(UpdateState) - .WasHandled; - } - - protected override bool ReceiveCommand(object message) - { - return message.Match() - .With(_ => Persist(new CounterChanged(1), UpdateState)) - .With(_ => Persist(new CounterChanged(-1), UpdateState)) - .With(_ => Sender.Tell(_count)) - .With(_ => Context.Parent.Tell(new ShardRegion.Passivate(Stop.Instance))) - .With(_ => Context.Stop(Self)) - .WasHandled; - } - - private void UpdateState(CounterChanged e) - { - _count += e.Delta; - } - } - public class ClusterShardingNode1 : ClusterShardingSpec { } - public class ClusterShardingNode2 : ClusterShardingSpec { } - public class ClusterShardingNode3 : ClusterShardingSpec { } - - public abstract class ClusterShardingSpec : MultiNodeClusterSpec - { - #region Setup - - private readonly DirectoryInfo[] _storageLocations; - private readonly RoleName _controller; - private readonly RoleName _second; - private readonly RoleName _first; - private readonly RoleName _third; - private readonly RoleName _fourth; - private readonly RoleName _sixth; - private readonly RoleName _fifth; - - private readonly Lazy _region; - private readonly Lazy _rebalancingRegion; - private readonly Lazy _persistentEntitiesRegion; - private readonly Lazy _anotherPersistentRegion; - private readonly Lazy _persistentRegion; - private readonly Lazy _rebalancingPersistentRegion; - private readonly Lazy _autoMigrateRegion; - - protected ClusterShardingSpec() : base(new ClusterShardingSpecConfig()) - { - _storageLocations = new[] - { - "akka.persistence.journal.leveldb.dir", - "akka.persistence.journal.leveldb-shared.store.dir", - "akka.persistence.snapshot-store.local.dir" - }.Select(s => new DirectoryInfo(Sys.Settings.Config.GetString(s))).ToArray(); - - _controller = new RoleName("controller"); - _first = new RoleName("first"); - _second = new RoleName("second"); - _third = new RoleName("third"); - _fourth = new RoleName("fourth"); - _fifth = new RoleName("fifth"); - _sixth = new RoleName("sixth"); - - _region = new Lazy(() => CreateRegion("counter", false)); - _rebalancingRegion = new Lazy(() => CreateRegion("rebalancingCounter", false)); - - _persistentEntitiesRegion = new Lazy(() => CreateRegion("PersistentCounterEntities", true)); - _anotherPersistentRegion = new Lazy(() => CreateRegion("AnotherPersistentCounter", true)); - _persistentRegion = new Lazy(() => CreateRegion("PersistentCounter", true)); - _rebalancingPersistentRegion = new Lazy(() => CreateRegion("RebalancingPersistentCounter", true)); - _autoMigrateRegion = new Lazy(() => CreateRegion("AutoMigrateRegionTest", true)); - } - - protected override int InitialParticipantsValueFactory { get { return Roles.Count; } } - - protected override void AtStartup() - { - base.AtStartup(); - RunOn(() => - { - foreach (var dir in _storageLocations) - { - if (dir.Exists) dir.Delete(); - } - }, _controller); - } - - protected override void AfterTermination() - { - base.AfterTermination(); - RunOn(() => - { - foreach (var dir in _storageLocations) - { - if (dir.Exists) dir.Delete(); - } - }, _controller); - } - - private void Join(RoleName from, RoleName to) - { - RunOn(() => - { - Cluster.Join(Node(to).Address); - }, from); - - EnterBarrier(from.Name + "-joined"); - } - - private void CreateCoordinator() - { - var typeNames = new[] - { - "counter", "rebalancingCounter", "PersistentCounterEntities", "AnotherPersistentCounter", - "PersistentCounter", "RebalancingPersistentCounter", "AutoMigrateRegionTest" - }; - - foreach (var typeName in typeNames) - { - var rebalanceEnabled = string.Equals(typeName, "rebalancing", StringComparison.InvariantCultureIgnoreCase); - var singletonProps = Props.Create(() => new BackoffSupervisor( - CoordinatorProps(typeName, rebalanceEnabled), - "coordinator", - TimeSpan.FromSeconds(5), - TimeSpan.FromSeconds(5), - 0.1)).WithDeploy(Deploy.Local); - - Sys.ActorOf(ClusterSingletonManager.Props( - singletonProps, - PoisonPill.Instance, - ClusterSingletonManagerSettings.Create(Sys)), - typeName + "Coordinator"); - } - } - - private Props CoordinatorProps(string typeName, bool rebalanceEntities) - { - var allocationStrategy = new LeastShardAllocationStrategy(2, 1); - var config = ConfigurationFactory.ParseString(string.Format("")); - var settings = ClusterShardingSettings.Create(config, Sys.Settings.Config.GetConfig("akka.cluster.singleton")); - - return PersistentShardCoordinator.Props(typeName, settings, allocationStrategy); - } - - private IActorRef CreateRegion(string typeName, bool rememberEntities) - { - var config = ConfigurationFactory.ParseString(@" - retry-interval = 1s - shard-failure-backoff = 1s - entity-restart-backoff = 1s - buffer-size = 1000").WithFallback(Sys.Settings.Config.GetConfig("akka.cluster.sharding")); - var settings = ClusterShardingSettings.Create(config, Sys.Settings.Config.GetConfig("akka.cluster.singleton")).WithRememberEntities(rememberEntities); - - return Sys.ActorOf(Props.Create(() => new ShardRegion( - typeName, - Props.Create(), - settings, - "/user/" + typeName + "Coordinator/singleton/coordinator", - Counter.ExtractEntityId, - Counter.ExtractShardId, - PoisonPill.Instance)), - typeName + "Region"); - } - - #endregion - - #region Cluster shardings specs - - [MultiNodeFact(Skip = "TODO")] - public void ClusterSharding_should_setup_shared_journal() - { - // start the Persistence extension - Persistence.Persistence.Instance.Apply(Sys); - RunOn(() => Sys.ActorOf("store"), _controller); - EnterBarrier("persistence-started"); - - RunOn(() => - { - Sys.ActorSelection(Node(_controller) / "user" / "store").Tell(new Identify(null)); - var sharedStore = ExpectMsg().Subject; - //SharedLeveldbJournal.setStore(sharedStore, system) - }, _first, _second, _third, _fourth, _fifth, _sixth); - - EnterBarrier("after-1"); - } - - [MultiNodeFact(Skip = "TODO")] - public void ClusterSharding_should_work_in_single_node_cluster() - { - ClusterSharding_should_setup_shared_journal(); - - Within(TimeSpan.FromSeconds(20), () => - { - Join(_first, _first); - - RunOn(() => - { - var r = _region.Value; - r.Tell(new Counter.EntityEnvelope(1, Counter.Increment.Instance)); - r.Tell(new Counter.EntityEnvelope(1, Counter.Increment.Instance)); - r.Tell(new Counter.EntityEnvelope(1, Counter.Increment.Instance)); - r.Tell(new Counter.EntityEnvelope(1, Counter.Decrement.Instance)); - r.Tell(new Counter.Get(1)); - - ExpectMsg(2); - r.Tell(ShardRegion.GetCurrentRegions.Instance); - ExpectMsg(m => m.Regions.Length == 1 && m.Regions[0].Equals(Cluster.SelfAddress)); - }, _first); - - EnterBarrier("after-2"); - }); - } - - [MultiNodeFact(Skip = "TODO")] - public void ClusterSharding_should_use_second_node() - { - ClusterSharding_should_work_in_single_node_cluster(); - - Within(TimeSpan.FromSeconds(20), () => - { - Join(_second, _first); - - RunOn(() => - { - var r = _region.Value; - r.Tell(new Counter.EntityEnvelope(2, Counter.Increment.Instance)); - r.Tell(new Counter.EntityEnvelope(2, Counter.Increment.Instance)); - r.Tell(new Counter.EntityEnvelope(2, Counter.Increment.Instance)); - r.Tell(new Counter.EntityEnvelope(2, Counter.Decrement.Instance)); - r.Tell(new Counter.Get(2)); - - ExpectMsg(2); - - r.Tell(new Counter.EntityEnvelope(11, Counter.Increment.Instance)); - r.Tell(new Counter.EntityEnvelope(12, Counter.Increment.Instance)); - r.Tell(new Counter.Get(11)); - ExpectMsg(1); - r.Tell(new Counter.Get(12)); - ExpectMsg(1); - }, _second); - EnterBarrier("second-update"); - - RunOn(() => - { - var r = _region.Value; - r.Tell(new Counter.EntityEnvelope(2, Counter.Increment.Instance)); - r.Tell(new Counter.Get(2)); - ExpectMsg(3); - Assert.Equal(Node(_second) / "user" / "counterRegion" / "2" / "2", LastSender.Path); - - r.Tell(new Counter.Get(11)); - ExpectMsg(1); - // local on first - Assert.Equal(r.Path / "11" / "11", LastSender.Path); - r.Tell(new Counter.Get(12)); - ExpectMsg(1); - Assert.Equal(Node(_second) / "user" / "counterRegion" / "0" / "12", LastSender.Path); - }, _first); - EnterBarrier("first-update"); - - RunOn(() => - { - var r = _region.Value; - r.Tell(new Counter.Get(2)); - ExpectMsg(3); - Assert.Equal(r.Path / "2" / "2", LastSender.Path); - - r.Tell(ShardRegion.GetCurrentRegions.Instance); - ExpectMsg(x => x.Regions.Length == 2 - && x.Regions[0].Equals(Cluster.SelfAddress) - && x.Regions[1].Equals(Node(_first).Address)); - }, _second); - EnterBarrier("after-3"); - }); - } - - [MultiNodeFact(Skip = "TODO")] - public void ClusterSharding_should_support_passivation_and_activation_of_entities() - { - ClusterSharding_should_use_second_node(); - - RunOn(() => - { - var r = _region.Value; - r.Tell(new Counter.Get(2)); - ExpectMsg(3); //TODO: shouldn't we tell increment 3x first? - r.Tell(new Counter.EntityEnvelope(2, ReceiveTimeout.Instance)); - // let the Passivate-Stop roundtrip begin to trigger buffering of subsequent messages - Thread.Sleep(200); - r.Tell(new Counter.EntityEnvelope(2, Counter.Increment.Instance)); - r.Tell(new Counter.Get(2)); - ExpectMsg(4); - }, _second); - EnterBarrier("after-4"); - } - - [MultiNodeFact(Skip = "TODO")] - public void ClusterSharding_should_support_proxy_only_mode() - { - ClusterSharding_should_support_passivation_and_activation_of_entities(); - - Within(TimeSpan.FromSeconds(10), () => - { - RunOn(() => - { - var cfg = ConfigurationFactory.ParseString(@" - retry-interval = 1s - buffer-size = 1000") - .WithFallback(Sys.Settings.Config.GetConfig("akka.cluster.sharding")); - - var settings = ClusterShardingSettings.Create(cfg, Sys.Settings.Config.GetConfig("akka.cluster.singleton")); - var proxy = Sys.ActorOf(ShardRegion.ProxyProps( - typeName: "counter", - settings: settings, - coordinatorPath: "/user/counterCoordinator/singleton/coordinator", - extractEntityId: Counter.ExtractEntityId, - extractShardId: Counter.ExtractShardId)); - - proxy.Tell(new Counter.EntityEnvelope(1, Counter.Increment.Instance)); - proxy.Tell(new Counter.EntityEnvelope(1, Counter.Increment.Instance)); - proxy.Tell(new Counter.EntityEnvelope(2, Counter.Increment.Instance)); - proxy.Tell(new Counter.EntityEnvelope(2, Counter.Increment.Instance)); - proxy.Tell(new Counter.EntityEnvelope(2, Counter.Increment.Instance)); - proxy.Tell(new Counter.EntityEnvelope(2, Counter.Increment.Instance)); - - proxy.Tell(new Counter.Get(1)); - ExpectMsg(2); - proxy.Tell(new Counter.Get(2)); - ExpectMsg(4); - }, _second); - EnterBarrier("after-5"); - }); - } - - [MultiNodeFact(Skip = "TODO")] - public void ClusterSharding_should_failover_shards_on_crashed_node() - { - ClusterSharding_should_support_proxy_only_mode(); - - Within(TimeSpan.FromSeconds(30), () => - { - // mute logging of deadLetters during shutdown of systems - if (!Log.IsDebugEnabled) Sys.EventStream.Publish(new Mute(new DeadLettersFilter(new PredicateMatcher(x => true), new PredicateMatcher(x => true)))); - EnterBarrier("logs-muted"); - - RunOn(() => - { - TestConductor.Exit(_second, 0).Wait(); - }, _controller); - EnterBarrier("crash-second"); - - RunOn(() => - { - var probe1 = CreateTestProbe(); - AwaitAssert(() => - { - Within(TimeSpan.FromSeconds(1), () => - { - var r = _region.Value; - r.Tell(new Counter.Get(2), probe1.Ref); - probe1.ExpectMsg(4); - Assert.Equal(r.Path / "2" / "2", probe1.LastSender.Path); - }); - }); - - var probe2 = CreateTestProbe(); - AwaitAssert(() => - { - Within(TimeSpan.FromSeconds(1), () => - { - var r = _region.Value; - r.Tell(new Counter.Get(12), probe2.Ref); - probe2.ExpectMsg(1); - Assert.Equal(r.Path / "0" / "12", probe2.LastSender.Path); - }); - }); - }, _first); - EnterBarrier("after-6"); - }); - } - - [MultiNodeFact(Skip = "TODO")] - public void ClusterSharding_should_use_third_and_fourth_node() - { - ClusterSharding_should_failover_shards_on_crashed_node(); - - Within(TimeSpan.FromSeconds(15), () => - { - Join(_third, _first); - Join(_fourth, _first); - - RunOn(() => - { - var r = _region.Value; - for (int i = 0; i < 10; i++) - r.Tell(new Counter.EntityEnvelope(3, Counter.Increment.Instance)); - - r.Tell(new Counter.Get(3)); - ExpectMsg(10); - Assert.Equal(r.Path / "3" / "3", LastSender.Path); - }, _third); - EnterBarrier("third-update"); - - RunOn(() => - { - var r = _region.Value; - for (int i = 0; i < 20; i++) - r.Tell(new Counter.EntityEnvelope(4, Counter.Increment.Instance)); - - r.Tell(new Counter.Get(4)); - ExpectMsg(20); - Assert.Equal(r.Path / "4" / "4", LastSender.Path); - }, _fourth); - EnterBarrier("fourth-update"); - - RunOn(() => - { - var r = _region.Value; - r.Tell(new Counter.EntityEnvelope(3, Counter.Increment.Instance)); - r.Tell(new Counter.Get(3)); - ExpectMsg(11); - Assert.Equal(Node(_third) / "user" / "counterRegion" / "3" / "3", LastSender.Path); - - r.Tell(new Counter.EntityEnvelope(4, Counter.Increment.Instance)); - r.Tell(new Counter.Get(4)); - ExpectMsg(21); - Assert.Equal(Node(_third) / "user" / "counterRegion" / "4" / "4", LastSender.Path); - }, _first); - EnterBarrier("first-update"); - - RunOn(() => - { - var r = _region.Value; - r.Tell(new Counter.Get(3)); - ExpectMsg(11); - Assert.Equal(r.Path / "3" / "3", LastSender.Path); - }, _third); - - RunOn(() => - { - var r = _region.Value; - r.Tell(new Counter.Get(4)); - ExpectMsg(21); - Assert.Equal(r.Path / "4" / "4", LastSender.Path); - }, _fourth); - EnterBarrier("after-7"); - }); - } - - [MultiNodeFact(Skip = "TODO")] - public void ClusterSharding_should_recover_coordinator_state_after_coordinator_crash() - { - ClusterSharding_should_use_third_and_fourth_node(); - - Within(TimeSpan.FromSeconds(60), () => - { - Join(_fifth, _fourth); - RunOn(() => - { - TestConductor.Exit(_first, 0).Wait(); - }, _controller); - EnterBarrier("crash-first"); - - RunOn(() => - { - var probe3 = CreateTestProbe(); - AwaitAssert(() => - { - Within(TimeSpan.FromSeconds(1), () => - { - _region.Value.Tell(new Counter.Get(3), probe3.Ref); - probe3.ExpectMsg(11); - Assert.Equal(Node(_third) / "user" / "counterRegion" / "3" / "3", probe3.LastSender.Path); - }); - }); - - var probe4 = CreateTestProbe(); - AwaitAssert(() => - { - Within(TimeSpan.FromSeconds(1), () => - { - _region.Value.Tell(new Counter.Get(4), probe4.Ref); - probe4.ExpectMsg(21); - Assert.Equal(Node(_fourth) / "user" / "counterRegion" / "4" / "4", probe4.LastSender.Path); - }); - }); - }, _fifth); - EnterBarrier("after-8"); - }); - } - - [MultiNodeFact(Skip = "TODO")] - public void ClusterSharding_should_rebalance_to_nodes_with_less_shards() - { - ClusterSharding_should_recover_coordinator_state_after_coordinator_crash(); - - Within(TimeSpan.FromSeconds(60), () => - { - RunOn(() => - { - for (int i = 1; i <= 10; i++) - { - var rebalancingRegion = _rebalancingRegion.Value; - rebalancingRegion.Tell(new Counter.EntityEnvelope(i, Counter.Increment.Instance)); - rebalancingRegion.Tell(new Counter.Get(i)); - ExpectMsg(1); - } - }, _fourth); - EnterBarrier("rebalancing-shards-allocated"); - - Join(_sixth, _third); - - RunOn(() => - { - AwaitAssert(() => - { - var probe = CreateTestProbe(); - Within(TimeSpan.FromSeconds(3), () => - { - var count = 0; - for (int i = 1; i <= 10; i++) - { - var rebalancingRegion = _rebalancingRegion.Value; - rebalancingRegion.Tell(new Counter.Get(i), probe.Ref); - probe.ExpectMsg(); - if (probe.LastSender.Path.Equals(rebalancingRegion.Path / (i % 12).ToString() / i.ToString())) - count++; - } - - Assert.True(count >= 2); - }); - }); - }, _sixth); - EnterBarrier("after-9"); - }); - } - - [MultiNodeFact(Skip = "TODO")] - public void ClusterSharding_should_be_easy_to_use_with_extensions() - { - ClusterSharding_should_rebalance_to_nodes_with_less_shards(); - - Within(TimeSpan.FromSeconds(50), () => - { - RunOn(() => - { - //#counter-start - ClusterSharding.Get(Sys).Start( - typeName: "Counter", - entityProps: Props.Create(), - settings: ClusterShardingSettings.Create(Sys), - idExtractor: Counter.ExtractEntityId, - shardResolver: Counter.ExtractShardId); - - //#counter-start - ClusterSharding.Get(Sys).Start( - typeName: "AnotherCounter", - entityProps: Props.Create(), - settings: ClusterShardingSettings.Create(Sys), - idExtractor: Counter.ExtractEntityId, - shardResolver: Counter.ExtractShardId); - }, _third, _fourth, _fifth, _sixth); - EnterBarrier("extension-started"); - - RunOn(() => - { - //#counter-usage - var counterRegion = ClusterSharding.Get(Sys).ShardRegion("Counter"); - counterRegion.Tell(new Counter.Get(123)); - ExpectMsg(0); - - counterRegion.Tell(new Counter.EntityEnvelope(123, Counter.Increment.Instance)); - counterRegion.Tell(new Counter.Get(123)); - ExpectMsg(1); - - //#counter-usage - var anotherCounterRegion = ClusterSharding.Get(Sys).ShardRegion("AnotherCounter"); - anotherCounterRegion.Tell(new Counter.EntityEnvelope(123, Counter.Decrement.Instance)); - anotherCounterRegion.Tell(new Counter.Get(123)); - ExpectMsg(-1); - }, _fifth); - EnterBarrier("extension-used"); - - // sixth is a frontend node, i.e. proxy only - RunOn(() => - { - for (int i = 1000; i <= 1010; i++) - { - ClusterSharding.Get(Sys).ShardRegion("Counter").Tell(new Counter.EntityEnvelope(i, Counter.Increment.Instance)); - ClusterSharding.Get(Sys).ShardRegion("Counter").Tell(new Counter.Get(i)); - ExpectMsg(1); - Assert.NotEqual(Cluster.SelfAddress, LastSender.Path.Address); - } - }, _sixth); - EnterBarrier("after-10"); - }); - } - - [MultiNodeFact(Skip = "TODO")] - public void ClusterSharding_should_be_easy_API_for_starting() - { - ClusterSharding_should_be_easy_to_use_with_extensions(); - - Within(TimeSpan.FromSeconds(50), () => - { - RunOn(() => - { - var counterRegionViaStart = ClusterSharding.Get(Sys).Start( - typeName: "ApiTest", - entityProps: Props.Create(), - settings: ClusterShardingSettings.Create(Sys), - idExtractor: Counter.ExtractEntityId, - shardResolver: Counter.ExtractShardId); - - var counterRegionViaGet = ClusterSharding.Get(Sys).ShardRegion("ApiTest"); - - Assert.Equal(counterRegionViaGet, counterRegionViaStart); - }, _first); - EnterBarrier("after-11"); - }); - } - - #endregion - - #region Persistent cluster shards specs - - [MultiNodeFact(Skip = "TODO")] - public void Persistent_cluster_shards_should_recover_entities_upon_restart() - { - Within(TimeSpan.FromSeconds(50), () => - { - RunOn(() => - { - var x = _persistentEntitiesRegion.Value; - var y = _anotherPersistentRegion.Value; - }, _third, _fourth, _fifth); - EnterBarrier("persistent-start"); - - RunOn(() => - { - //Create an increment counter 1 - _persistentEntitiesRegion.Value.Tell(new Counter.EntityEnvelope(1, Counter.Increment.Instance)); - _persistentEntitiesRegion.Value.Tell(new Counter.EntityEnvelope(1, new Counter.Get(1))); - ExpectMsg(1); - - //Shut down the shard and confirm it's dead - var shard = Sys.ActorSelection(LastSender.Path.Parent); - var region = Sys.ActorSelection(LastSender.Path.Parent.Parent); - - // stop shard - region.Tell(new PersistentShardCoordinator.HandOff("1")); - ExpectMsg(s => s.Shard == "1", TimeSpan.FromSeconds(10)); - - var probe = CreateTestProbe(); - AwaitAssert(() => - { - shard.Tell(new Identify(1), probe.Ref); - probe.ExpectMsg(i => i.MessageId.Equals(1) && i.Subject == null, TimeSpan.FromSeconds(1)); - }, TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(500)); - - //Get the path to where the shard now resides - _persistentEntitiesRegion.Value.Tell(new Counter.Get(13)); - ExpectMsg(0); - - //Check that counter 1 is now alive again, even though we have - // not sent a message to it via the ShardRegion - var counter1 = Sys.ActorSelection(LastSender.Path.Parent / "1"); - counter1.Tell(new Identify(2)); - Assert.NotNull(ExpectMsg(TimeSpan.FromSeconds(3)).Subject); - - counter1.Tell(new Counter.Get(1)); - ExpectMsg(1); - }, _third); - EnterBarrier("after-shard-restart"); - - RunOn(() => - { - //Check a second region does not share the same persistent shards - - //Create a separate 13 counter - _anotherPersistentRegion.Value.Tell(new Counter.EntityEnvelope(13, Counter.Increment.Instance)); - _anotherPersistentRegion.Value.Tell(new Counter.Get(13)); - ExpectMsg(1); - - //Check that no counter "1" exists in this shard - var secondCounter1 = Sys.ActorSelection(LastSender.Path.Parent / "1"); - secondCounter1.Tell(new Identify(3)); - ExpectMsg(i => i.MessageId.Equals(3) && i.Subject == null, TimeSpan.FromSeconds(3)); - }, _fourth); - EnterBarrier("after-12"); - }); - } - - [MultiNodeFact(Skip = "TODO")] - public void Persistent_cluster_shards_should_permanently_stop_entities_which_passivate() - { - Persistent_cluster_shards_should_recover_entities_upon_restart(); - - Within(TimeSpan.FromSeconds(15), () => - { - RunOn(() => - { - var x = _persistentRegion.Value; - }, _third, _fourth, _fifth); - EnterBarrier("cluster-started-12"); - - RunOn(() => - { - //create and increment counter 1 - _persistentRegion.Value.Tell(new Counter.EntityEnvelope(1, Counter.Increment.Instance)); - _persistentRegion.Value.Tell(new Counter.Get(1)); - ExpectMsg(1); - - var counter1 = LastSender; - var shard = Sys.ActorSelection(counter1.Path.Parent); - var region = Sys.ActorSelection(counter1.Path.Parent.Parent); - - //create and increment counter 13 - _persistentRegion.Value.Tell(new Counter.EntityEnvelope(13, Counter.Increment.Instance)); - _persistentRegion.Value.Tell(new Counter.Get(13)); - ExpectMsg(1); - - var counter13 = LastSender; - - Assert.Equal(counter1.Path.Parent, counter13.Path.Parent); - - //Send the shard the passivate message from the counter - Watch(counter1); - shard.Tell(new ShardRegion.Passivate(Counter.Stop.Instance), counter1); - - // watch for the Terminated message - ExpectTerminated(counter1, TimeSpan.FromSeconds(5)); - - var probe1 = CreateTestProbe(); - AwaitAssert(() => - { - // check counter 1 is dead - counter1.Tell(new Identify(1), probe1.Ref); - probe1.ExpectMsg(i => i.MessageId.Equals(1) && i.Subject == null, TimeSpan.FromSeconds(1)); - }, TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(500)); - - // stop shard cleanly - region.Tell(new PersistentShardCoordinator.HandOff("1")); - ExpectMsg(s => s.Shard == "1", TimeSpan.FromSeconds(10)); - - var probe2 = CreateTestProbe(); - AwaitAssert(() => - { - shard.Tell(new Identify(2), probe2.Ref); - probe1.ExpectMsg(i => i.MessageId.Equals(1) && i.Subject == null, TimeSpan.FromSeconds(1)); - }, TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(500)); - - }, _third); - EnterBarrier("shard-shutdonw-12"); - - RunOn(() => - { - // force shard backup - _persistentRegion.Value.Tell(new Counter.Get(25)); - ExpectMsg(0); - - var shard = LastSender.Path.Parent; - - // check counter 1 is still dead - Sys.ActorSelection(shard / "1").Tell(new Identify(3)); - ExpectMsg(i => i.MessageId.Equals(3) && i.Subject == null); - - // check counter 13 is alive again - Sys.ActorSelection(shard / "13").Tell(new Identify(4)); - ExpectMsg(i => i.MessageId.Equals(4) && i.Subject != null); - - }, _fourth); - EnterBarrier("after-13"); - }); - } - - [MultiNodeFact(Skip = "TODO")] - public void Persistent_cluster_shards_should_restart_entities_which_stop_without_passivation() - { - Persistent_cluster_shards_should_permanently_stop_entities_which_passivate(); - - Within(TimeSpan.FromSeconds(50), () => - { - RunOn(() => - { - var x = _persistentRegion.Value; - }, _third, _fourth); - EnterBarrier("cluster-started-12"); - - RunOn(() => - { - //create and increment counter 1 - _persistentRegion.Value.Tell(new Counter.EntityEnvelope(1, Counter.Increment.Instance)); - _persistentRegion.Value.Tell(new Counter.Get(1)); - ExpectMsg(2); - - var counter1 = Sys.ActorSelection(LastSender.Path); - counter1.Tell(Counter.Stop.Instance); - - var probe = CreateTestProbe(); - AwaitAssert(() => - { - counter1.Tell(new Identify(1), probe.Ref); - Assert.NotNull(probe.ExpectMsg(TimeSpan.FromSeconds(1)).Subject); - }, TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(500)); - }, _third); - EnterBarrier("after-14"); - }); - } - - [MultiNodeFact(Skip = "TODO")] - public void Persistent_cluster_shards_should_be_migrated_to_new_regions_upon_region_failure() - { - Persistent_cluster_shards_should_restart_entities_which_stop_without_passivation(); - - Within(TimeSpan.FromSeconds(15), () => - { - //Start only one region, and force an entity onto that region - RunOn(() => - { - _autoMigrateRegion.Value.Tell(new Counter.EntityEnvelope(1, Counter.Increment.Instance)); - _autoMigrateRegion.Value.Tell(new Counter.Get(1)); - ExpectMsg(1); - }, _third); - EnterBarrier("shard1-region3"); - - //Start another region and test it talks to node 3 - RunOn(() => - { - _autoMigrateRegion.Value.Tell(new Counter.EntityEnvelope(1, Counter.Increment.Instance)); - _autoMigrateRegion.Value.Tell(new Counter.Get(1)); - ExpectMsg(2); - - Assert.Equal(Node(_third) / "user" / "AutoMigrateRegionTestRegion" / "1" / "1", LastSender.Path); - - // kill region 3 - Sys.ActorSelection(LastSender.Path.Parent.Parent).Tell(PoisonPill.Instance); - }, _fourth); - EnterBarrier("region4-up"); - - // Wait for migration to happen - //Test the shard, thus counter was moved onto node 4 and started. - RunOn(() => - { - var counter1 = Sys.ActorSelection(ActorPath.Parse("user") / "AutoMigrateRegionTestRegion" / "1" / "1"); - var probe = CreateTestProbe(); - AwaitAssert(() => - { - counter1.Tell(new Identify(1), probe.Ref); - Assert.NotNull(probe.ExpectMsg(TimeSpan.FromSeconds(1)).Subject); - }, TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(500)); - - counter1.Tell(new Counter.Get(1)); - ExpectMsg(2); - }, _fourth); - EnterBarrier("after-15"); - }); - } - - [MultiNodeFact(Skip = "TODO")] - public void Persistent_cluster_shards_should_ensure_rebalance_restarts_shards() - { - Persistent_cluster_shards_should_be_migrated_to_new_regions_upon_region_failure(); - - Within(TimeSpan.FromSeconds(50), () => - { - RunOn(() => - { - for (int i = 1; i <= 12; i++) - _rebalancingPersistentRegion.Value.Tell(new Counter.EntityEnvelope(i, Counter.Increment.Instance)); - - for (int i = 1; i <= 12; i++) - { - _rebalancingPersistentRegion.Value.Tell(new Counter.Get(i)); - ExpectMsg(1); - } - }, _fourth); - EnterBarrier("entities-started"); - - RunOn(() => - { - var r = _rebalancingPersistentRegion.Value; - }, _fifth); - EnterBarrier("fifth-joined-shard"); - - RunOn(() => - { - AwaitAssert(() => - { - var count = 0; - for (int i = 2; i <= 12; i++) - { - var entity = Sys.ActorSelection(_rebalancingPersistentRegion.Value.Path / (i % 12).ToString() / i.ToString()); - entity.Tell(new Identify(i)); - - var msg = ReceiveOne(TimeSpan.FromSeconds(3)) as ActorIdentity; - if (msg != null && msg.Subject != null) - count++; - } - - Assert.True(count >= 2); - }); - }, _fifth); - EnterBarrier("after-16"); - }); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Sharding.Tests/LeastShardAllocationStrategySpec.cs b/src/contrib/cluster/Akka.Cluster.Sharding.Tests/LeastShardAllocationStrategySpec.cs deleted file mode 100644 index f1f701a1391..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Sharding.Tests/LeastShardAllocationStrategySpec.cs +++ /dev/null @@ -1,94 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Linq; -using Akka.Actor; -using Akka.TestKit; -using Akka.TestKit.Xunit2; -using Xunit; - -namespace Akka.Cluster.Sharding.Tests -{ - public class LeastShardAllocationStrategySpec : TestKitBase - { - private readonly IShardAllocationStrategy _allocationStrategy; - private readonly IActorRef _regionA; - private readonly IActorRef _regionB; - private readonly IActorRef _regionC; - - public LeastShardAllocationStrategySpec() : base(new XunitAssertions(), "LeastShardAllocationStrategySpec") - { - _regionA = Sys.ActorOf(Props.Empty, "regionA"); - _regionB = Sys.ActorOf(Props.Empty, "regionB"); - _regionC = Sys.ActorOf(Props.Empty, "regionC"); - - _allocationStrategy = new LeastShardAllocationStrategy(3, 2); - } - - [Fact] - public void LeastShardAllocationStrategy_should_allocate_to_region_with_least_number_of_shards() - { - var allocations = new Dictionary> - { - {_regionA, new []{"shard1"}.ToImmutableList() }, - {_regionB, new []{"shard2"}.ToImmutableList() }, - {_regionC, ImmutableList.Empty } - }.ToImmutableDictionary(); - - var result = _allocationStrategy.AllocateShard(_regionA, "shard3", allocations).Result; - Assert.Equal(result, _regionC); - } - - [Fact] - public void LeastShardAllocationStrategy_should_reallocate_from_region_with_most_number_of_shards() - { - var allocations = new Dictionary> - { - {_regionA, new []{"shard1"}.ToImmutableList() }, - {_regionB, new []{"shard2", "shard3"}.ToImmutableList() }, - {_regionC, ImmutableList.Empty } - }.ToImmutableDictionary(); - - // so far regionB has 2 shards and regionC has 0 shards, but the diff is less than rebalanceThreshold - var r1 = _allocationStrategy.Rebalance(allocations, ImmutableHashSet.Empty).Result; - Assert.Equal(r1.Count, 0); - - allocations = allocations.SetItem(_regionB, new[] { "shard2", "shard3", "shard4" }.ToImmutableList()); - var r2 = _allocationStrategy.Rebalance(allocations, ImmutableHashSet.Empty).Result; - Assert.Equal(r2.Count, 1); - Assert.Equal(r2.First(), "shard2"); - - var r3 = _allocationStrategy.Rebalance(allocations, ImmutableHashSet.Empty.Add("shard4")).Result; - Assert.Equal(r3.Count, 0); - - allocations = allocations.SetItem(_regionA, new[] { "shard1", "shard5", "shard6" }.ToImmutableList()); - var r4 = _allocationStrategy.Rebalance(allocations, ImmutableHashSet.Empty.Add("shard1")).Result; - Assert.Equal(r4.Count, 1); - Assert.Equal(r2.First(), "shard2"); - } - - [Fact] - public void LeastShardAllocationStrategy_should_limit_number_of_simultanious_rebalances() - { - var allocations = new Dictionary> - { - {_regionA, new []{"shard1"}.ToImmutableList() }, - {_regionB, new []{ "shard2", "shard3", "shard4", "shard5", "shard6" }.ToImmutableList() }, - {_regionC, ImmutableList.Empty} - }.ToImmutableDictionary(); - - var r1 = _allocationStrategy.Rebalance(allocations, ImmutableHashSet.Empty.Add("shard2")).Result; - Assert.Equal(r1.Count, 1); - Assert.Equal(r1.First(), "shard3"); - - var r2 = _allocationStrategy.Rebalance(allocations, ImmutableHashSet.Empty.Add("shard2").Add("shard3")).Result; - Assert.Equal(r2.Count, 0); - } - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Sharding.Tests/Properties/AssemblyInfo.cs b/src/contrib/cluster/Akka.Cluster.Sharding.Tests/Properties/AssemblyInfo.cs deleted file mode 100644 index 5f5029bda60..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Sharding.Tests/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Akka.Cluster.Sharding.Tests")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Akka.Cluster.Sharding.Tests")] -[assembly: AssemblyCopyright("Copyright © 2015")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("b369f314-4d37-4ac1-b4fb-64ff671af0bc")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/contrib/cluster/Akka.Cluster.Sharding.Tests/packages.config b/src/contrib/cluster/Akka.Cluster.Sharding.Tests/packages.config deleted file mode 100644 index 1c51a9333a8..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Sharding.Tests/packages.config +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Sharding/Akka.Cluster.Sharding.csproj b/src/contrib/cluster/Akka.Cluster.Sharding/Akka.Cluster.Sharding.csproj deleted file mode 100644 index f2229d5617b..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Sharding/Akka.Cluster.Sharding.csproj +++ /dev/null @@ -1,179 +0,0 @@ - - - - - Debug - AnyCPU - {A05C31E8-0246-46A1-B3BC-4D6FE7A9AA49} - Library - Properties - Akka.Cluster.Sharding - Akka.Cluster.Sharding - v4.5 - 512 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\..\..\packages\Google.ProtocolBuffers.2.4.1.555\lib\net40\Google.ProtocolBuffers.dll - True - - - ..\..\..\packages\Google.ProtocolBuffers.2.4.1.555\lib\net40\Google.ProtocolBuffers.Serialization.dll - True - - - - ..\..\..\packages\System.Collections.Immutable.1.1.37\lib\dotnet\System.Collections.Immutable.dll - True - - - - - - - - - - - - - - - - - - - - - - - - - {6ab00f61-269a-4501-b06a-026707f000a7} - Akka.Cluster - - - {fca84dea-c118-424b-9eb8-34375dfef18a} - Akka.Persistence - - - {ea4ff8fd-7c53-49c8-b9aa-02e458b3e6a7} - Akka.Remote - - - {5deddf90-37f0-48d3-a0b0-a5cbd8a7e377} - Akka - - - {5cf8a8be-b634-473f-bb01-eba878746bd4} - Akka.Cluster.Tools - - - - - - - - - - - - - - - ..\..\..\..\packages\Google.ProtocolBuffers\lib\net35\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\packages\Google.ProtocolBuffers\lib\net35\Google.ProtocolBuffers.dll - True - True - - - - - - - ..\..\..\..\packages\Google.ProtocolBuffers\lib\net20\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\packages\Google.ProtocolBuffers\lib\net20\Google.ProtocolBuffers.dll - True - True - - - - - - - - ..\..\..\..\packages\Google.ProtocolBuffers\lib\sl30\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\packages\Google.ProtocolBuffers\lib\sl30\Google.ProtocolBuffers.dll - True - True - - - - - - - ..\..\..\..\packages\Google.ProtocolBuffers\lib\sl40\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\packages\Google.ProtocolBuffers\lib\sl40\Google.ProtocolBuffers.dll - True - True - - - - - - - ..\..\..\..\packages\Google.ProtocolBuffers\lib\portable-net40+sl4+sl5+wp7+wp8+win8\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\packages\Google.ProtocolBuffers\lib\portable-net40+sl4+sl5+wp7+wp8+win8\Google.ProtocolBuffers.dll - True - True - - - - - - - - \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Sharding/ClusterSharding.cs b/src/contrib/cluster/Akka.Cluster.Sharding/ClusterSharding.cs deleted file mode 100644 index ca55cbcb8d0..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Sharding/ClusterSharding.cs +++ /dev/null @@ -1,620 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using Akka.Actor; -using Akka.Configuration; -using Akka.Dispatch; -using Akka.Pattern; - -namespace Akka.Cluster.Sharding -{ - using Msg = Object; - using EntityId = String; - using ShardId = String; - - /// - /// Marker trait for remote messages and persistent events/snapshots with special serializer. - /// - public interface IClusterShardingSerializable { } - - public class ClusterShardingExtensionProvider : ExtensionIdProvider - { - public override ClusterSharding CreateExtension(ExtendedActorSystem system) - { - var extension = new ClusterSharding(system); - return extension; - } - } - - /// - /// Convenience implementation of that - /// construct ShardId based on the of the EntityId. - /// The number of unique shards is limited by the given MaxNumberOfShards. - /// - public abstract class HashCodeMessageExtractor : IMessageExtractor - { - public readonly int MaxNumberOfShards; - - protected HashCodeMessageExtractor(int maxNumberOfShards) - { - MaxNumberOfShards = maxNumberOfShards; - } - - public abstract string EntityId(object message); - - public virtual object EntityMessage(object message) - { - return message; - } - - public virtual string ShardId(object message) - { - return (Math.Abs(EntityId(message).GetHashCode())%MaxNumberOfShards).ToString(); - } - } - - /// - /// - /// This extension provides sharding functionality of actors in a cluster. - /// The typical use case is when you have many stateful actors that together consume - /// more resources (e.g. memory) than fit on one machine. You need to distribute them across - /// several nodes in the cluster and you want to be able to interact with them using their - /// logical identifier, but without having to care about their physical location in the cluster, - /// which might also change over time. It could for example be actors representing Aggregate Roots in - /// Domain-Driven Design terminology. Here we call these actors "entries". These actors - /// typically have persistent (durable) state, but this feature is not limited to - /// actors with persistent state. - /// - /// - /// In this context sharding means that actors with an identifier, so called entries, - /// can be automatically distributed across multiple nodes in the cluster. Each entity - /// actor runs only at one place, and messages can be sent to the entity without requiring - /// the sender to know the location of the destination actor. This is achieved by sending - /// the messages via a actor provided by this extension, which knows how - /// to route the message with the entity id to the final destination. - /// - /// - /// This extension is supposed to be used by first, typically at system startup on each node - /// in the cluster, registering the supported entity types with the - /// method and then the actor for a named entity type can be retrieved with - /// . Messages to the entries are always sent via the local - /// . Some settings can be configured as described in the `akka.contrib.cluster.sharding` - /// section of the `reference.conf`. - /// - /// - /// The actor is started on each node in the cluster, or group of nodes - /// tagged with a specific role. The is created with two application specific - /// functions to extract the entity identifier and the shard identifier from incoming messages. - /// A shard is a group of entries that will be managed together. For the first message in a - /// specific shard the request the location of the shard from a central coordinator, - /// the . The decides which that - /// owns the shard. The receives the decided home of the shard - /// and if that is the instance itself it will create a local child - /// actor representing the entity and direct all messages for that entity to it. - /// If the shard home is another instance messages will be forwarded - /// to that instance instead. While resolving the location of a - /// shard incoming messages for that shard are buffered and later delivered when the - /// shard home is known. Subsequent messages to the resolved shard can be delivered - /// to the target destination immediately without involving the . - /// - /// - /// To make sure that at most one instance of a specific entity actor is running somewhere - /// in the cluster it is important that all nodes have the same view of where the shards - /// are located. Therefore the shard allocation decisions are taken by the central - /// , which is running as a cluster singleton, i.e. one instance on - /// the oldest member among all cluster nodes or a group of nodes tagged with a specific - /// role. The oldest member can be determined by . - /// - /// - /// The logic that decides where a shard is to be located is defined in a pluggable shard - /// allocation strategy. The default implementation - /// allocates new shards to the with least number of previously allocated shards. - /// This strategy can be replaced by an application specific implementation. - /// - /// - /// To be able to use newly added members in the cluster the coordinator facilitates rebalancing - /// of shards, i.e. migrate entries from one node to another. In the rebalance process the - /// coordinator first notifies all actors that a handoff for a shard has started. - /// That means they will start buffering incoming messages for that shard, in the same way as if the - /// shard location is unknown. During the rebalance process the coordinator will not answer any - /// requests for the location of shards that are being rebalanced, i.e. local buffering will - /// continue until the handoff is completed. The responsible for the rebalanced shard - /// will stop all entries in that shard by sending `PoisonPill` to them. When all entries have - /// been terminated the owning the entries will acknowledge the handoff as completed - /// to the coordinator. Thereafter the coordinator will reply to requests for the location of - /// the shard and thereby allocate a new home for the shard and then buffered messages in the - /// actors are delivered to the new location. This means that the state of the entries - /// are not transferred or migrated. If the state of the entries are of importance it should be - /// persistent (durable), e.g. with `Akka.Persistence`, so that it can be recovered at the new - /// location. - /// - /// - /// The logic that decides which shards to rebalance is defined in a pluggable shard - /// allocation strategy. The default implementation - /// picks shards for handoff from the with most number of previously allocated shards. - /// They will then be allocated to the with least number of previously allocated shards, - /// i.e. new members in the cluster. There is a configurable threshold of how large the difference - /// must be to begin the rebalancing. This strategy can be replaced by an application specific - /// implementation. - /// - /// - /// The state of shard locations in the is persistent (durable) with - /// `Akka.Persistence` to survive failures. Since it is running in a cluster `Akka.Persistence` - /// must be configured with a distributed journal. When a crashed or unreachable coordinator - /// node has been removed (via down) from the cluster a new singleton - /// actor will take over and the state is recovered. During such a failure period shards - /// with known location are still available, while messages for new (unknown) shards - /// are buffered until the new becomes available. - /// - /// - /// As long as a sender uses the same actor to deliver messages to an entity - /// actor the order of the messages is preserved. As long as the buffer limit is not reached - /// messages are delivered on a best effort basis, with at-most once delivery semantics, - /// in the same way as ordinary message sending. Reliable end-to-end messaging, with - /// at-least-once semantics can be added by using in `Akka.Persistence`. - /// - /// Some additional latency is introduced for messages targeted to new or previously - /// unused shards due to the round-trip to the coordinator. Rebalancing of shards may - /// also add latency. This should be considered when designing the application specific - /// shard resolution, e.g. to avoid too fine grained shards. - /// - /// The actor can also be started in proxy only mode, i.e. it will not - /// host any entries itself, but knows how to delegate messages to the right location. - /// A starts in proxy only mode if the roles of the node does not include - /// the node role specified in `akka.contrib.cluster.sharding.role` config property - /// or if the specified `EntityProps` is `null`. - /// - /// - /// If the state of the entries are persistent you may stop entries that are not used to - /// reduce memory consumption. This is done by the application specific implementation of - /// the entity actors for example by defining receive timeout (). - /// If a message is already enqueued to the entity when it stops itself the enqueued message - /// in the mailbox will be dropped. To support graceful passivation without loosing such - /// messages the entity actor can send to its parent . - /// The specified wrapped message in will be sent back to the entity, which is - /// then supposed to stop itself. Incoming messages will be buffered by the - /// between reception of and termination of the entity. Such buffered messages - /// are thereafter delivered to a new incarnation of the entity. - /// - /// - public class ClusterSharding : IExtension - { - private readonly Lazy _guardian; - private readonly ConcurrentDictionary _regions = new ConcurrentDictionary(); - private readonly ExtendedActorSystem _system; - private readonly Cluster _cluster; - - public static ClusterSharding Get(ActorSystem system) - { - return system.WithExtension(); - } - - public ClusterSharding(ExtendedActorSystem system) - { - _system = system; - _system.Settings.InjectTopLevelFallback(DefaultConfig()); - _cluster = Cluster.Get(_system); - Settings = ClusterShardingSettings.Create(system); - - _guardian = new Lazy(() => - { - var guardianName = system.Settings.Config.GetString("akka.cluster.sharding.guardian-name"); - var dispatcher = system.Settings.Config.GetString("akka.cluster.sharding.use-dispatcher"); - if (string.IsNullOrEmpty(dispatcher)) dispatcher = Dispatchers.DefaultDispatcherId; - return system.ActorOf(Props.Create(() => new ClusterShardingGuardian()).WithDispatcher(dispatcher), guardianName); - }); - } - - public ClusterShardingSettings Settings { get; private set; } - - public static Config DefaultConfig() - { - return ConfigurationFactory.FromResource("Akka.Cluster.Sharding.reference.conf"); - } - - /// - /// Register a named entity type by defining the of the entity actor and - /// functions to extract entity and shard identifier from messages. The - /// actor for this type can later be retrieved with the method. - /// - /// The name of the entity type - /// - /// The of the entity actors that will be created by the - /// - /// Configuration settings, see - /// - /// Partial function to extract the entity id and the message to send to the entity from the incoming message, - /// if the partial function does not match the message will be `unhandled`, - /// i.e.posted as `Unhandled` messages on the event stream - /// - /// - /// Function to determine the shard id for an incoming message, only messages that passed the `extractEntityId` will be used - /// - /// Possibility to use a custom shard allocation and rebalancing logic - /// - /// The message that will be sent to entities when they are to be stopped for a rebalance or - /// graceful shutdown of a , e.g. . - /// - /// The actor ref of the that is to be responsible for the shard. - public IActorRef Start( - string typeName, //TODO: change type name to type instance? - Props entityProps, - ClusterShardingSettings settings, - IdExtractor idExtractor, - ShardResolver shardResolver, - IShardAllocationStrategy allocationStrategy, - object handOffStopMessage) - { - RequireClusterRole(settings.Role); - - var timeout = _system.Settings.CreationTimeout; - var startMsg = new ClusterShardingGuardian.Start(typeName, entityProps, settings, idExtractor, shardResolver, allocationStrategy, handOffStopMessage); - - var started = _guardian.Value.Ask(startMsg, timeout).Result; - var shardRegion = started.ShardRegion; - _regions.TryAdd(typeName, shardRegion); - return shardRegion; - } - - /// - /// Register a named entity type by defining the of the entity actor and - /// functions to extract entity and shard identifier from messages. The - /// actor for this type can later be retrieved with the method. - /// - /// The name of the entity type - /// - /// The of the entity actors that will be created by the - /// - /// Configuration settings, see - /// - /// Partial function to extract the entity id and the message to send to the entity from the incoming message, - /// if the partial function does not match the message will be `unhandled`, - /// i.e.posted as `Unhandled` messages on the event stream - /// - /// - /// Function to determine the shard id for an incoming message, only messages that passed the `extractEntityId` will be used - /// - /// The actor ref of the that is to be responsible for the shard. - public IActorRef Start( - string typeName, //TODO: change type name to type instance? - Props entityProps, - ClusterShardingSettings settings, - IdExtractor idExtractor, - ShardResolver shardResolver) - { - var allocationStrategy = new LeastShardAllocationStrategy( - Settings.TunningParameters.LeastShardAllocationRebalanceThreshold, - Settings.TunningParameters.LeastShardAllocationMaxSimultaneousRebalance); - return Start(typeName, entityProps, settings, idExtractor, shardResolver, allocationStrategy, PoisonPill.Instance); - } - - /// - /// Register a named entity type by defining the of the entity actor and - /// functions to extract entity and shard identifier from messages. The - /// actor for this type can later be retrieved with the method. - /// - /// The name of the entity type - /// - /// The of the entity actors that will be created by the - /// - /// Configuration settings, see - /// - /// Functions to extract the entity id, shard id, and the message to send to the entity from the incoming message. - /// - /// Possibility to use a custom shard allocation and rebalancing logic - /// - /// The message that will be sent to entities when they are to be stopped for a rebalance or - /// graceful shutdown of a , e.g. . - /// - /// The actor ref of the that is to be responsible for the shard. - public IActorRef Start(string typeName, Props entityProps, ClusterShardingSettings settings, - IMessageExtractor messageExtractor, IShardAllocationStrategy allocationStrategy, object handOffMessage) - { - IdExtractor idExtractor = messageExtractor.ToIdExtractor(); - ShardResolver shardResolver = messageExtractor.ShardId; - - return Start(typeName, entityProps, settings, idExtractor, shardResolver, allocationStrategy, handOffMessage); - } - - /// - /// Register a named entity type by defining the of the entity actor and - /// functions to extract entity and shard identifier from messages. The - /// actor for this type can later be retrieved with the method. - /// - /// The name of the entity type - /// - /// The of the entity actors that will be created by the - /// - /// Configuration settings, see - /// - /// Functions to extract the entity id, shard id, and the message to send to the entity from the incoming message. - /// - /// The actor ref of the that is to be responsible for the shard. - public IActorRef Start(string typeName, Props entityProps, ClusterShardingSettings settings, - IMessageExtractor messageExtractor) - { - return Start(typeName, - entityProps, - settings, - messageExtractor, - new LeastShardAllocationStrategy( - Settings.TunningParameters.LeastShardAllocationRebalanceThreshold, - Settings.TunningParameters.LeastShardAllocationMaxSimultaneousRebalance), - PoisonPill.Instance); - } - - /// - /// Register a named entity type `ShardRegion` on this node that will run in proxy only mode, i.e.it will - /// delegate messages to other `ShardRegion` actors on other nodes, but not host any entity actors itself. - /// The actor for this type can later be retrieved with the - /// method. - /// - /// The name of the entity type. - /// - /// Specifies that this entity type is located on cluster nodes with a specific role. - /// If the role is not specified all nodes in the cluster are used. - /// - /// - /// Partial function to extract the entity id and the message to send to the entity from the incoming message, - /// if the partial function does not match the message will be `unhandled`, i.e.posted as `Unhandled` messages - /// on the event stream - /// - /// - /// Function to determine the shard id for an incoming message, only messages that passed the `extractEntityId` will be used - /// - /// The actor ref of the that is to be responsible for the shard. - public IActorRef StartProxy(string typeName, string role, IdExtractor idExtractor, ShardResolver shardResolver) - { - var timeout = _system.Settings.CreationTimeout; - var settings = ClusterShardingSettings.Create(_system).WithRole(role); - var startMsg = new ClusterShardingGuardian.StartProxy(typeName, settings, idExtractor, shardResolver); - var started = _guardian.Value.Ask(startMsg, timeout).Result; - _regions.TryAdd(typeName, started.ShardRegion); - return started.ShardRegion; - } - - /// - /// Register a named entity type `ShardRegion` on this node that will run in proxy only mode, i.e.it will - /// delegate messages to other `ShardRegion` actors on other nodes, but not host any entity actors itself. - /// The actor for this type can later be retrieved with the - /// method. - /// - /// The name of the entity type. - /// - /// Specifies that this entity type is located on cluster nodes with a specific role. - /// If the role is not specified all nodes in the cluster are used. - /// - /// - /// Functions to extract the entity id, shard id, and the message to send to the entity from the incoming message. - /// - /// The actor ref of the that is to be responsible for the shard. - public IActorRef StartProxy(string typeName, string role, IMessageExtractor messageExtractor) - { - IdExtractor extractEntityId = msg => - { - var entityId = messageExtractor.EntityId(msg); - var entityMessage = messageExtractor.EntityMessage(msg); - return Tuple.Create(entityId, entityMessage); - }; - - return StartProxy(typeName, role, extractEntityId, messageExtractor.ShardId); - } - - /// - /// Retrieve the actor reference of the actor responsible for the named entity type. - /// The entity type must be registered with the method before it can be used here. - /// Messages to the entity is always sent via the . - /// - public IActorRef ShardRegion(string typeName) - { - IActorRef region; - if (_regions.TryGetValue(typeName, out region)) - { - return region; - } - throw new ArgumentException(string.Format("Shard type [{0}] must be started first", typeName)); - } - - private void RequireClusterRole(string role) - { - if (!(string.IsNullOrEmpty(role) || _cluster.SelfRoles.Contains(role))) - { - throw new IllegalStateException(string.Format("This cluster member [{0}] doesn't have the role [{1}]", _cluster.SelfAddress, role)); - } - } - } - - /// - /// Interface of the function used by the to - /// extract the shard id from an incoming message. - /// Only messages that passed the will be used - /// as input to this function. - /// - public delegate ShardId ShardResolver(Msg message); - - public static class ShardResolvers - { - public static readonly ShardResolver Default = msg => (ShardId)msg; - } - - /// - /// Interface of the partial function used by the to - /// extract the entity id and the message to send to the entity from an - /// incoming message. The implementation is application specific. - /// If the partial function does not match the message will be - /// `unhandled`, i.e. posted as `Unhandled` messages on the event stream. - /// Note that the extracted message does not have to be the same as the incoming - /// message to support wrapping in message envelope that is unwrapped before - /// sending to the entity actor. - /// - public delegate Tuple IdExtractor(Msg message); - - /// - /// Interface of functions to extract entity id, shard id, and the message to send - /// to the entity from an incoming message. - /// - public interface IMessageExtractor - { - /// - /// Extract the entity id from an incoming . - /// If `null` is returned the message will be `unhandled`, i.e. posted as `Unhandled` - /// messages on the event stream - /// - EntityId EntityId(object message); - - /// - /// Extract the message to send to the entity from an incoming . - /// Note that the extracted message does not have to be the same as the incoming - /// message to support wrapping in message envelope that is unwrapped before - /// sending to the entity actor. - /// - object EntityMessage(object message); - - /// - /// Extract the entity id from an incoming . Only messages that - /// passed the method will be used as input to this method. - /// - string ShardId(object message); - } - - public static class Extensions - { - public static IdExtractor ToIdExtractor(this IMessageExtractor self) - { - IdExtractor idExtractor = msg => - { - if (self.EntityId(msg) != null) - return Tuple.Create(self.EntityId(msg), self.EntityMessage(msg)); - //TODO: should we really use tuples? - - return null; - }; - - return idExtractor; - } - } - - /// - /// Periodic message to trigger rebalance. - /// - internal sealed class RebalanceTick - { - public static readonly RebalanceTick Instance = new RebalanceTick(); - private RebalanceTick() { } - } - - /// - /// End of rebalance process performed by . - /// - internal sealed class RebalanceDone - { - public readonly ShardId Shard; - public readonly bool Ok; - - public RebalanceDone(string shard, bool ok) - { - Shard = shard; - Ok = ok; - } - } - - /// - /// INTERNAL API. Rebalancing process is performed by this actor. It sends - /// to all actors followed - /// by to the responsible for - /// the shard. When the handoff is completed it sends to its parent - /// . If the process takes longer than the `handOffTimeout` it - /// also sends . - /// - public class RebalanceWorker : ActorBase - { - public static Props Props(string shard, IActorRef @from, TimeSpan handOffTimeout, IEnumerable regions) - { - return Actor.Props.Create(() => new RebalanceWorker(shard, @from, handOffTimeout, regions)); - } - - private readonly ShardId _shard; - private readonly IActorRef _from; - private readonly ISet _remaining; - - public RebalanceWorker(string shard, IActorRef @from, TimeSpan handOffTimeout, IEnumerable regions) - { - _shard = shard; - _from = @from; - - _remaining = new HashSet(regions); - foreach (var region in _remaining) - region.Tell(new PersistentShardCoordinator.BeginHandOff(shard)); - - Context.System.Scheduler.ScheduleTellOnce(handOffTimeout, Self, ReceiveTimeout.Instance, Self); - } - - protected override bool Receive(object message) - { - if (message is PersistentShardCoordinator.BeginHandOffAck) - { - var shard = ((PersistentShardCoordinator.BeginHandOffAck)message).Shard; - _remaining.Remove(Sender); - if (_remaining.Count == 0) - { - _from.Tell(new PersistentShardCoordinator.HandOff(shard)); - Context.Become(StoppingShard); - } - } - else if (message is ReceiveTimeout) - { - Done(false); - } - else return false; - return true; - } - - private bool StoppingShard(object message) - { - if (message is PersistentShardCoordinator.ShardStopped) Done(true); - else if (message is ReceiveTimeout) Done(false); - else return false; - return true; - } - - private void Done(bool ok) - { - Context.Parent.Tell(new RebalanceDone(_shard, ok)); - Context.Stop(Self); - } - } - - /// - /// Check if we've received a shard start request. - /// - [Serializable] - public sealed class ResendShardHost - { - public readonly ShardId Shard; - public readonly IActorRef Region; - - public ResendShardHost(string shard, IActorRef region) - { - Shard = shard; - Region = region; - } - } - - [Serializable] - public sealed class DelayedShardRegionTerminated - { - public readonly IActorRef Region; - - public DelayedShardRegionTerminated(IActorRef region) - { - Region = region; - } - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Sharding/ClusterShardingGuardian.cs b/src/contrib/cluster/Akka.Cluster.Sharding/ClusterShardingGuardian.cs deleted file mode 100644 index ce6e2da4852..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Sharding/ClusterShardingGuardian.cs +++ /dev/null @@ -1,145 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using Akka.Actor; -using Akka.Cluster.Tools.Singleton; -using Akka.Pattern; - -namespace Akka.Cluster.Sharding -{ - /// - /// INTERNAL API: and actors are createad as children of this actor. - /// - public sealed class ClusterShardingGuardian : ReceiveActor - { - #region messages - - [Serializable] - public sealed class Started : INoSerializationVerificationNeeded - { - public readonly IActorRef ShardRegion; - - public Started(IActorRef shardRegion) - { - ShardRegion = shardRegion; - } - } - - [Serializable] - public sealed class Start : INoSerializationVerificationNeeded - { - public readonly string TypeName; - public readonly Props EntityProps; - public readonly ClusterShardingSettings Settings; - public readonly IdExtractor IdExtractor; - public readonly ShardResolver ShardResolver; - public readonly IShardAllocationStrategy AllocationStrategy; - public readonly object HandOffStopMessage; - - public Start(string typeName, Props entityProps, ClusterShardingSettings settings, - IdExtractor idIdExtractor, ShardResolver shardResolver, IShardAllocationStrategy allocationStrategy, object handOffStopMessage) - { - if (string.IsNullOrEmpty(typeName)) throw new ArgumentNullException("typeName", "ClusterSharding start requires type name to be provided"); - if (entityProps == null) throw new ArgumentNullException("entityProps", string.Format("ClusterSharding start requires Props for [{0}] to be provided", typeName)); - - TypeName = typeName; - EntityProps = entityProps; - Settings = settings; - IdExtractor = idIdExtractor; - ShardResolver = shardResolver; - AllocationStrategy = allocationStrategy; - HandOffStopMessage = handOffStopMessage; - } - } - - [Serializable] - public sealed class StartProxy : INoSerializationVerificationNeeded - { - public readonly string TypeName; - public readonly ClusterShardingSettings Settings; - public readonly IdExtractor ExtractEntityId; - public readonly ShardResolver ExtractShardId; - - public StartProxy(string typeName, ClusterShardingSettings settings, IdExtractor extractEntityId, ShardResolver extractShardId) - { - if (string.IsNullOrEmpty(typeName)) throw new ArgumentNullException("typeName", "ClusterSharding start proxy requires type name to be provided"); - - TypeName = typeName; - Settings = settings; - ExtractEntityId = extractEntityId; - ExtractShardId = extractShardId; - } - } - - #endregion - - private readonly Cluster _cluster = Cluster.Get(Context.System); - private readonly ClusterSharding _sharding = ClusterSharding.Get(Context.System); - - public ClusterShardingGuardian() - { - Receive(start => - { - var settings = start.Settings; - var encName = Uri.EscapeDataString(start.TypeName); - var coordinatorSingletonManagerName = CoordinatorSingletonManagerName(encName); - var coordinatorPath = CoordinatorPath(encName); - var shardRegion = Context.Child(encName); - - if (Equals(shardRegion, ActorRefs.Nobody)) - { - var minBackoff = settings.TunningParameters.CoordinatorFailureBackoff; - var maxBackoff = new TimeSpan(minBackoff.Ticks * 5); - var coordinatorProps = PersistentShardCoordinator.Props(start.TypeName, settings, start.AllocationStrategy); - var singletonProps = Props.Create(() => new BackoffSupervisor(coordinatorProps, "coordinator", minBackoff, maxBackoff, 0.2)).WithDeploy(Deploy.Local); - var singletonSettings = settings.CoordinatorSingletonSettings.WithSingletonName("singleton").WithRole(settings.Role); - - var shardCoordinatorSingleton = Context.ActorOf(ClusterSingletonManager.Props(singletonProps, PoisonPill.Instance, singletonSettings), coordinatorSingletonManagerName); - } - - shardRegion = Context.ActorOf(ShardRegion.Props( - typeName: start.TypeName, - entityProps: start.EntityProps, - settings: settings, - coordinatorPath: coordinatorPath, - extractEntityId: start.IdExtractor, - extractShardId: start.ShardResolver, - handOffStopMessage: start.HandOffStopMessage), encName); - - Sender.Tell(new Started(shardRegion)); - }); - - Receive(startProxy => - { - var settings = startProxy.Settings; - var encName = Uri.EscapeDataString(startProxy.TypeName); - var coordinatorSingletonManagerName = CoordinatorSingletonManagerName(encName); - var coordinatorPath = CoordinatorPath(encName); - - var shardRegion = Context.ActorOf(ShardRegion.ProxyProps( - typeName: startProxy.TypeName, - settings: settings, - coordinatorPath: coordinatorPath, - extractEntityId: startProxy.ExtractEntityId, - extractShardId: startProxy.ExtractShardId), encName); - - Sender.Tell(new Started(shardRegion)); - }); - } - - private string CoordinatorPath(string encName) - { - return (Self.Path / CoordinatorSingletonManagerName(encName) / "singleton" / "coordinator").ToStringWithoutAddress(); - } - - private static string CoordinatorSingletonManagerName(string encName) - { - return encName + "Coordinator"; - } - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Sharding/ClusterShardingSettings.cs b/src/contrib/cluster/Akka.Cluster.Sharding/ClusterShardingSettings.cs deleted file mode 100644 index 3000c798f17..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Sharding/ClusterShardingSettings.cs +++ /dev/null @@ -1,204 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using Akka.Actor; -using Akka.Cluster.Tools.Singleton; -using Akka.Configuration; - -namespace Akka.Cluster.Sharding -{ - [Serializable] - public class TunningParameters - { - public readonly TimeSpan CoordinatorFailureBackoff; - public readonly TimeSpan RetryInterval; - public readonly int BufferSize; - public readonly TimeSpan HandOffTimeout; - public readonly TimeSpan ShardStartTimeout; - public readonly TimeSpan ShardFailureBackoff; - public readonly TimeSpan EntityRestartBackoff; - public readonly TimeSpan RebalanceInterval; - public readonly int SnapshotAfter; - public readonly int LeastShardAllocationRebalanceThreshold; - public readonly int LeastShardAllocationMaxSimultaneousRebalance; - - public TunningParameters( - TimeSpan coordinatorFailureBackoff, - TimeSpan retryInterval, - int bufferSize, - TimeSpan handOffTimeout, - TimeSpan shardStartTimeout, - TimeSpan shardFailureBackoff, - TimeSpan entityRestartBackoff, - TimeSpan rebalanceInterval, - int snapshotAfter, - int leastShardAllocationRebalanceThreshold, - int leastShardAllocationMaxSimultaneousRebalance) - { - CoordinatorFailureBackoff = coordinatorFailureBackoff; - RetryInterval = retryInterval; - BufferSize = bufferSize; - HandOffTimeout = handOffTimeout; - ShardStartTimeout = shardStartTimeout; - ShardFailureBackoff = shardFailureBackoff; - EntityRestartBackoff = entityRestartBackoff; - RebalanceInterval = rebalanceInterval; - SnapshotAfter = snapshotAfter; - LeastShardAllocationRebalanceThreshold = leastShardAllocationRebalanceThreshold; - LeastShardAllocationMaxSimultaneousRebalance = leastShardAllocationMaxSimultaneousRebalance; - } - } - - [Serializable] - public sealed class ClusterShardingSettings : INoSerializationVerificationNeeded - { - /// - /// Specifies that this entity type requires cluster nodes with a specific role. - /// If the role is not specified all nodes in the cluster are used. - /// - public readonly string Role; - - /// - /// True if active entity actors shall be automatically restarted upon restart.i.e. - /// if the is started on a different due to rebalance or crash. - /// - public readonly bool RememberEntities; - - /// - /// Absolute path to the journal plugin configuration entity that is to be used for the internal - /// persistence of ClusterSharding.If not defined the default journal plugin is used. Note that - /// this is not related to persistence used by the entity actors. - /// - public readonly string JournalPluginId; - - /// - /// Absolute path to the snapshot plugin configuration entity that is to be used for the internal persistence - /// of ClusterSharding. If not defined the default snapshot plugin is used.Note that this is not related - /// to persistence used by the entity actors. - /// - public readonly string SnapshotPluginId; - - public readonly TunningParameters TunningParameters; - - public readonly ClusterSingletonManagerSettings CoordinatorSingletonSettings; - - /// - /// Create settings from the default configuration `akka.cluster.sharding`. - /// - public static ClusterShardingSettings Create(ActorSystem system) - { - var config = system.Settings.Config.GetConfig("akka.cluster.sharding"); - var coordinatorSingletonPath = config.GetString("coordinator-singleton"); - - return Create(config, system.Settings.Config.GetConfig(coordinatorSingletonPath)); - } - - public static ClusterShardingSettings Create(Config config, Config singletonConfig) - { - var tuningParameters = new TunningParameters( - coordinatorFailureBackoff: config.GetTimeSpan("coordinator-failure-backoff"), - retryInterval: config.GetTimeSpan("retry-interval"), - bufferSize: config.GetInt("buffer-size"), - handOffTimeout: config.GetTimeSpan("handoff-timeout"), - shardStartTimeout: config.GetTimeSpan("shard-start-timeout"), - shardFailureBackoff: config.GetTimeSpan("shard-failure-backoff"), - entityRestartBackoff: config.GetTimeSpan("entity-restart-backoff"), - rebalanceInterval: config.GetTimeSpan("rebalance-interval"), - snapshotAfter: config.GetInt("snapshot-after"), - leastShardAllocationRebalanceThreshold: config.GetInt("least-shard-allocation-strategy.rebalance-threshold"), - leastShardAllocationMaxSimultaneousRebalance: config.GetInt("least-shard-allocation-strategy.max-simultaneous-rebalance")); - - var coordinatorSingletonSettings = ClusterSingletonManagerSettings.Create(singletonConfig); - var role = config.GetString("role"); - if (role == string.Empty) role = null; - - return new ClusterShardingSettings( - role: role, - rememberEntities: config.GetBoolean("remember-entities"), - journalPluginId: config.GetString("journal-plugin-id"), - snapshotPluginId: config.GetString("snapshot-plugin-id"), - tunningParameters: tuningParameters, - coordinatorSingletonSettings: coordinatorSingletonSettings); - } - - public ClusterShardingSettings( - string role, - bool rememberEntities, - string journalPluginId, - string snapshotPluginId, - TunningParameters tunningParameters, - ClusterSingletonManagerSettings coordinatorSingletonSettings) - { - Role = role; - RememberEntities = rememberEntities; - JournalPluginId = journalPluginId; - SnapshotPluginId = snapshotPluginId; - TunningParameters = tunningParameters; - CoordinatorSingletonSettings = coordinatorSingletonSettings; - } - - public ClusterShardingSettings WithRole(string role) - { - return new ClusterShardingSettings( - role: role, - rememberEntities: RememberEntities, - journalPluginId: JournalPluginId, - snapshotPluginId: SnapshotPluginId, - tunningParameters: TunningParameters, - coordinatorSingletonSettings: CoordinatorSingletonSettings); - } - - public ClusterShardingSettings WithRememberEntities(bool rememberEntities) - { - return Copy(rememberEntities: rememberEntities); - } - - public ClusterShardingSettings WithJournalPluginId(string journalPluginId) - { - return Copy(journalPluginId: journalPluginId ?? string.Empty); - } - - public ClusterShardingSettings WithSnapshotPluginId(string snapshotPluginId) - { - return Copy(snapshotPluginId: snapshotPluginId ?? string.Empty); - } - - public ClusterShardingSettings WithTuningParameters(TunningParameters tunningParameters) - { - if (tunningParameters == null) - throw new ArgumentNullException("tunningParameters"); - - return Copy(tunningParameters: tunningParameters); - } - - public ClusterShardingSettings WithCoordinatorSingletonSettings(ClusterSingletonManagerSettings coordinatorSingletonSettings) - { - if (coordinatorSingletonSettings == null) - throw new ArgumentNullException("coordinatorSingletonSettings"); - - return Copy(coordinatorSingletonSettings: coordinatorSingletonSettings); - } - - private ClusterShardingSettings Copy( - string role = null, - bool? rememberEntities = null, - string journalPluginId = null, - string snapshotPluginId = null, - TunningParameters tunningParameters = null, - ClusterSingletonManagerSettings coordinatorSingletonSettings = null) - { - return new ClusterShardingSettings( - role: role ?? Role, - rememberEntities: rememberEntities ?? RememberEntities, - journalPluginId: journalPluginId ?? JournalPluginId, - snapshotPluginId: snapshotPluginId ?? SnapshotPluginId, - tunningParameters: tunningParameters ?? TunningParameters, - coordinatorSingletonSettings: coordinatorSingletonSettings ?? CoordinatorSingletonSettings); - } - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Sharding/PersistentShard.cs b/src/contrib/cluster/Akka.Cluster.Sharding/PersistentShard.cs deleted file mode 100644 index 72e151aa14e..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Sharding/PersistentShard.cs +++ /dev/null @@ -1,140 +0,0 @@ -using System; -using System.Collections.Immutable; -using Akka.Actor; -using Akka.Persistence; - -namespace Akka.Cluster.Sharding -{ - using ShardId = String; - using EntryId = String; - using Msg = Object; - - /// - /// This actor creates children entity actors on demand that it is told to be - /// responsible for. It is used when `rememberEntities` is enabled. - /// - public class PersistentShard : Shard - { - protected int PersistCount = 0; - - private readonly string _persistenceId; - public override string PersistenceId { get { return _persistenceId; } } - - public PersistentShard( - string typeName, - string shardId, - Props entityProps, - ClusterShardingSettings settings, - IdExtractor extractEntityId, - ShardResolver extractShardId, - object handOffStopMessage) - : base(typeName, shardId, entityProps, settings, extractEntityId, extractShardId, handOffStopMessage) - { - _persistenceId = "/sharding/" + TypeName + "Shard/" + ShardId; - JournalPluginId = Settings.JournalPluginId; - SnapshotPluginId = Settings.SnapshotPluginId; - - } - - protected override bool ReceiveCommand(object message) - { - return HandleCommand(message); - } - - protected override bool ReceiveRecover(object message) - { - SnapshotOffer offer; - if (message is EntityStarted) - { - var started = (EntityStarted)message; - State = new ShardState(State.Entries.Add(started.EntityId)); - } - else if (message is EntityStopped) - { - var stopped = (EntityStopped)message; - State = new ShardState(State.Entries.Remove(stopped.EntityId)); - } - else if ((offer = message as SnapshotOffer) != null && offer.Snapshot is ShardState) - { - State = (ShardState)offer.Snapshot; - } - else if (message is RecoveryCompleted) - { - foreach (var entry in State.Entries) - GetEntity(entry); - - base.Initialized(); - Log.Debug("Shard recovery completed [{0}]", ShardId); - } - else return false; - return true; - } - - protected override void ProcessChange(T evt, Action handler) - { - SaveSnapshotIfNeeded(); - Persist(evt, handler); - } - - protected void SaveSnapshotIfNeeded() - { - PersistCount++; - if ((PersistCount & Settings.TunningParameters.SnapshotAfter) == 0) - { - Log.Debug("Saving snapshot, sequence number [{0}]", SnapshotSequenceNr); - SaveSnapshot(State); - } - } - - protected override void EntityTerminated(IActorRef tref) - { - ShardId id; - IImmutableList> buffer; - - if (IdByRef.TryGetValue(tref, out id)) - { - if (MessageBuffers.TryGetValue(id, out buffer) && buffer.Count != 0) - { - // Note; because we're not persisting the EntityStopped, we don't need - // to persist the EntityStarted either. - Log.Debug("Starting entity [{0}] again, there are buffered messages for it", id); - SendMessageBuffer(new EntityStarted(id)); - } - else - { - if (!Passivating.Contains(tref)) - { - Log.Debug("Entity [{0}] stopped without passivating, will restart after backoff", id); - Context.System.Scheduler.ScheduleTellOnce(Settings.TunningParameters.EntityRestartBackoff, Sender, new RestartEntity(id), Self); - } - else - { - ProcessChange(new EntityStopped(id), PassivateCompleted); - } - } - } - - Passivating = Passivating.Remove(tref); - } - - protected override void DeliverTo(string id, object message, object payload, IActorRef sender) - { - var name = Uri.EscapeDataString(id); - var child = Context.Child(name); - if (Equals(child, ActorRefs.Nobody)) - { - // Note; we only do this if remembering, otherwise the buffer is an overhead - MessageBuffers = MessageBuffers.SetItem(id, ImmutableList>.Empty.Add(Tuple.Create(message, sender))); - SaveSnapshotIfNeeded(); - Persist(new EntityStarted(id), SendMessageBuffer); - } - else - child.Tell(payload, sender); - } - - public static Actor.Props Props(string typeName, ShardId shardId, Props entryProps, ClusterShardingSettings settings, IdExtractor idExtractor, ShardResolver shardResolver, object handOffStopMessage) - { - return Actor.Props.Create(() => new PersistentShard(typeName, shardId, entryProps, settings, idExtractor, shardResolver, handOffStopMessage)).WithDeploy(Deploy.Local); - } - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Sharding/PersistentShardCoordinator.Messages.cs b/src/contrib/cluster/Akka.Cluster.Sharding/PersistentShardCoordinator.Messages.cs deleted file mode 100644 index cd2e3e66741..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Sharding/PersistentShardCoordinator.Messages.cs +++ /dev/null @@ -1,319 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using System.Collections.Generic; -using Akka.Actor; - -namespace Akka.Cluster.Sharding -{ - using ShardId = String; - - partial class PersistentShardCoordinator - { - #region Message types - - /// - /// Messages sent to the coordinator. - /// - public interface ICoordinatorCommand : IClusterShardingSerializable { } - - /// - /// Messages sent from the coordinator. - /// - public interface ICoordinatorMessage : IClusterShardingSerializable { } - - /// - /// registers to , until it receives . - /// - [Serializable] - public sealed class Register : ICoordinatorCommand - { - public readonly IActorRef ShardRegion; - - public Register(IActorRef shardRegion) - { - ShardRegion = shardRegion; - } - } - - /// - /// in proxy only mode registers to , until it receives . - /// - [Serializable] - public sealed class RegisterProxy : ICoordinatorCommand - { - public readonly IActorRef ShardRegionProxy; - - public RegisterProxy(IActorRef shardRegionProxy) - { - ShardRegionProxy = shardRegionProxy; - } - } - - /// - /// Acknowledgement from that or was sucessful. - /// - public sealed class RegisterAck : ICoordinatorMessage - { - public readonly IActorRef Coordinator; - - public RegisterAck(IActorRef coordinator) - { - Coordinator = coordinator; - } - } - - /// - /// requests the location of a shard by sending this message - /// to the . - /// - [Serializable] - public sealed class GetShardHome : ICoordinatorCommand - { - public readonly ShardId Shard; - - public GetShardHome(string shard) - { - Shard = shard; - } - } - - /// - /// replies with this message for requests. - /// - [Serializable] - public sealed class ShardHome : ICoordinatorMessage - { - public readonly ShardId Shard; - public readonly IActorRef Ref; - - public ShardHome(string shard, IActorRef @ref) - { - Shard = shard; - Ref = @ref; - } - } - - /// - /// informs a that it is hosting this shard - /// - [Serializable] - public sealed class HostShard : ICoordinatorMessage - { - public readonly ShardId Shard; - - public HostShard(string shard) - { - Shard = shard; - } - } - - /// - /// replies with this message for requests which lead to it hosting the shard - /// - [Serializable] - public sealed class ShardStarted : ICoordinatorMessage - { - public readonly ShardId Shard; - - public ShardStarted(string shard) - { - Shard = shard; - } - } - - /// - /// initiates rebalancing process by sending this message - /// to all registered actors (including proxy only). They are - /// supposed to discard their known location of the shard, i.e. start buffering - /// incoming messages for the shard. They reply with . - /// When all have replied the continues by sending - /// to the responsible for the shard. - /// - [Serializable] - public sealed class BeginHandOff : ICoordinatorMessage - { - public readonly ShardId Shard; - - public BeginHandOff(string shard) - { - Shard = shard; - } - } - - /// - /// Acknowledgement of - /// - [Serializable] - public sealed class BeginHandOffAck : ICoordinatorCommand - { - public readonly ShardId Shard; - - public BeginHandOffAck(string shard) - { - Shard = shard; - } - } - - /// - /// When all actors have acknoledged the the - /// sends this message to the responsible for the - /// shard. The is supposed to stop all entries in that shard and when - /// all entries have terminated reply with to the . - /// - [Serializable] - public sealed class HandOff : ICoordinatorMessage - { - public readonly ShardId Shard; - - public HandOff(string shard) - { - Shard = shard; - } - } - - /// - /// Reply to when all entries in the shard have been terminated. - /// - [Serializable] - public sealed class ShardStopped : ICoordinatorCommand - { - public readonly ShardId Shard; - - public ShardStopped(string shard) - { - Shard = shard; - } - } - - /// - /// Result of is piped to self with this message. - /// - [Serializable] - public sealed class AllocateShardResult : ICoordinatorCommand - { - public readonly ShardId Shard; - public readonly IActorRef ShardRegion; // option - public readonly IActorRef GetShardHomeSender; - - public AllocateShardResult(string shard, IActorRef shardRegion, IActorRef getShardHomeSender) - { - Shard = shard; - ShardRegion = shardRegion; - GetShardHomeSender = getShardHomeSender; - } - } - - /// - /// Result of `rebalance` is piped to self with this message. - /// - [Serializable] - public sealed class RebalanceResult : ICoordinatorCommand - { - public readonly IEnumerable Shards; - - public RebalanceResult(IEnumerable shards) - { - Shards = shards; - } - } - - /// - /// requests full handoff to be able to shutdown gracefully. - /// - [Serializable] - public sealed class GracefulShutdownRequest : ICoordinatorCommand - { - public readonly IActorRef ShardRegion; - public GracefulShutdownRequest(IActorRef shardRegion) - { - ShardRegion = shardRegion; - } - } - - /// - /// DomainEvents for the persistent state of the event sourced PersistentShardCoordinator - /// - public interface IDomainEvent { } - - [Serializable] - public class ShardRegionRegistered : IDomainEvent - { - public readonly IActorRef Region; - - public ShardRegionRegistered(IActorRef region) - { - Region = region; - } - } - - [Serializable] - public class ShardRegionProxyRegistered : IDomainEvent - { - public readonly IActorRef RegionProxy; - public ShardRegionProxyRegistered(IActorRef regionProxy) - { - RegionProxy = regionProxy; - } - } - - [Serializable] - public class ShardRegionTerminated : IDomainEvent - { - public readonly IActorRef Region; - public ShardRegionTerminated(IActorRef region) - { - Region = region; - } - } - - [Serializable] - public class ShardRegionProxyTerminated : IDomainEvent - { - public readonly IActorRef RegionProxy; - public ShardRegionProxyTerminated(IActorRef regionProxy) - { - RegionProxy = regionProxy; - } - } - - [Serializable] - public class ShardHomeAllocated : IDomainEvent - { - public readonly ShardId Shard; - public readonly IActorRef Region; - - public ShardHomeAllocated(string shard, IActorRef region) - { - Shard = shard; - Region = region; - } - } - - [Serializable] - public class ShardHomeDeallocated : IDomainEvent - { - public readonly ShardId Shard; - - public ShardHomeDeallocated(string shard) - { - Shard = shard; - } - } - - [Serializable] - public sealed class StateInitialized - { - public static readonly StateInitialized Instance = new StateInitialized(); - private StateInitialized() { } - } - - #endregion - - } -} diff --git a/src/contrib/cluster/Akka.Cluster.Sharding/PersistentShardCoordinator.cs b/src/contrib/cluster/Akka.Cluster.Sharding/PersistentShardCoordinator.cs deleted file mode 100644 index 6bd92586bd9..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Sharding/PersistentShardCoordinator.cs +++ /dev/null @@ -1,668 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Linq; -using System.Threading.Tasks; -using Akka.Actor; -using Akka.Event; -using Akka.Persistence; - -namespace Akka.Cluster.Sharding -{ - using ShardId = String; - - /// - /// Singleton coordinator that decides where shards should be allocated. - /// - public partial class PersistentShardCoordinator : PersistentActor - { - #region State data type definition - - /// - /// Persistent state of the event sourced PersistentShardCoordinator. - /// - [Serializable] - public sealed class State - { - public static readonly State Empty = new State(); - - /// - /// Region for each shard. - /// - public readonly IImmutableDictionary Shards; - - /// - /// Shards for each region. - /// - public readonly IImmutableDictionary> Regions; - public readonly IImmutableSet RegionProxies; - public readonly IImmutableSet UnallocatedShards; - - private State() : this( - shards: ImmutableDictionary.Empty, - regions: ImmutableDictionary>.Empty, - regionProxies: ImmutableHashSet.Empty, - unallocatedShards: ImmutableHashSet.Empty) - { } - - public State( - IImmutableDictionary shards, - IImmutableDictionary> regions, - IImmutableSet regionProxies, - IImmutableSet unallocatedShards) - { - Shards = shards; - Regions = regions; - RegionProxies = regionProxies; - UnallocatedShards = unallocatedShards; - } - - public State Updated(IDomainEvent e) - { - if (e is ShardRegionRegistered) - { - var message = e as ShardRegionRegistered; - if (Regions.ContainsKey(message.Region)) throw new ArgumentException(string.Format("Region {0} is already registered", message.Region)); - - return Copy(regions: Regions.SetItem(message.Region, ImmutableList.Empty)); - } - else if (e is ShardRegionProxyRegistered) - { - var message = e as ShardRegionProxyRegistered; - if (RegionProxies.Contains(message.RegionProxy)) throw new ArgumentException(string.Format("Region proxy {0} is already registered", message.RegionProxy)); - - return Copy(regionProxies: RegionProxies.Add(message.RegionProxy)); - } - else if (e is ShardRegionTerminated) - { - IImmutableList shardRegions; - var message = e as ShardRegionTerminated; - if (!Regions.TryGetValue(message.Region, out shardRegions)) throw new ArgumentException(string.Format("Region {0} not registered", message.Region)); - - return Copy( - regions: Regions.Remove(message.Region), - shards: Shards.RemoveRange(shardRegions), - unallocatedShards: shardRegions.Aggregate(UnallocatedShards, (set, shard) => set.Add(shard))); - } - else if (e is ShardRegionProxyTerminated) - { - var message = e as ShardRegionProxyTerminated; - if (!RegionProxies.Contains(message.RegionProxy)) throw new ArgumentException(string.Format("Region proxy {0} not registered", message.RegionProxy)); - - return Copy(regionProxies: RegionProxies.Remove(message.RegionProxy)); - } - else if (e is ShardHomeAllocated) - { - IImmutableList shardRegions; - var message = e as ShardHomeAllocated; - if (!Regions.TryGetValue(message.Region, out shardRegions)) throw new ArgumentException(string.Format("Region {0} not registered", message.Region)); - if (Shards.ContainsKey(message.Shard)) throw new ArgumentException(string.Format("Shard {0} is already allocated", message.Shard)); - - return Copy( - shards: Shards.SetItem(message.Shard, message.Region), - regions: Regions.SetItem(message.Region, shardRegions.Add(message.Shard)), - unallocatedShards: UnallocatedShards.Remove(message.Shard)); - } - else if (e is ShardHomeDeallocated) - { - IActorRef region; - IImmutableList shardRegions; - var message = e as ShardHomeDeallocated; - if (!Shards.TryGetValue(message.Shard, out region)) throw new ArgumentException(string.Format("Shard {0} not allocated", message.Shard)); - if (!Regions.TryGetValue(region, out shardRegions)) throw new ArgumentException(string.Format("Region {0} for shard {1} not registered", region, message.Shard)); - - return Copy( - shards: Shards.Remove(message.Shard), - regions: Regions.SetItem(region, shardRegions.Where(s => s != message.Shard).ToImmutableList()), - unallocatedShards: UnallocatedShards.Add(message.Shard)); - } - else return this; - } - - public State Copy(IImmutableDictionary shards = null, - IImmutableDictionary> regions = null, - IImmutableSet regionProxies = null, - IImmutableSet unallocatedShards = null) - { - if (shards == null && regions == null && regionProxies == null && unallocatedShards == null) return this; - - return new State(shards ?? Shards, regions ?? Regions, regionProxies ?? RegionProxies, unallocatedShards ?? UnallocatedShards); - } - } - - #endregion - - /// - /// Factory method for the of the actor. - /// - public static Props Props(string typeName, ClusterShardingSettings settings, IShardAllocationStrategy allocationStrategy) - { - return Actor.Props.Create(() => new PersistentShardCoordinator(typeName, settings, allocationStrategy)).WithDeploy(Deploy.Local); - } - - public readonly Cluster Cluster = Cluster.Get(Context.System); - public readonly TimeSpan DownRemovalMargin; - public readonly string TypeName; - public readonly ClusterShardingSettings Settings; - public readonly IShardAllocationStrategy AllocationStrategy; - - private IImmutableDictionary _unAckedHostShards = ImmutableDictionary.Empty; - private IImmutableSet _rebalanceInProgress = ImmutableHashSet.Empty; - // regions that have requested handoff, for graceful shutdown - private IImmutableSet _gracefullShutdownInProgress = ImmutableHashSet.Empty; - private IImmutableSet _aliveRegions = ImmutableHashSet.Empty; - private IImmutableSet _regionTerminationInProgress = ImmutableHashSet.Empty; - - private readonly ICancelable _rebalanceTask; - - private int _persistCount = 0; - private State _currentState = State.Empty; - - public PersistentShardCoordinator(string typeName, ClusterShardingSettings settings, IShardAllocationStrategy allocationStrategy) - { - TypeName = typeName; - Settings = settings; - AllocationStrategy = allocationStrategy; - DownRemovalMargin = Cluster.Settings.DownRemovalMargin; - - JournalPluginId = Settings.JournalPluginId; - SnapshotPluginId = Settings.SnapshotPluginId; - - _rebalanceTask = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(Settings.TunningParameters.RebalanceInterval, Settings.TunningParameters.RebalanceInterval, Self, RebalanceTick.Instance, Self); - - Cluster.Subscribe(Self, ClusterEvent.SubscriptionInitialStateMode.InitialStateAsEvents, new[] { typeof(ClusterEvent.ClusterShuttingDown) }); - } - - private ILoggingAdapter _log; - public ILoggingAdapter Log { get { return _log ?? (_log = Context.GetLogger()); } } - protected State CurrentState { get { return _currentState; } } - - #region shared part - - protected override void PostStop() - { - base.PostStop(); - _rebalanceTask.Cancel(); - Cluster.Unsubscribe(Self); - } - - private bool IsMember(IActorRef region) - { - var addr = region.Path.Address; - return addr == Self.Path.Address || Cluster.ReadView.Members.Any(m => m.Address == addr && m.Status == MemberStatus.Up); - } - - protected bool Active(object message) - { - if (message is Register) HandleRegister(message as Register); - else if (message is RegisterProxy) HandleRegisterProxy(message as RegisterProxy); - else if (message is GetShardHome) HandleGetShardHome(message as GetShardHome); - else if (message is AllocateShardResult) HandleAllocateShardResult(message as AllocateShardResult); - else if (message is ShardStarted) HandleShardStated(message as ShardStarted); - else if (message is ResendShardHost) HandleResendShardHost(message as ResendShardHost); - else if (message is RebalanceTick) HandleRebalanceTick(); - else if (message is RebalanceResult) ContinueRebalance(((RebalanceResult)message).Shards.ToImmutableHashSet()); - else if (message is RebalanceDone) HandleRebalanceDone(message as RebalanceDone); - else if (message is GracefulShutdownRequest) HandleGracefulShutdownRequest(message as GracefulShutdownRequest); - else if (message is ShardHome) - { - // On rebalance, we send ourselves a GetShardHome message to reallocate a - // shard. This recieve handles the "response" from that message. i.e. Ingores it. - } - else if (message is ClusterEvent.ClusterShuttingDown) - { - Log.Debug("Shutting down shard coordinator"); - // can't stop because supervisor will start it again, - // it will soon be stopped when singleton is stopped - Context.Become(ShuttingDown); - } - else if (message is ShardRegion.GetCurrentRegions) - { - var regions = _currentState.Regions.Keys - .Select(region => string.IsNullOrEmpty(region.Path.Address.Host) ? Cluster.SelfAddress : region.Path.Address) - .ToArray(); - Sender.Tell(new ShardRegion.CurrentRegions(regions)); - } - else if (message is ClusterEvent.CurrentClusterState) - { - /* ignore */ - } - else return ReceiveTerminated(message); - return true; - } - - private void AllocateShardHomes() - { - foreach (var unallocatedShard in _currentState.UnallocatedShards) - { - Self.Tell(new GetShardHome(unallocatedShard)); - } - } - - private void SendHostShardMessage(String shard, IActorRef region) - { - region.Tell(new HostShard(shard)); - var cancelable = new Cancelable(Context.System.Scheduler); - Context.System.Scheduler.ScheduleTellOnce(Settings.TunningParameters.ShardStartTimeout, Self, new ResendShardHost(shard, region), Self, cancelable); - _unAckedHostShards = _unAckedHostShards.SetItem(shard, cancelable); - } - - protected void ApplyStateInitialized() - { - foreach (var entry in _currentState.Shards) - SendHostShardMessage(entry.Key, entry.Value); - - AllocateShardHomes(); - } - - private void WatchStateActors() - { - // Optimization: - // Consider regions that don't belong to the current cluster to be terminated. - // This is an optimization that makes it operational faster and reduces the - // amount of lost messages during startup. - var nodes = Cluster.ReadView.Members.Select(x => x.Address).ToImmutableHashSet(); - - foreach (var entry in _currentState.Regions) - { - var a = entry.Key.Path.Address; - if ((string.IsNullOrEmpty(a.Host) && a.Port == null) || nodes.Contains(a)) - Context.Watch(entry.Key); - else - RegionTerminated(entry.Key); // not part of the cluster - } - - foreach (var proxy in _currentState.RegionProxies) - { - var a = proxy.Path.Address; - if ((string.IsNullOrEmpty(a.Host) && a.Port == null) || nodes.Contains(a)) - Context.Watch(proxy); - else - RegionTerminated(proxy); // not part of the cluster - } - - // Let the quick (those not involving failure detection) Terminated messages - // be processed before starting to reply to GetShardHome. - // This is an optimization that makes it operational faster and reduces the - // amount of lost messages during startup. - Context.System.Scheduler.ScheduleTellOnce(TimeSpan.FromMilliseconds(500), Self, StateInitialized.Instance, Self); - } - - private bool ReceiveTerminated(object message) - { - if (message is Terminated) - { - var terminated = (Terminated)message; - var terminatedRef = terminated.ActorRef; - if (_currentState.Regions.ContainsKey(terminatedRef)) - { - if (DownRemovalMargin != TimeSpan.Zero && terminated.AddressTerminated && _aliveRegions.Contains(terminatedRef)) - { - Context.System.Scheduler.ScheduleTellOnce(DownRemovalMargin, Self, new DelayedShardRegionTerminated(terminatedRef), Self); - _regionTerminationInProgress = _regionTerminationInProgress.Add(terminatedRef); - } - else - RegionTerminated(terminatedRef); - } - else if (_currentState.RegionProxies.Contains(terminatedRef)) - RegionProxyTerminated(terminatedRef); - } - else if (message is DelayedShardRegionTerminated) - RegionTerminated(((DelayedShardRegionTerminated)message).Region); - else return false; - return true; - } - - private void HandleGracefulShutdownRequest(GracefulShutdownRequest request) - { - if (!_gracefullShutdownInProgress.Contains(request.ShardRegion)) - { - IImmutableList shards; - if (_currentState.Regions.TryGetValue(request.ShardRegion, out shards)) - { - Log.Debug("Graceful shutdown of region [{0}] with shards [{1}]", request.ShardRegion, string.Join(", ", shards)); - _gracefullShutdownInProgress = _gracefullShutdownInProgress.Add(request.ShardRegion); - ContinueRebalance(shards.ToImmutableHashSet()); - } - } - } - - private void HandleRebalanceDone(RebalanceDone done) - { - _rebalanceInProgress = _rebalanceInProgress.Remove(done.Shard); - Log.Debug("Rebalance shard [{0}] done [{1}]", done.Shard, done.Ok); - - IActorRef region; - // The shard could have been removed by ShardRegionTerminated - if (_currentState.Shards.ContainsKey(done.Shard)) - { - if (done.Ok) - Update(new ShardHomeDeallocated(done.Shard), e => - { - _currentState = _currentState.Updated(e); - Log.Debug("Shard [{0}] deallocated", e.Shard); - AllocateShardHomes(); - }); - else if (_currentState.Shards.TryGetValue(done.Shard, out region)) - // rebalance not completed, graceful shutdown will be retried - _gracefullShutdownInProgress = _gracefullShutdownInProgress.Remove(region); - } - } - - private void HandleRebalanceTick() - { - if (_currentState.Regions.Count != 0) - { - var shardsTask = AllocationStrategy.Rebalance(_currentState.Regions, _rebalanceInProgress); - if (shardsTask.IsCompleted && !shardsTask.IsFaulted) - ContinueRebalance(shardsTask.Result); - else - shardsTask.ContinueWith(t => !(t.IsFaulted || t.IsCanceled) - ? new RebalanceResult(t.Result) - : new RebalanceResult(Enumerable.Empty())) - .PipeTo(Self); - } - } - - private void HandleResendShardHost(ResendShardHost resend) - { - IActorRef region; - if (_currentState.Shards.TryGetValue(resend.Shard, out region) && region.Equals(resend.Region)) - SendHostShardMessage(resend.Shard, region); - } - - private void HandleShardStated(ShardStarted message) - { - var shard = message.Shard; - ICancelable cancel; - if (_unAckedHostShards.TryGetValue(shard, out cancel)) - { - cancel.Cancel(); - _unAckedHostShards = _unAckedHostShards.Remove(shard); - } - } - - private void HandleAllocateShardResult(AllocateShardResult allocateResult) - { - if (allocateResult.ShardRegion == null) - Log.Debug("Shard [{0}] allocation failed. It will be retried", allocateResult.Shard); - else - ContinueGetShardHome(allocateResult.Shard, allocateResult.ShardRegion, allocateResult.GetShardHomeSender); - } - - private void HandleGetShardHome(GetShardHome getShardHome) - { - var shard = getShardHome.Shard; - if (!_rebalanceInProgress.Contains(shard)) - { - IActorRef region; - if (_currentState.Shards.TryGetValue(shard, out region)) - { - if (_regionTerminationInProgress.Contains(region)) - Log.Debug("GetShardHome [{0}] request ignored, due to region [{1}] termination in progress.", shard, region); - else - Sender.Tell(new ShardHome(shard, region)); - } - else - { - var activeRegions = _currentState.Regions.RemoveRange(_gracefullShutdownInProgress); - if (activeRegions.Count != 0) - { - var getShardHomeSender = Sender; - var regionTask = AllocationStrategy.AllocateShard(getShardHomeSender, shard, activeRegions); - - // if task completed immediately, just continue - if (regionTask.IsCompleted && !regionTask.IsFaulted) - ContinueGetShardHome(shard, regionTask.Result, getShardHomeSender); - else - regionTask.ContinueWith(t => !(t.IsFaulted || t.IsCanceled) - ? new AllocateShardResult(shard, t.Result, getShardHomeSender) - : new AllocateShardResult(shard, null, getShardHomeSender)) - .PipeTo(Self); - } - } - } - } - - private void RegionTerminated(IActorRef terminatedRef) - { - IImmutableList shards; - if (_currentState.Regions.TryGetValue(terminatedRef, out shards)) - { - Log.Debug("Shard region terminated: [{0}]", terminatedRef); - foreach (var shard in shards) - Self.Tell(new GetShardHome(shard)); - - Update(new ShardRegionTerminated(terminatedRef), e => - { - _currentState = _currentState.Updated(e); - _gracefullShutdownInProgress = _gracefullShutdownInProgress.Remove(terminatedRef); - _regionTerminationInProgress = _regionTerminationInProgress.Remove(terminatedRef); - AllocateShardHomes(); - }); - } - } - - private void RegionProxyTerminated(IActorRef proxyRef) - { - if (_currentState.RegionProxies.Contains(proxyRef)) - { - Log.Debug("ShardRegion proxy terminated: [{0}]", proxyRef); - Update(new ShardRegionProxyTerminated(proxyRef), e => _currentState = _currentState.Updated(e)); - } - } - - private void HandleRegisterProxy(RegisterProxy registerProxy) - { - var proxy = registerProxy.ShardRegionProxy; - Log.Debug("Shard region proxy registered: [{0}]", proxy); - if (_currentState.RegionProxies.Contains(proxy)) - Sender.Tell(new RegisterAck(Self)); - else - { - var context = Context; - var self = Self; - Update(new ShardRegionProxyRegistered(proxy), e => - { - _currentState = _currentState.Updated(e); - context.Watch(proxy); - proxy.Tell(new RegisterAck(self)); - }); - } - } - - private void HandleRegister(Register message) - { - var region = message.ShardRegion; - if (IsMember(region)) - { - Log.Debug("Shard region registered: [{0}]", region); - _aliveRegions = _aliveRegions.Add(region); - - if (_currentState.Regions.ContainsKey(region)) - Sender.Tell(new RegisterAck(Self)); - else - { - var context = Context; - var self = Self; - - _gracefullShutdownInProgress = _gracefullShutdownInProgress.Remove(region); - Update(new ShardRegionRegistered(region), e => - { - var isFirstRegion = _currentState.Regions.Count == 0; - _currentState = _currentState.Updated(e); - context.Watch(region); - region.Tell(new RegisterAck(self)); - - if (isFirstRegion) AllocateShardHomes(); - }); - } - } - else Log.Debug("ShardRegion [{0}] was not registered since the coordinator currently does not know about a node of that region", region); - } - - private void SaveSnapshotIfNeeded() - { - _persistCount++; - if (_persistCount % Settings.TunningParameters.SnapshotAfter == 0) - { - Log.Debug("Saving snapshot, sequence number [{0}]", SnapshotSequenceNr); - SaveSnapshot(_currentState); - } - } - - private bool ShuttingDown(object message) - { - // ignore all - return true; - } - - private void ContinueRebalance(IImmutableSet shards) - { - foreach (var shard in shards) - { - if (!_rebalanceInProgress.Contains(shard)) - { - IActorRef rebalanceFromRegion; - if (_currentState.Shards.TryGetValue(shard, out rebalanceFromRegion)) - { - _rebalanceInProgress = _rebalanceInProgress.Add(shard); - Log.Debug("Rebalance shard [{0}] from [{1}]", shard, rebalanceFromRegion); - - var regions = _currentState.Regions.Keys.Union(_currentState.RegionProxies); - Context.ActorOf(RebalanceWorker.Props(shard, rebalanceFromRegion, Settings.TunningParameters.HandOffTimeout, regions) - .WithDispatcher(Context.Props.Dispatcher)); - } - else - Log.Debug("Rebalance of non-existing shard [{0}] is ignored", shard); - } - } - } - - private void ContinueGetShardHome(string shard, IActorRef region, IActorRef getShardHomeSender) - { - if (!_rebalanceInProgress.Contains(shard)) - { - IActorRef aref; - if (_currentState.Shards.TryGetValue(shard, out aref)) - getShardHomeSender.Tell(new ShardHome(shard, aref)); - else - { - if (_currentState.Regions.ContainsKey(region) && !_gracefullShutdownInProgress.Contains(region)) - { - Update(new ShardHomeAllocated(shard, region), e => - { - _currentState = _currentState.Updated(e); - Log.Debug("Shard [{0}] allocated at [{1}]", e.Shard, e.Region); - - SendHostShardMessage(e.Shard, e.Region); - getShardHomeSender.Tell(new ShardHome(e.Shard, e.Region)); - }); - } - else - Log.Debug("Allocated region {0} for shard [{1}] is not (any longer) one of the registered regions", region, shard); - } - } - } - - #endregion - - #region persistent part - - public override String PersistenceId { get { return Self.Path.ToStringWithoutAddress(); } } - - protected override bool ReceiveRecover(Object message) - { - if (message is IDomainEvent) - { - var evt = message as IDomainEvent; - Log.Debug("ReceiveRecover {0}", evt); - - if (message is ShardRegionRegistered) _currentState = _currentState.Updated(evt); - else if (message is ShardRegionProxyRegistered) _currentState = _currentState.Updated(evt); - else if (message is ShardRegionTerminated) - { - var regionTerminated = (ShardRegionTerminated)message; - if (_currentState.Regions.ContainsKey(regionTerminated.Region)) - _currentState = _currentState.Updated(evt); - else - Log.Debug("ShardRegionTerminated but region {0} was not registered", regionTerminated.Region); - } - else if (message is ShardRegionProxyTerminated) - { - var proxyTerminated = (ShardRegionProxyTerminated)message; - if (_currentState.RegionProxies.Contains(proxyTerminated.RegionProxy)) - _currentState = _currentState.Updated(evt); - } - else if (message is ShardHomeAllocated) _currentState = _currentState.Updated(evt); - else if (message is ShardHomeDeallocated) _currentState = _currentState.Updated(evt); - else return false; - return true; - } - else if (message is SnapshotOffer) - { - var state = ((SnapshotOffer)message).Snapshot as State; - if (state != null) - { - Log.Debug("ReceiveRecover SnapshotOffer {0}", state); - - // Old versions of the state object may not have unallocatedShard set, - // thus it will be null. - if (state.UnallocatedShards == null) - _currentState = state.Copy(unallocatedShards: ImmutableHashSet.Empty); - else - _currentState = state; - - return true; - } - } - else if (message is RecoveryCompleted) - { - WatchStateActors(); - return true; - } - return false; - } - - protected override bool ReceiveCommand(object message) - { - return WaitingForStateInitialized(message); - } - - private bool WaitingForStateInitialized(object message) - { - if (message is StateInitialized) - { - ApplyStateInitialized(); - Context.Become(msg => Active(msg) || HandleSnapshotResult(msg)); - return true; - } - else if (ReceiveTerminated(message)) return true; - else return HandleSnapshotResult(message); - } - - private bool HandleSnapshotResult(object message) - { - if (message is SaveSnapshotSuccess) Log.Debug("Persistent snapshot saved successfully"); - else if (message is SaveSnapshotFailure) Log.Warning("Persistent snapshot failure: {0}", ((SaveSnapshotFailure)message).Cause.Message); - else return false; - return true; - } - - protected void Update(TEvent e, Action handler) where TEvent : IDomainEvent - { - SaveSnapshotIfNeeded(); - Persist(e, handler); - } - - #endregion - } - -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Sharding/Properties/AssemblyInfo.cs b/src/contrib/cluster/Akka.Cluster.Sharding/Properties/AssemblyInfo.cs deleted file mode 100644 index e4b191ab2d8..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Sharding/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Akka.Cluster.Sharding")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Akka.Cluster.Sharding")] -[assembly: AssemblyCopyright("Copyright © 2015")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("a05c31e8-0246-46a1-b3bc-4d6fe7a9aa49")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/contrib/cluster/Akka.Cluster.Sharding/Serialization/Proto/ClusterShardingMessages.cs b/src/contrib/cluster/Akka.Cluster.Sharding/Serialization/Proto/ClusterShardingMessages.cs deleted file mode 100644 index c0ceeec3270..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Sharding/Serialization/Proto/ClusterShardingMessages.cs +++ /dev/null @@ -1,3640 +0,0 @@ -// Generated by ProtoGen, Version=2.4.1.521, Culture=neutral, PublicKeyToken=55f7125234beb589. DO NOT EDIT! -#pragma warning disable 1591, 0612, 3021 -#region Designer generated code - -using pb = global::Google.ProtocolBuffers; -using pbc = global::Google.ProtocolBuffers.Collections; -using pbd = global::Google.ProtocolBuffers.Descriptors; -using scg = global::System.Collections.Generic; -[global::System.Diagnostics.DebuggerNonUserCodeAttribute()] -public static partial class ClusterShardingMessages -{ - - #region Extension registration - public static void RegisterAllExtensions(pb::ExtensionRegistry registry) - { - } - #endregion - #region Static variables - internal static pbd::MessageDescriptor internal__static_CoordinatorState__Descriptor; - internal static pb::FieldAccess.FieldAccessorTable internal__static_CoordinatorState__FieldAccessorTable; - internal static pbd::MessageDescriptor internal__static_CoordinatorState_ShardEntry__Descriptor; - internal static pb::FieldAccess.FieldAccessorTable internal__static_CoordinatorState_ShardEntry__FieldAccessorTable; - internal static pbd::MessageDescriptor internal__static_ActorRefMessage__Descriptor; - internal static pb::FieldAccess.FieldAccessorTable internal__static_ActorRefMessage__FieldAccessorTable; - internal static pbd::MessageDescriptor internal__static_ShardIdMessage__Descriptor; - internal static pb::FieldAccess.FieldAccessorTable internal__static_ShardIdMessage__FieldAccessorTable; - internal static pbd::MessageDescriptor internal__static_ShardHomeAllocated__Descriptor; - internal static pb::FieldAccess.FieldAccessorTable internal__static_ShardHomeAllocated__FieldAccessorTable; - internal static pbd::MessageDescriptor internal__static_ShardHome__Descriptor; - internal static pb::FieldAccess.FieldAccessorTable internal__static_ShardHome__FieldAccessorTable; - internal static pbd::MessageDescriptor internal__static_EntityState__Descriptor; - internal static pb::FieldAccess.FieldAccessorTable internal__static_EntityState__FieldAccessorTable; - internal static pbd::MessageDescriptor internal__static_EntityStarted__Descriptor; - internal static pb::FieldAccess.FieldAccessorTable internal__static_EntityStarted__FieldAccessorTable; - internal static pbd::MessageDescriptor internal__static_EntityStopped__Descriptor; - internal static pb::FieldAccess.FieldAccessorTable internal__static_EntityStopped__FieldAccessorTable; - #endregion - #region Descriptor - public static pbd::FileDescriptor Descriptor - { - get { return descriptor; } - } - private static pbd::FileDescriptor descriptor; - - static ClusterShardingMessages() - { - byte[] descriptorData = global::System.Convert.FromBase64String( - "Ch1DbHVzdGVyU2hhcmRpbmdNZXNzYWdlcy5wcm90byK1AQoQQ29vcmRpbmF0" + - "b3JTdGF0ZRIsCgZzaGFyZHMYASADKAsyHC5Db29yZGluYXRvclN0YXRlLlNo" + - "YXJkRW50cnkSDwoHcmVnaW9ucxgCIAMoCRIVCg1yZWdpb25Qcm94aWVzGAMg" + - "AygJEhkKEXVuYWxsb2NhdGVkU2hhcmRzGAQgAygJGjAKClNoYXJkRW50cnkS" + - "DwoHc2hhcmRJZBgBIAIoCRIRCglyZWdpb25SZWYYAiACKAkiHgoPQWN0b3JS" + - "ZWZNZXNzYWdlEgsKA3JlZhgBIAIoCSIfCg5TaGFyZElkTWVzc2FnZRINCgVz" + - "aGFyZBgBIAIoCSIzChJTaGFyZEhvbWVBbGxvY2F0ZWQSDQoFc2hhcmQYASAC" + - "KAkSDgoGcmVnaW9uGAIgAigJIioKCVNoYXJkSG9tZRINCgVzaGFyZBgBIAIo" + - "CRIOCgZyZWdpb24YAiACKAkiHwoLRW50aXR5U3RhdGUSEAoIZW50aXRpZXMY" + - "ASADKAkiIQoNRW50aXR5U3RhcnRlZBIQCghlbnRpdHlJZBgBIAIoCSIhCg1F" + - "bnRpdHlTdG9wcGVkEhAKCGVudGl0eUlkGAEgAigJQiYKImFra2EuY2x1c3Rl" + - "ci5zaGFyZGluZy5wcm90b2J1Zi5tc2dIAQ=="); - pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate (pbd::FileDescriptor root) { - descriptor = root; - internal__static_CoordinatorState__Descriptor = Descriptor.MessageTypes[0]; - internal__static_CoordinatorState__FieldAccessorTable = - new pb::FieldAccess.FieldAccessorTable(internal__static_CoordinatorState__Descriptor, - new string[] { "Shards", "Regions", "RegionProxies", "UnallocatedShards", }); - internal__static_CoordinatorState_ShardEntry__Descriptor = internal__static_CoordinatorState__Descriptor.NestedTypes[0]; - internal__static_CoordinatorState_ShardEntry__FieldAccessorTable = - new pb::FieldAccess.FieldAccessorTable(internal__static_CoordinatorState_ShardEntry__Descriptor, - new string[] { "ShardId", "RegionRef", }); - internal__static_ActorRefMessage__Descriptor = Descriptor.MessageTypes[1]; - internal__static_ActorRefMessage__FieldAccessorTable = - new pb::FieldAccess.FieldAccessorTable(internal__static_ActorRefMessage__Descriptor, - new string[] { "Ref", }); - internal__static_ShardIdMessage__Descriptor = Descriptor.MessageTypes[2]; - internal__static_ShardIdMessage__FieldAccessorTable = - new pb::FieldAccess.FieldAccessorTable(internal__static_ShardIdMessage__Descriptor, - new string[] { "Shard", }); - internal__static_ShardHomeAllocated__Descriptor = Descriptor.MessageTypes[3]; - internal__static_ShardHomeAllocated__FieldAccessorTable = - new pb::FieldAccess.FieldAccessorTable(internal__static_ShardHomeAllocated__Descriptor, - new string[] { "Shard", "Region", }); - internal__static_ShardHome__Descriptor = Descriptor.MessageTypes[4]; - internal__static_ShardHome__FieldAccessorTable = - new pb::FieldAccess.FieldAccessorTable(internal__static_ShardHome__Descriptor, - new string[] { "Shard", "Region", }); - internal__static_EntityState__Descriptor = Descriptor.MessageTypes[5]; - internal__static_EntityState__FieldAccessorTable = - new pb::FieldAccess.FieldAccessorTable(internal__static_EntityState__Descriptor, - new string[] { "Entities", }); - internal__static_EntityStarted__Descriptor = Descriptor.MessageTypes[6]; - internal__static_EntityStarted__FieldAccessorTable = - new pb::FieldAccess.FieldAccessorTable(internal__static_EntityStarted__Descriptor, - new string[] { "EntityId", }); - internal__static_EntityStopped__Descriptor = Descriptor.MessageTypes[7]; - internal__static_EntityStopped__FieldAccessorTable = - new pb::FieldAccess.FieldAccessorTable(internal__static_EntityStopped__Descriptor, - new string[] { "EntityId", }); - return null; - }; - pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, - new pbd::FileDescriptor[] { - }, assigner); - } - #endregion - -} -#region Messages -[global::System.Diagnostics.DebuggerNonUserCodeAttribute()] -public sealed partial class CoordinatorState : pb::GeneratedMessage -{ - private CoordinatorState() { } - private static readonly CoordinatorState defaultInstance = new CoordinatorState().MakeReadOnly(); - private static readonly string[] _coordinatorStateFieldNames = new string[] { "regionProxies", "regions", "shards", "unallocatedShards" }; - private static readonly uint[] _coordinatorStateFieldTags = new uint[] { 26, 18, 10, 34 }; - public static CoordinatorState DefaultInstance - { - get { return defaultInstance; } - } - - public override CoordinatorState DefaultInstanceForType - { - get { return DefaultInstance; } - } - - protected override CoordinatorState ThisMessage - { - get { return this; } - } - - public static pbd::MessageDescriptor Descriptor - { - get { return global::ClusterShardingMessages.internal__static_CoordinatorState__Descriptor; } - } - - protected override pb::FieldAccess.FieldAccessorTable InternalFieldAccessors - { - get { return global::ClusterShardingMessages.internal__static_CoordinatorState__FieldAccessorTable; } - } - - #region Nested types - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public static partial class Types - { - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class ShardEntry : pb::GeneratedMessage - { - private ShardEntry() { } - private static readonly ShardEntry defaultInstance = new ShardEntry().MakeReadOnly(); - private static readonly string[] _shardEntryFieldNames = new string[] { "regionRef", "shardId" }; - private static readonly uint[] _shardEntryFieldTags = new uint[] { 18, 10 }; - public static ShardEntry DefaultInstance - { - get { return defaultInstance; } - } - - public override ShardEntry DefaultInstanceForType - { - get { return DefaultInstance; } - } - - protected override ShardEntry ThisMessage - { - get { return this; } - } - - public static pbd::MessageDescriptor Descriptor - { - get { return global::ClusterShardingMessages.internal__static_CoordinatorState_ShardEntry__Descriptor; } - } - - protected override pb::FieldAccess.FieldAccessorTable InternalFieldAccessors - { - get { return global::ClusterShardingMessages.internal__static_CoordinatorState_ShardEntry__FieldAccessorTable; } - } - - public const int ShardIdFieldNumber = 1; - private bool hasShardId; - private string shardId_ = ""; - public bool HasShardId - { - get { return hasShardId; } - } - public string ShardId - { - get { return shardId_; } - } - - public const int RegionRefFieldNumber = 2; - private bool hasRegionRef; - private string regionRef_ = ""; - public bool HasRegionRef - { - get { return hasRegionRef; } - } - public string RegionRef - { - get { return regionRef_; } - } - - public override bool IsInitialized - { - get - { - if (!hasShardId) return false; - if (!hasRegionRef) return false; - return true; - } - } - - public override void WriteTo(pb::ICodedOutputStream output) - { - int size = SerializedSize; - string[] field_names = _shardEntryFieldNames; - if (hasShardId) - { - output.WriteString(1, field_names[1], ShardId); - } - if (hasRegionRef) - { - output.WriteString(2, field_names[0], RegionRef); - } - UnknownFields.WriteTo(output); - } - - private int memoizedSerializedSize = -1; - public override int SerializedSize - { - get - { - int size = memoizedSerializedSize; - if (size != -1) return size; - - size = 0; - if (hasShardId) - { - size += pb::CodedOutputStream.ComputeStringSize(1, ShardId); - } - if (hasRegionRef) - { - size += pb::CodedOutputStream.ComputeStringSize(2, RegionRef); - } - size += UnknownFields.SerializedSize; - memoizedSerializedSize = size; - return size; - } - } - - public static ShardEntry ParseFrom(pb::ByteString data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static ShardEntry ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static ShardEntry ParseFrom(byte[] data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static ShardEntry ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static ShardEntry ParseFrom(global::System.IO.Stream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static ShardEntry ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - public static ShardEntry ParseDelimitedFrom(global::System.IO.Stream input) - { - return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); - } - public static ShardEntry ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); - } - public static ShardEntry ParseFrom(pb::ICodedInputStream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static ShardEntry ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - private ShardEntry MakeReadOnly() - { - return this; - } - - public static Builder CreateBuilder() { return new Builder(); } - public override Builder ToBuilder() { return CreateBuilder(this); } - public override Builder CreateBuilderForType() { return new Builder(); } - public static Builder CreateBuilder(ShardEntry prototype) - { - return new Builder(prototype); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class Builder : pb::GeneratedBuilder - { - protected override Builder ThisBuilder - { - get { return this; } - } - public Builder() - { - result = DefaultInstance; - resultIsReadOnly = true; - } - internal Builder(ShardEntry cloneFrom) - { - result = cloneFrom; - resultIsReadOnly = true; - } - - private bool resultIsReadOnly; - private ShardEntry result; - - private ShardEntry PrepareBuilder() - { - if (resultIsReadOnly) - { - ShardEntry original = result; - result = new ShardEntry(); - resultIsReadOnly = false; - MergeFrom(original); - } - return result; - } - - public override bool IsInitialized - { - get { return result.IsInitialized; } - } - - protected override ShardEntry MessageBeingBuilt - { - get { return PrepareBuilder(); } - } - - public override Builder Clear() - { - result = DefaultInstance; - resultIsReadOnly = true; - return this; - } - - public override Builder Clone() - { - if (resultIsReadOnly) - { - return new Builder(result); - } - else - { - return new Builder().MergeFrom(result); - } - } - - public override pbd::MessageDescriptor DescriptorForType - { - get { return global::CoordinatorState.Types.ShardEntry.Descriptor; } - } - - public override ShardEntry DefaultInstanceForType - { - get { return global::CoordinatorState.Types.ShardEntry.DefaultInstance; } - } - - public override ShardEntry BuildPartial() - { - if (resultIsReadOnly) - { - return result; - } - resultIsReadOnly = true; - return result.MakeReadOnly(); - } - - public override Builder MergeFrom(pb::IMessage other) - { - if (other is ShardEntry) - { - return MergeFrom((ShardEntry)other); - } - else - { - base.MergeFrom(other); - return this; - } - } - - public override Builder MergeFrom(ShardEntry other) - { - if (other == global::CoordinatorState.Types.ShardEntry.DefaultInstance) return this; - PrepareBuilder(); - if (other.HasShardId) - { - ShardId = other.ShardId; - } - if (other.HasRegionRef) - { - RegionRef = other.RegionRef; - } - this.MergeUnknownFields(other.UnknownFields); - return this; - } - - public override Builder MergeFrom(pb::ICodedInputStream input) - { - return MergeFrom(input, pb::ExtensionRegistry.Empty); - } - - public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - PrepareBuilder(); - pb::UnknownFieldSet.Builder unknownFields = null; - uint tag; - string field_name; - while (input.ReadTag(out tag, out field_name)) - { - if (tag == 0 && field_name != null) - { - int field_ordinal = global::System.Array.BinarySearch(_shardEntryFieldNames, field_name, global::System.StringComparer.Ordinal); - if (field_ordinal >= 0) - tag = _shardEntryFieldTags[field_ordinal]; - else - { - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - continue; - } - } - switch (tag) - { - case 0: - { - throw pb::InvalidProtocolBufferException.InvalidTag(); - } - default: - { - if (pb::WireFormat.IsEndGroupTag(tag)) - { - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - break; - } - case 10: - { - result.hasShardId = input.ReadString(ref result.shardId_); - break; - } - case 18: - { - result.hasRegionRef = input.ReadString(ref result.regionRef_); - break; - } - } - } - - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - - - public bool HasShardId - { - get { return result.hasShardId; } - } - public string ShardId - { - get { return result.ShardId; } - set { SetShardId(value); } - } - public Builder SetShardId(string value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.hasShardId = true; - result.shardId_ = value; - return this; - } - public Builder ClearShardId() - { - PrepareBuilder(); - result.hasShardId = false; - result.shardId_ = ""; - return this; - } - - public bool HasRegionRef - { - get { return result.hasRegionRef; } - } - public string RegionRef - { - get { return result.RegionRef; } - set { SetRegionRef(value); } - } - public Builder SetRegionRef(string value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.hasRegionRef = true; - result.regionRef_ = value; - return this; - } - public Builder ClearRegionRef() - { - PrepareBuilder(); - result.hasRegionRef = false; - result.regionRef_ = ""; - return this; - } - } - static ShardEntry() - { - object.ReferenceEquals(global::ClusterShardingMessages.Descriptor, null); - } - } - - } - #endregion - - public const int ShardsFieldNumber = 1; - private pbc::PopsicleList shards_ = new pbc::PopsicleList(); - public scg::IList ShardsList - { - get { return shards_; } - } - public int ShardsCount - { - get { return shards_.Count; } - } - public global::CoordinatorState.Types.ShardEntry GetShards(int index) - { - return shards_[index]; - } - - public const int RegionsFieldNumber = 2; - private pbc::PopsicleList regions_ = new pbc::PopsicleList(); - public scg::IList RegionsList - { - get { return pbc::Lists.AsReadOnly(regions_); } - } - public int RegionsCount - { - get { return regions_.Count; } - } - public string GetRegions(int index) - { - return regions_[index]; - } - - public const int RegionProxiesFieldNumber = 3; - private pbc::PopsicleList regionProxies_ = new pbc::PopsicleList(); - public scg::IList RegionProxiesList - { - get { return pbc::Lists.AsReadOnly(regionProxies_); } - } - public int RegionProxiesCount - { - get { return regionProxies_.Count; } - } - public string GetRegionProxies(int index) - { - return regionProxies_[index]; - } - - public const int UnallocatedShardsFieldNumber = 4; - private pbc::PopsicleList unallocatedShards_ = new pbc::PopsicleList(); - public scg::IList UnallocatedShardsList - { - get { return pbc::Lists.AsReadOnly(unallocatedShards_); } - } - public int UnallocatedShardsCount - { - get { return unallocatedShards_.Count; } - } - public string GetUnallocatedShards(int index) - { - return unallocatedShards_[index]; - } - - public override bool IsInitialized - { - get - { - foreach (global::CoordinatorState.Types.ShardEntry element in ShardsList) - { - if (!element.IsInitialized) return false; - } - return true; - } - } - - public override void WriteTo(pb::ICodedOutputStream output) - { - int size = SerializedSize; - string[] field_names = _coordinatorStateFieldNames; - if (shards_.Count > 0) - { - output.WriteMessageArray(1, field_names[2], shards_); - } - if (regions_.Count > 0) - { - output.WriteStringArray(2, field_names[1], regions_); - } - if (regionProxies_.Count > 0) - { - output.WriteStringArray(3, field_names[0], regionProxies_); - } - if (unallocatedShards_.Count > 0) - { - output.WriteStringArray(4, field_names[3], unallocatedShards_); - } - UnknownFields.WriteTo(output); - } - - private int memoizedSerializedSize = -1; - public override int SerializedSize - { - get - { - int size = memoizedSerializedSize; - if (size != -1) return size; - - size = 0; - foreach (global::CoordinatorState.Types.ShardEntry element in ShardsList) - { - size += pb::CodedOutputStream.ComputeMessageSize(1, element); - } - { - int dataSize = 0; - foreach (string element in RegionsList) - { - dataSize += pb::CodedOutputStream.ComputeStringSizeNoTag(element); - } - size += dataSize; - size += 1 * regions_.Count; - } - { - int dataSize = 0; - foreach (string element in RegionProxiesList) - { - dataSize += pb::CodedOutputStream.ComputeStringSizeNoTag(element); - } - size += dataSize; - size += 1 * regionProxies_.Count; - } - { - int dataSize = 0; - foreach (string element in UnallocatedShardsList) - { - dataSize += pb::CodedOutputStream.ComputeStringSizeNoTag(element); - } - size += dataSize; - size += 1 * unallocatedShards_.Count; - } - size += UnknownFields.SerializedSize; - memoizedSerializedSize = size; - return size; - } - } - - public static CoordinatorState ParseFrom(pb::ByteString data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static CoordinatorState ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static CoordinatorState ParseFrom(byte[] data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static CoordinatorState ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static CoordinatorState ParseFrom(global::System.IO.Stream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static CoordinatorState ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - public static CoordinatorState ParseDelimitedFrom(global::System.IO.Stream input) - { - return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); - } - public static CoordinatorState ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); - } - public static CoordinatorState ParseFrom(pb::ICodedInputStream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static CoordinatorState ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - private CoordinatorState MakeReadOnly() - { - shards_.MakeReadOnly(); - regions_.MakeReadOnly(); - regionProxies_.MakeReadOnly(); - unallocatedShards_.MakeReadOnly(); - return this; - } - - public static Builder CreateBuilder() { return new Builder(); } - public override Builder ToBuilder() { return CreateBuilder(this); } - public override Builder CreateBuilderForType() { return new Builder(); } - public static Builder CreateBuilder(CoordinatorState prototype) - { - return new Builder(prototype); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class Builder : pb::GeneratedBuilder - { - protected override Builder ThisBuilder - { - get { return this; } - } - public Builder() - { - result = DefaultInstance; - resultIsReadOnly = true; - } - internal Builder(CoordinatorState cloneFrom) - { - result = cloneFrom; - resultIsReadOnly = true; - } - - private bool resultIsReadOnly; - private CoordinatorState result; - - private CoordinatorState PrepareBuilder() - { - if (resultIsReadOnly) - { - CoordinatorState original = result; - result = new CoordinatorState(); - resultIsReadOnly = false; - MergeFrom(original); - } - return result; - } - - public override bool IsInitialized - { - get { return result.IsInitialized; } - } - - protected override CoordinatorState MessageBeingBuilt - { - get { return PrepareBuilder(); } - } - - public override Builder Clear() - { - result = DefaultInstance; - resultIsReadOnly = true; - return this; - } - - public override Builder Clone() - { - if (resultIsReadOnly) - { - return new Builder(result); - } - else - { - return new Builder().MergeFrom(result); - } - } - - public override pbd::MessageDescriptor DescriptorForType - { - get { return global::CoordinatorState.Descriptor; } - } - - public override CoordinatorState DefaultInstanceForType - { - get { return global::CoordinatorState.DefaultInstance; } - } - - public override CoordinatorState BuildPartial() - { - if (resultIsReadOnly) - { - return result; - } - resultIsReadOnly = true; - return result.MakeReadOnly(); - } - - public override Builder MergeFrom(pb::IMessage other) - { - if (other is CoordinatorState) - { - return MergeFrom((CoordinatorState)other); - } - else - { - base.MergeFrom(other); - return this; - } - } - - public override Builder MergeFrom(CoordinatorState other) - { - if (other == global::CoordinatorState.DefaultInstance) return this; - PrepareBuilder(); - if (other.shards_.Count != 0) - { - result.shards_.Add(other.shards_); - } - if (other.regions_.Count != 0) - { - result.regions_.Add(other.regions_); - } - if (other.regionProxies_.Count != 0) - { - result.regionProxies_.Add(other.regionProxies_); - } - if (other.unallocatedShards_.Count != 0) - { - result.unallocatedShards_.Add(other.unallocatedShards_); - } - this.MergeUnknownFields(other.UnknownFields); - return this; - } - - public override Builder MergeFrom(pb::ICodedInputStream input) - { - return MergeFrom(input, pb::ExtensionRegistry.Empty); - } - - public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - PrepareBuilder(); - pb::UnknownFieldSet.Builder unknownFields = null; - uint tag; - string field_name; - while (input.ReadTag(out tag, out field_name)) - { - if (tag == 0 && field_name != null) - { - int field_ordinal = global::System.Array.BinarySearch(_coordinatorStateFieldNames, field_name, global::System.StringComparer.Ordinal); - if (field_ordinal >= 0) - tag = _coordinatorStateFieldTags[field_ordinal]; - else - { - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - continue; - } - } - switch (tag) - { - case 0: - { - throw pb::InvalidProtocolBufferException.InvalidTag(); - } - default: - { - if (pb::WireFormat.IsEndGroupTag(tag)) - { - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - break; - } - case 10: - { - input.ReadMessageArray(tag, field_name, result.shards_, global::CoordinatorState.Types.ShardEntry.DefaultInstance, extensionRegistry); - break; - } - case 18: - { - input.ReadStringArray(tag, field_name, result.regions_); - break; - } - case 26: - { - input.ReadStringArray(tag, field_name, result.regionProxies_); - break; - } - case 34: - { - input.ReadStringArray(tag, field_name, result.unallocatedShards_); - break; - } - } - } - - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - - - public pbc::IPopsicleList ShardsList - { - get { return PrepareBuilder().shards_; } - } - public int ShardsCount - { - get { return result.ShardsCount; } - } - public global::CoordinatorState.Types.ShardEntry GetShards(int index) - { - return result.GetShards(index); - } - public Builder SetShards(int index, global::CoordinatorState.Types.ShardEntry value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.shards_[index] = value; - return this; - } - public Builder SetShards(int index, global::CoordinatorState.Types.ShardEntry.Builder builderForValue) - { - pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); - PrepareBuilder(); - result.shards_[index] = builderForValue.Build(); - return this; - } - public Builder AddShards(global::CoordinatorState.Types.ShardEntry value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.shards_.Add(value); - return this; - } - public Builder AddShards(global::CoordinatorState.Types.ShardEntry.Builder builderForValue) - { - pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); - PrepareBuilder(); - result.shards_.Add(builderForValue.Build()); - return this; - } - public Builder AddRangeShards(scg::IEnumerable values) - { - PrepareBuilder(); - result.shards_.Add(values); - return this; - } - public Builder ClearShards() - { - PrepareBuilder(); - result.shards_.Clear(); - return this; - } - - public pbc::IPopsicleList RegionsList - { - get { return PrepareBuilder().regions_; } - } - public int RegionsCount - { - get { return result.RegionsCount; } - } - public string GetRegions(int index) - { - return result.GetRegions(index); - } - public Builder SetRegions(int index, string value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.regions_[index] = value; - return this; - } - public Builder AddRegions(string value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.regions_.Add(value); - return this; - } - public Builder AddRangeRegions(scg::IEnumerable values) - { - PrepareBuilder(); - result.regions_.Add(values); - return this; - } - public Builder ClearRegions() - { - PrepareBuilder(); - result.regions_.Clear(); - return this; - } - - public pbc::IPopsicleList RegionProxiesList - { - get { return PrepareBuilder().regionProxies_; } - } - public int RegionProxiesCount - { - get { return result.RegionProxiesCount; } - } - public string GetRegionProxies(int index) - { - return result.GetRegionProxies(index); - } - public Builder SetRegionProxies(int index, string value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.regionProxies_[index] = value; - return this; - } - public Builder AddRegionProxies(string value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.regionProxies_.Add(value); - return this; - } - public Builder AddRangeRegionProxies(scg::IEnumerable values) - { - PrepareBuilder(); - result.regionProxies_.Add(values); - return this; - } - public Builder ClearRegionProxies() - { - PrepareBuilder(); - result.regionProxies_.Clear(); - return this; - } - - public pbc::IPopsicleList UnallocatedShardsList - { - get { return PrepareBuilder().unallocatedShards_; } - } - public int UnallocatedShardsCount - { - get { return result.UnallocatedShardsCount; } - } - public string GetUnallocatedShards(int index) - { - return result.GetUnallocatedShards(index); - } - public Builder SetUnallocatedShards(int index, string value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.unallocatedShards_[index] = value; - return this; - } - public Builder AddUnallocatedShards(string value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.unallocatedShards_.Add(value); - return this; - } - public Builder AddRangeUnallocatedShards(scg::IEnumerable values) - { - PrepareBuilder(); - result.unallocatedShards_.Add(values); - return this; - } - public Builder ClearUnallocatedShards() - { - PrepareBuilder(); - result.unallocatedShards_.Clear(); - return this; - } - } - static CoordinatorState() - { - object.ReferenceEquals(global::ClusterShardingMessages.Descriptor, null); - } -} - -[global::System.Diagnostics.DebuggerNonUserCodeAttribute()] -public sealed partial class ActorRefMessage : pb::GeneratedMessage -{ - private ActorRefMessage() { } - private static readonly ActorRefMessage defaultInstance = new ActorRefMessage().MakeReadOnly(); - private static readonly string[] _actorRefMessageFieldNames = new string[] { "ref" }; - private static readonly uint[] _actorRefMessageFieldTags = new uint[] { 10 }; - public static ActorRefMessage DefaultInstance - { - get { return defaultInstance; } - } - - public override ActorRefMessage DefaultInstanceForType - { - get { return DefaultInstance; } - } - - protected override ActorRefMessage ThisMessage - { - get { return this; } - } - - public static pbd::MessageDescriptor Descriptor - { - get { return global::ClusterShardingMessages.internal__static_ActorRefMessage__Descriptor; } - } - - protected override pb::FieldAccess.FieldAccessorTable InternalFieldAccessors - { - get { return global::ClusterShardingMessages.internal__static_ActorRefMessage__FieldAccessorTable; } - } - - public const int RefFieldNumber = 1; - private bool hasRef; - private string ref_ = ""; - public bool HasRef - { - get { return hasRef; } - } - public string Ref - { - get { return ref_; } - } - - public override bool IsInitialized - { - get - { - if (!hasRef) return false; - return true; - } - } - - public override void WriteTo(pb::ICodedOutputStream output) - { - int size = SerializedSize; - string[] field_names = _actorRefMessageFieldNames; - if (hasRef) - { - output.WriteString(1, field_names[0], Ref); - } - UnknownFields.WriteTo(output); - } - - private int memoizedSerializedSize = -1; - public override int SerializedSize - { - get - { - int size = memoizedSerializedSize; - if (size != -1) return size; - - size = 0; - if (hasRef) - { - size += pb::CodedOutputStream.ComputeStringSize(1, Ref); - } - size += UnknownFields.SerializedSize; - memoizedSerializedSize = size; - return size; - } - } - - public static ActorRefMessage ParseFrom(pb::ByteString data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static ActorRefMessage ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static ActorRefMessage ParseFrom(byte[] data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static ActorRefMessage ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static ActorRefMessage ParseFrom(global::System.IO.Stream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static ActorRefMessage ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - public static ActorRefMessage ParseDelimitedFrom(global::System.IO.Stream input) - { - return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); - } - public static ActorRefMessage ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); - } - public static ActorRefMessage ParseFrom(pb::ICodedInputStream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static ActorRefMessage ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - private ActorRefMessage MakeReadOnly() - { - return this; - } - - public static Builder CreateBuilder() { return new Builder(); } - public override Builder ToBuilder() { return CreateBuilder(this); } - public override Builder CreateBuilderForType() { return new Builder(); } - public static Builder CreateBuilder(ActorRefMessage prototype) - { - return new Builder(prototype); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class Builder : pb::GeneratedBuilder - { - protected override Builder ThisBuilder - { - get { return this; } - } - public Builder() - { - result = DefaultInstance; - resultIsReadOnly = true; - } - internal Builder(ActorRefMessage cloneFrom) - { - result = cloneFrom; - resultIsReadOnly = true; - } - - private bool resultIsReadOnly; - private ActorRefMessage result; - - private ActorRefMessage PrepareBuilder() - { - if (resultIsReadOnly) - { - ActorRefMessage original = result; - result = new ActorRefMessage(); - resultIsReadOnly = false; - MergeFrom(original); - } - return result; - } - - public override bool IsInitialized - { - get { return result.IsInitialized; } - } - - protected override ActorRefMessage MessageBeingBuilt - { - get { return PrepareBuilder(); } - } - - public override Builder Clear() - { - result = DefaultInstance; - resultIsReadOnly = true; - return this; - } - - public override Builder Clone() - { - if (resultIsReadOnly) - { - return new Builder(result); - } - else - { - return new Builder().MergeFrom(result); - } - } - - public override pbd::MessageDescriptor DescriptorForType - { - get { return global::ActorRefMessage.Descriptor; } - } - - public override ActorRefMessage DefaultInstanceForType - { - get { return global::ActorRefMessage.DefaultInstance; } - } - - public override ActorRefMessage BuildPartial() - { - if (resultIsReadOnly) - { - return result; - } - resultIsReadOnly = true; - return result.MakeReadOnly(); - } - - public override Builder MergeFrom(pb::IMessage other) - { - if (other is ActorRefMessage) - { - return MergeFrom((ActorRefMessage)other); - } - else - { - base.MergeFrom(other); - return this; - } - } - - public override Builder MergeFrom(ActorRefMessage other) - { - if (other == global::ActorRefMessage.DefaultInstance) return this; - PrepareBuilder(); - if (other.HasRef) - { - Ref = other.Ref; - } - this.MergeUnknownFields(other.UnknownFields); - return this; - } - - public override Builder MergeFrom(pb::ICodedInputStream input) - { - return MergeFrom(input, pb::ExtensionRegistry.Empty); - } - - public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - PrepareBuilder(); - pb::UnknownFieldSet.Builder unknownFields = null; - uint tag; - string field_name; - while (input.ReadTag(out tag, out field_name)) - { - if (tag == 0 && field_name != null) - { - int field_ordinal = global::System.Array.BinarySearch(_actorRefMessageFieldNames, field_name, global::System.StringComparer.Ordinal); - if (field_ordinal >= 0) - tag = _actorRefMessageFieldTags[field_ordinal]; - else - { - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - continue; - } - } - switch (tag) - { - case 0: - { - throw pb::InvalidProtocolBufferException.InvalidTag(); - } - default: - { - if (pb::WireFormat.IsEndGroupTag(tag)) - { - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - break; - } - case 10: - { - result.hasRef = input.ReadString(ref result.ref_); - break; - } - } - } - - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - - - public bool HasRef - { - get { return result.hasRef; } - } - public string Ref - { - get { return result.Ref; } - set { SetRef(value); } - } - public Builder SetRef(string value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.hasRef = true; - result.ref_ = value; - return this; - } - public Builder ClearRef() - { - PrepareBuilder(); - result.hasRef = false; - result.ref_ = ""; - return this; - } - } - static ActorRefMessage() - { - object.ReferenceEquals(global::ClusterShardingMessages.Descriptor, null); - } -} - -[global::System.Diagnostics.DebuggerNonUserCodeAttribute()] -public sealed partial class ShardIdMessage : pb::GeneratedMessage -{ - private ShardIdMessage() { } - private static readonly ShardIdMessage defaultInstance = new ShardIdMessage().MakeReadOnly(); - private static readonly string[] _shardIdMessageFieldNames = new string[] { "shard" }; - private static readonly uint[] _shardIdMessageFieldTags = new uint[] { 10 }; - public static ShardIdMessage DefaultInstance - { - get { return defaultInstance; } - } - - public override ShardIdMessage DefaultInstanceForType - { - get { return DefaultInstance; } - } - - protected override ShardIdMessage ThisMessage - { - get { return this; } - } - - public static pbd::MessageDescriptor Descriptor - { - get { return global::ClusterShardingMessages.internal__static_ShardIdMessage__Descriptor; } - } - - protected override pb::FieldAccess.FieldAccessorTable InternalFieldAccessors - { - get { return global::ClusterShardingMessages.internal__static_ShardIdMessage__FieldAccessorTable; } - } - - public const int ShardFieldNumber = 1; - private bool hasShard; - private string shard_ = ""; - public bool HasShard - { - get { return hasShard; } - } - public string Shard - { - get { return shard_; } - } - - public override bool IsInitialized - { - get - { - if (!hasShard) return false; - return true; - } - } - - public override void WriteTo(pb::ICodedOutputStream output) - { - int size = SerializedSize; - string[] field_names = _shardIdMessageFieldNames; - if (hasShard) - { - output.WriteString(1, field_names[0], Shard); - } - UnknownFields.WriteTo(output); - } - - private int memoizedSerializedSize = -1; - public override int SerializedSize - { - get - { - int size = memoizedSerializedSize; - if (size != -1) return size; - - size = 0; - if (hasShard) - { - size += pb::CodedOutputStream.ComputeStringSize(1, Shard); - } - size += UnknownFields.SerializedSize; - memoizedSerializedSize = size; - return size; - } - } - - public static ShardIdMessage ParseFrom(pb::ByteString data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static ShardIdMessage ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static ShardIdMessage ParseFrom(byte[] data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static ShardIdMessage ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static ShardIdMessage ParseFrom(global::System.IO.Stream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static ShardIdMessage ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - public static ShardIdMessage ParseDelimitedFrom(global::System.IO.Stream input) - { - return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); - } - public static ShardIdMessage ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); - } - public static ShardIdMessage ParseFrom(pb::ICodedInputStream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static ShardIdMessage ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - private ShardIdMessage MakeReadOnly() - { - return this; - } - - public static Builder CreateBuilder() { return new Builder(); } - public override Builder ToBuilder() { return CreateBuilder(this); } - public override Builder CreateBuilderForType() { return new Builder(); } - public static Builder CreateBuilder(ShardIdMessage prototype) - { - return new Builder(prototype); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class Builder : pb::GeneratedBuilder - { - protected override Builder ThisBuilder - { - get { return this; } - } - public Builder() - { - result = DefaultInstance; - resultIsReadOnly = true; - } - internal Builder(ShardIdMessage cloneFrom) - { - result = cloneFrom; - resultIsReadOnly = true; - } - - private bool resultIsReadOnly; - private ShardIdMessage result; - - private ShardIdMessage PrepareBuilder() - { - if (resultIsReadOnly) - { - ShardIdMessage original = result; - result = new ShardIdMessage(); - resultIsReadOnly = false; - MergeFrom(original); - } - return result; - } - - public override bool IsInitialized - { - get { return result.IsInitialized; } - } - - protected override ShardIdMessage MessageBeingBuilt - { - get { return PrepareBuilder(); } - } - - public override Builder Clear() - { - result = DefaultInstance; - resultIsReadOnly = true; - return this; - } - - public override Builder Clone() - { - if (resultIsReadOnly) - { - return new Builder(result); - } - else - { - return new Builder().MergeFrom(result); - } - } - - public override pbd::MessageDescriptor DescriptorForType - { - get { return global::ShardIdMessage.Descriptor; } - } - - public override ShardIdMessage DefaultInstanceForType - { - get { return global::ShardIdMessage.DefaultInstance; } - } - - public override ShardIdMessage BuildPartial() - { - if (resultIsReadOnly) - { - return result; - } - resultIsReadOnly = true; - return result.MakeReadOnly(); - } - - public override Builder MergeFrom(pb::IMessage other) - { - if (other is ShardIdMessage) - { - return MergeFrom((ShardIdMessage)other); - } - else - { - base.MergeFrom(other); - return this; - } - } - - public override Builder MergeFrom(ShardIdMessage other) - { - if (other == global::ShardIdMessage.DefaultInstance) return this; - PrepareBuilder(); - if (other.HasShard) - { - Shard = other.Shard; - } - this.MergeUnknownFields(other.UnknownFields); - return this; - } - - public override Builder MergeFrom(pb::ICodedInputStream input) - { - return MergeFrom(input, pb::ExtensionRegistry.Empty); - } - - public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - PrepareBuilder(); - pb::UnknownFieldSet.Builder unknownFields = null; - uint tag; - string field_name; - while (input.ReadTag(out tag, out field_name)) - { - if (tag == 0 && field_name != null) - { - int field_ordinal = global::System.Array.BinarySearch(_shardIdMessageFieldNames, field_name, global::System.StringComparer.Ordinal); - if (field_ordinal >= 0) - tag = _shardIdMessageFieldTags[field_ordinal]; - else - { - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - continue; - } - } - switch (tag) - { - case 0: - { - throw pb::InvalidProtocolBufferException.InvalidTag(); - } - default: - { - if (pb::WireFormat.IsEndGroupTag(tag)) - { - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - break; - } - case 10: - { - result.hasShard = input.ReadString(ref result.shard_); - break; - } - } - } - - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - - - public bool HasShard - { - get { return result.hasShard; } - } - public string Shard - { - get { return result.Shard; } - set { SetShard(value); } - } - public Builder SetShard(string value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.hasShard = true; - result.shard_ = value; - return this; - } - public Builder ClearShard() - { - PrepareBuilder(); - result.hasShard = false; - result.shard_ = ""; - return this; - } - } - static ShardIdMessage() - { - object.ReferenceEquals(global::ClusterShardingMessages.Descriptor, null); - } -} - -[global::System.Diagnostics.DebuggerNonUserCodeAttribute()] -public sealed partial class ShardHomeAllocated : pb::GeneratedMessage -{ - private ShardHomeAllocated() { } - private static readonly ShardHomeAllocated defaultInstance = new ShardHomeAllocated().MakeReadOnly(); - private static readonly string[] _shardHomeAllocatedFieldNames = new string[] { "region", "shard" }; - private static readonly uint[] _shardHomeAllocatedFieldTags = new uint[] { 18, 10 }; - public static ShardHomeAllocated DefaultInstance - { - get { return defaultInstance; } - } - - public override ShardHomeAllocated DefaultInstanceForType - { - get { return DefaultInstance; } - } - - protected override ShardHomeAllocated ThisMessage - { - get { return this; } - } - - public static pbd::MessageDescriptor Descriptor - { - get { return global::ClusterShardingMessages.internal__static_ShardHomeAllocated__Descriptor; } - } - - protected override pb::FieldAccess.FieldAccessorTable InternalFieldAccessors - { - get { return global::ClusterShardingMessages.internal__static_ShardHomeAllocated__FieldAccessorTable; } - } - - public const int ShardFieldNumber = 1; - private bool hasShard; - private string shard_ = ""; - public bool HasShard - { - get { return hasShard; } - } - public string Shard - { - get { return shard_; } - } - - public const int RegionFieldNumber = 2; - private bool hasRegion; - private string region_ = ""; - public bool HasRegion - { - get { return hasRegion; } - } - public string Region - { - get { return region_; } - } - - public override bool IsInitialized - { - get - { - if (!hasShard) return false; - if (!hasRegion) return false; - return true; - } - } - - public override void WriteTo(pb::ICodedOutputStream output) - { - int size = SerializedSize; - string[] field_names = _shardHomeAllocatedFieldNames; - if (hasShard) - { - output.WriteString(1, field_names[1], Shard); - } - if (hasRegion) - { - output.WriteString(2, field_names[0], Region); - } - UnknownFields.WriteTo(output); - } - - private int memoizedSerializedSize = -1; - public override int SerializedSize - { - get - { - int size = memoizedSerializedSize; - if (size != -1) return size; - - size = 0; - if (hasShard) - { - size += pb::CodedOutputStream.ComputeStringSize(1, Shard); - } - if (hasRegion) - { - size += pb::CodedOutputStream.ComputeStringSize(2, Region); - } - size += UnknownFields.SerializedSize; - memoizedSerializedSize = size; - return size; - } - } - - public static ShardHomeAllocated ParseFrom(pb::ByteString data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static ShardHomeAllocated ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static ShardHomeAllocated ParseFrom(byte[] data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static ShardHomeAllocated ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static ShardHomeAllocated ParseFrom(global::System.IO.Stream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static ShardHomeAllocated ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - public static ShardHomeAllocated ParseDelimitedFrom(global::System.IO.Stream input) - { - return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); - } - public static ShardHomeAllocated ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); - } - public static ShardHomeAllocated ParseFrom(pb::ICodedInputStream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static ShardHomeAllocated ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - private ShardHomeAllocated MakeReadOnly() - { - return this; - } - - public static Builder CreateBuilder() { return new Builder(); } - public override Builder ToBuilder() { return CreateBuilder(this); } - public override Builder CreateBuilderForType() { return new Builder(); } - public static Builder CreateBuilder(ShardHomeAllocated prototype) - { - return new Builder(prototype); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class Builder : pb::GeneratedBuilder - { - protected override Builder ThisBuilder - { - get { return this; } - } - public Builder() - { - result = DefaultInstance; - resultIsReadOnly = true; - } - internal Builder(ShardHomeAllocated cloneFrom) - { - result = cloneFrom; - resultIsReadOnly = true; - } - - private bool resultIsReadOnly; - private ShardHomeAllocated result; - - private ShardHomeAllocated PrepareBuilder() - { - if (resultIsReadOnly) - { - ShardHomeAllocated original = result; - result = new ShardHomeAllocated(); - resultIsReadOnly = false; - MergeFrom(original); - } - return result; - } - - public override bool IsInitialized - { - get { return result.IsInitialized; } - } - - protected override ShardHomeAllocated MessageBeingBuilt - { - get { return PrepareBuilder(); } - } - - public override Builder Clear() - { - result = DefaultInstance; - resultIsReadOnly = true; - return this; - } - - public override Builder Clone() - { - if (resultIsReadOnly) - { - return new Builder(result); - } - else - { - return new Builder().MergeFrom(result); - } - } - - public override pbd::MessageDescriptor DescriptorForType - { - get { return global::ShardHomeAllocated.Descriptor; } - } - - public override ShardHomeAllocated DefaultInstanceForType - { - get { return global::ShardHomeAllocated.DefaultInstance; } - } - - public override ShardHomeAllocated BuildPartial() - { - if (resultIsReadOnly) - { - return result; - } - resultIsReadOnly = true; - return result.MakeReadOnly(); - } - - public override Builder MergeFrom(pb::IMessage other) - { - if (other is ShardHomeAllocated) - { - return MergeFrom((ShardHomeAllocated)other); - } - else - { - base.MergeFrom(other); - return this; - } - } - - public override Builder MergeFrom(ShardHomeAllocated other) - { - if (other == global::ShardHomeAllocated.DefaultInstance) return this; - PrepareBuilder(); - if (other.HasShard) - { - Shard = other.Shard; - } - if (other.HasRegion) - { - Region = other.Region; - } - this.MergeUnknownFields(other.UnknownFields); - return this; - } - - public override Builder MergeFrom(pb::ICodedInputStream input) - { - return MergeFrom(input, pb::ExtensionRegistry.Empty); - } - - public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - PrepareBuilder(); - pb::UnknownFieldSet.Builder unknownFields = null; - uint tag; - string field_name; - while (input.ReadTag(out tag, out field_name)) - { - if (tag == 0 && field_name != null) - { - int field_ordinal = global::System.Array.BinarySearch(_shardHomeAllocatedFieldNames, field_name, global::System.StringComparer.Ordinal); - if (field_ordinal >= 0) - tag = _shardHomeAllocatedFieldTags[field_ordinal]; - else - { - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - continue; - } - } - switch (tag) - { - case 0: - { - throw pb::InvalidProtocolBufferException.InvalidTag(); - } - default: - { - if (pb::WireFormat.IsEndGroupTag(tag)) - { - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - break; - } - case 10: - { - result.hasShard = input.ReadString(ref result.shard_); - break; - } - case 18: - { - result.hasRegion = input.ReadString(ref result.region_); - break; - } - } - } - - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - - - public bool HasShard - { - get { return result.hasShard; } - } - public string Shard - { - get { return result.Shard; } - set { SetShard(value); } - } - public Builder SetShard(string value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.hasShard = true; - result.shard_ = value; - return this; - } - public Builder ClearShard() - { - PrepareBuilder(); - result.hasShard = false; - result.shard_ = ""; - return this; - } - - public bool HasRegion - { - get { return result.hasRegion; } - } - public string Region - { - get { return result.Region; } - set { SetRegion(value); } - } - public Builder SetRegion(string value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.hasRegion = true; - result.region_ = value; - return this; - } - public Builder ClearRegion() - { - PrepareBuilder(); - result.hasRegion = false; - result.region_ = ""; - return this; - } - } - static ShardHomeAllocated() - { - object.ReferenceEquals(global::ClusterShardingMessages.Descriptor, null); - } -} - -[global::System.Diagnostics.DebuggerNonUserCodeAttribute()] -public sealed partial class ShardHome : pb::GeneratedMessage -{ - private ShardHome() { } - private static readonly ShardHome defaultInstance = new ShardHome().MakeReadOnly(); - private static readonly string[] _shardHomeFieldNames = new string[] { "region", "shard" }; - private static readonly uint[] _shardHomeFieldTags = new uint[] { 18, 10 }; - public static ShardHome DefaultInstance - { - get { return defaultInstance; } - } - - public override ShardHome DefaultInstanceForType - { - get { return DefaultInstance; } - } - - protected override ShardHome ThisMessage - { - get { return this; } - } - - public static pbd::MessageDescriptor Descriptor - { - get { return global::ClusterShardingMessages.internal__static_ShardHome__Descriptor; } - } - - protected override pb::FieldAccess.FieldAccessorTable InternalFieldAccessors - { - get { return global::ClusterShardingMessages.internal__static_ShardHome__FieldAccessorTable; } - } - - public const int ShardFieldNumber = 1; - private bool hasShard; - private string shard_ = ""; - public bool HasShard - { - get { return hasShard; } - } - public string Shard - { - get { return shard_; } - } - - public const int RegionFieldNumber = 2; - private bool hasRegion; - private string region_ = ""; - public bool HasRegion - { - get { return hasRegion; } - } - public string Region - { - get { return region_; } - } - - public override bool IsInitialized - { - get - { - if (!hasShard) return false; - if (!hasRegion) return false; - return true; - } - } - - public override void WriteTo(pb::ICodedOutputStream output) - { - int size = SerializedSize; - string[] field_names = _shardHomeFieldNames; - if (hasShard) - { - output.WriteString(1, field_names[1], Shard); - } - if (hasRegion) - { - output.WriteString(2, field_names[0], Region); - } - UnknownFields.WriteTo(output); - } - - private int memoizedSerializedSize = -1; - public override int SerializedSize - { - get - { - int size = memoizedSerializedSize; - if (size != -1) return size; - - size = 0; - if (hasShard) - { - size += pb::CodedOutputStream.ComputeStringSize(1, Shard); - } - if (hasRegion) - { - size += pb::CodedOutputStream.ComputeStringSize(2, Region); - } - size += UnknownFields.SerializedSize; - memoizedSerializedSize = size; - return size; - } - } - - public static ShardHome ParseFrom(pb::ByteString data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static ShardHome ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static ShardHome ParseFrom(byte[] data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static ShardHome ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static ShardHome ParseFrom(global::System.IO.Stream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static ShardHome ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - public static ShardHome ParseDelimitedFrom(global::System.IO.Stream input) - { - return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); - } - public static ShardHome ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); - } - public static ShardHome ParseFrom(pb::ICodedInputStream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static ShardHome ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - private ShardHome MakeReadOnly() - { - return this; - } - - public static Builder CreateBuilder() { return new Builder(); } - public override Builder ToBuilder() { return CreateBuilder(this); } - public override Builder CreateBuilderForType() { return new Builder(); } - public static Builder CreateBuilder(ShardHome prototype) - { - return new Builder(prototype); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class Builder : pb::GeneratedBuilder - { - protected override Builder ThisBuilder - { - get { return this; } - } - public Builder() - { - result = DefaultInstance; - resultIsReadOnly = true; - } - internal Builder(ShardHome cloneFrom) - { - result = cloneFrom; - resultIsReadOnly = true; - } - - private bool resultIsReadOnly; - private ShardHome result; - - private ShardHome PrepareBuilder() - { - if (resultIsReadOnly) - { - ShardHome original = result; - result = new ShardHome(); - resultIsReadOnly = false; - MergeFrom(original); - } - return result; - } - - public override bool IsInitialized - { - get { return result.IsInitialized; } - } - - protected override ShardHome MessageBeingBuilt - { - get { return PrepareBuilder(); } - } - - public override Builder Clear() - { - result = DefaultInstance; - resultIsReadOnly = true; - return this; - } - - public override Builder Clone() - { - if (resultIsReadOnly) - { - return new Builder(result); - } - else - { - return new Builder().MergeFrom(result); - } - } - - public override pbd::MessageDescriptor DescriptorForType - { - get { return global::ShardHome.Descriptor; } - } - - public override ShardHome DefaultInstanceForType - { - get { return global::ShardHome.DefaultInstance; } - } - - public override ShardHome BuildPartial() - { - if (resultIsReadOnly) - { - return result; - } - resultIsReadOnly = true; - return result.MakeReadOnly(); - } - - public override Builder MergeFrom(pb::IMessage other) - { - if (other is ShardHome) - { - return MergeFrom((ShardHome)other); - } - else - { - base.MergeFrom(other); - return this; - } - } - - public override Builder MergeFrom(ShardHome other) - { - if (other == global::ShardHome.DefaultInstance) return this; - PrepareBuilder(); - if (other.HasShard) - { - Shard = other.Shard; - } - if (other.HasRegion) - { - Region = other.Region; - } - this.MergeUnknownFields(other.UnknownFields); - return this; - } - - public override Builder MergeFrom(pb::ICodedInputStream input) - { - return MergeFrom(input, pb::ExtensionRegistry.Empty); - } - - public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - PrepareBuilder(); - pb::UnknownFieldSet.Builder unknownFields = null; - uint tag; - string field_name; - while (input.ReadTag(out tag, out field_name)) - { - if (tag == 0 && field_name != null) - { - int field_ordinal = global::System.Array.BinarySearch(_shardHomeFieldNames, field_name, global::System.StringComparer.Ordinal); - if (field_ordinal >= 0) - tag = _shardHomeFieldTags[field_ordinal]; - else - { - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - continue; - } - } - switch (tag) - { - case 0: - { - throw pb::InvalidProtocolBufferException.InvalidTag(); - } - default: - { - if (pb::WireFormat.IsEndGroupTag(tag)) - { - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - break; - } - case 10: - { - result.hasShard = input.ReadString(ref result.shard_); - break; - } - case 18: - { - result.hasRegion = input.ReadString(ref result.region_); - break; - } - } - } - - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - - - public bool HasShard - { - get { return result.hasShard; } - } - public string Shard - { - get { return result.Shard; } - set { SetShard(value); } - } - public Builder SetShard(string value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.hasShard = true; - result.shard_ = value; - return this; - } - public Builder ClearShard() - { - PrepareBuilder(); - result.hasShard = false; - result.shard_ = ""; - return this; - } - - public bool HasRegion - { - get { return result.hasRegion; } - } - public string Region - { - get { return result.Region; } - set { SetRegion(value); } - } - public Builder SetRegion(string value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.hasRegion = true; - result.region_ = value; - return this; - } - public Builder ClearRegion() - { - PrepareBuilder(); - result.hasRegion = false; - result.region_ = ""; - return this; - } - } - static ShardHome() - { - object.ReferenceEquals(global::ClusterShardingMessages.Descriptor, null); - } -} - -[global::System.Diagnostics.DebuggerNonUserCodeAttribute()] -public sealed partial class EntityState : pb::GeneratedMessage -{ - private EntityState() { } - private static readonly EntityState defaultInstance = new EntityState().MakeReadOnly(); - private static readonly string[] _entityStateFieldNames = new string[] { "entities" }; - private static readonly uint[] _entityStateFieldTags = new uint[] { 10 }; - public static EntityState DefaultInstance - { - get { return defaultInstance; } - } - - public override EntityState DefaultInstanceForType - { - get { return DefaultInstance; } - } - - protected override EntityState ThisMessage - { - get { return this; } - } - - public static pbd::MessageDescriptor Descriptor - { - get { return global::ClusterShardingMessages.internal__static_EntityState__Descriptor; } - } - - protected override pb::FieldAccess.FieldAccessorTable InternalFieldAccessors - { - get { return global::ClusterShardingMessages.internal__static_EntityState__FieldAccessorTable; } - } - - public const int EntitiesFieldNumber = 1; - private pbc::PopsicleList entities_ = new pbc::PopsicleList(); - public scg::IList EntitiesList - { - get { return pbc::Lists.AsReadOnly(entities_); } - } - public int EntitiesCount - { - get { return entities_.Count; } - } - public string GetEntities(int index) - { - return entities_[index]; - } - - public override bool IsInitialized - { - get - { - return true; - } - } - - public override void WriteTo(pb::ICodedOutputStream output) - { - int size = SerializedSize; - string[] field_names = _entityStateFieldNames; - if (entities_.Count > 0) - { - output.WriteStringArray(1, field_names[0], entities_); - } - UnknownFields.WriteTo(output); - } - - private int memoizedSerializedSize = -1; - public override int SerializedSize - { - get - { - int size = memoizedSerializedSize; - if (size != -1) return size; - - size = 0; - { - int dataSize = 0; - foreach (string element in EntitiesList) - { - dataSize += pb::CodedOutputStream.ComputeStringSizeNoTag(element); - } - size += dataSize; - size += 1 * entities_.Count; - } - size += UnknownFields.SerializedSize; - memoizedSerializedSize = size; - return size; - } - } - - public static EntityState ParseFrom(pb::ByteString data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static EntityState ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static EntityState ParseFrom(byte[] data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static EntityState ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static EntityState ParseFrom(global::System.IO.Stream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static EntityState ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - public static EntityState ParseDelimitedFrom(global::System.IO.Stream input) - { - return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); - } - public static EntityState ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); - } - public static EntityState ParseFrom(pb::ICodedInputStream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static EntityState ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - private EntityState MakeReadOnly() - { - entities_.MakeReadOnly(); - return this; - } - - public static Builder CreateBuilder() { return new Builder(); } - public override Builder ToBuilder() { return CreateBuilder(this); } - public override Builder CreateBuilderForType() { return new Builder(); } - public static Builder CreateBuilder(EntityState prototype) - { - return new Builder(prototype); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class Builder : pb::GeneratedBuilder - { - protected override Builder ThisBuilder - { - get { return this; } - } - public Builder() - { - result = DefaultInstance; - resultIsReadOnly = true; - } - internal Builder(EntityState cloneFrom) - { - result = cloneFrom; - resultIsReadOnly = true; - } - - private bool resultIsReadOnly; - private EntityState result; - - private EntityState PrepareBuilder() - { - if (resultIsReadOnly) - { - EntityState original = result; - result = new EntityState(); - resultIsReadOnly = false; - MergeFrom(original); - } - return result; - } - - public override bool IsInitialized - { - get { return result.IsInitialized; } - } - - protected override EntityState MessageBeingBuilt - { - get { return PrepareBuilder(); } - } - - public override Builder Clear() - { - result = DefaultInstance; - resultIsReadOnly = true; - return this; - } - - public override Builder Clone() - { - if (resultIsReadOnly) - { - return new Builder(result); - } - else - { - return new Builder().MergeFrom(result); - } - } - - public override pbd::MessageDescriptor DescriptorForType - { - get { return global::EntityState.Descriptor; } - } - - public override EntityState DefaultInstanceForType - { - get { return global::EntityState.DefaultInstance; } - } - - public override EntityState BuildPartial() - { - if (resultIsReadOnly) - { - return result; - } - resultIsReadOnly = true; - return result.MakeReadOnly(); - } - - public override Builder MergeFrom(pb::IMessage other) - { - if (other is EntityState) - { - return MergeFrom((EntityState)other); - } - else - { - base.MergeFrom(other); - return this; - } - } - - public override Builder MergeFrom(EntityState other) - { - if (other == global::EntityState.DefaultInstance) return this; - PrepareBuilder(); - if (other.entities_.Count != 0) - { - result.entities_.Add(other.entities_); - } - this.MergeUnknownFields(other.UnknownFields); - return this; - } - - public override Builder MergeFrom(pb::ICodedInputStream input) - { - return MergeFrom(input, pb::ExtensionRegistry.Empty); - } - - public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - PrepareBuilder(); - pb::UnknownFieldSet.Builder unknownFields = null; - uint tag; - string field_name; - while (input.ReadTag(out tag, out field_name)) - { - if (tag == 0 && field_name != null) - { - int field_ordinal = global::System.Array.BinarySearch(_entityStateFieldNames, field_name, global::System.StringComparer.Ordinal); - if (field_ordinal >= 0) - tag = _entityStateFieldTags[field_ordinal]; - else - { - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - continue; - } - } - switch (tag) - { - case 0: - { - throw pb::InvalidProtocolBufferException.InvalidTag(); - } - default: - { - if (pb::WireFormat.IsEndGroupTag(tag)) - { - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - break; - } - case 10: - { - input.ReadStringArray(tag, field_name, result.entities_); - break; - } - } - } - - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - - - public pbc::IPopsicleList EntitiesList - { - get { return PrepareBuilder().entities_; } - } - public int EntitiesCount - { - get { return result.EntitiesCount; } - } - public string GetEntities(int index) - { - return result.GetEntities(index); - } - public Builder SetEntities(int index, string value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.entities_[index] = value; - return this; - } - public Builder AddEntities(string value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.entities_.Add(value); - return this; - } - public Builder AddRangeEntities(scg::IEnumerable values) - { - PrepareBuilder(); - result.entities_.Add(values); - return this; - } - public Builder ClearEntities() - { - PrepareBuilder(); - result.entities_.Clear(); - return this; - } - } - static EntityState() - { - object.ReferenceEquals(global::ClusterShardingMessages.Descriptor, null); - } -} - -[global::System.Diagnostics.DebuggerNonUserCodeAttribute()] -public sealed partial class EntityStarted : pb::GeneratedMessage -{ - private EntityStarted() { } - private static readonly EntityStarted defaultInstance = new EntityStarted().MakeReadOnly(); - private static readonly string[] _entityStartedFieldNames = new string[] { "entityId" }; - private static readonly uint[] _entityStartedFieldTags = new uint[] { 10 }; - public static EntityStarted DefaultInstance - { - get { return defaultInstance; } - } - - public override EntityStarted DefaultInstanceForType - { - get { return DefaultInstance; } - } - - protected override EntityStarted ThisMessage - { - get { return this; } - } - - public static pbd::MessageDescriptor Descriptor - { - get { return global::ClusterShardingMessages.internal__static_EntityStarted__Descriptor; } - } - - protected override pb::FieldAccess.FieldAccessorTable InternalFieldAccessors - { - get { return global::ClusterShardingMessages.internal__static_EntityStarted__FieldAccessorTable; } - } - - public const int EntityIdFieldNumber = 1; - private bool hasEntityId; - private string entityId_ = ""; - public bool HasEntityId - { - get { return hasEntityId; } - } - public string EntityId - { - get { return entityId_; } - } - - public override bool IsInitialized - { - get - { - if (!hasEntityId) return false; - return true; - } - } - - public override void WriteTo(pb::ICodedOutputStream output) - { - int size = SerializedSize; - string[] field_names = _entityStartedFieldNames; - if (hasEntityId) - { - output.WriteString(1, field_names[0], EntityId); - } - UnknownFields.WriteTo(output); - } - - private int memoizedSerializedSize = -1; - public override int SerializedSize - { - get - { - int size = memoizedSerializedSize; - if (size != -1) return size; - - size = 0; - if (hasEntityId) - { - size += pb::CodedOutputStream.ComputeStringSize(1, EntityId); - } - size += UnknownFields.SerializedSize; - memoizedSerializedSize = size; - return size; - } - } - - public static EntityStarted ParseFrom(pb::ByteString data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static EntityStarted ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static EntityStarted ParseFrom(byte[] data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static EntityStarted ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static EntityStarted ParseFrom(global::System.IO.Stream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static EntityStarted ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - public static EntityStarted ParseDelimitedFrom(global::System.IO.Stream input) - { - return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); - } - public static EntityStarted ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); - } - public static EntityStarted ParseFrom(pb::ICodedInputStream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static EntityStarted ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - private EntityStarted MakeReadOnly() - { - return this; - } - - public static Builder CreateBuilder() { return new Builder(); } - public override Builder ToBuilder() { return CreateBuilder(this); } - public override Builder CreateBuilderForType() { return new Builder(); } - public static Builder CreateBuilder(EntityStarted prototype) - { - return new Builder(prototype); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class Builder : pb::GeneratedBuilder - { - protected override Builder ThisBuilder - { - get { return this; } - } - public Builder() - { - result = DefaultInstance; - resultIsReadOnly = true; - } - internal Builder(EntityStarted cloneFrom) - { - result = cloneFrom; - resultIsReadOnly = true; - } - - private bool resultIsReadOnly; - private EntityStarted result; - - private EntityStarted PrepareBuilder() - { - if (resultIsReadOnly) - { - EntityStarted original = result; - result = new EntityStarted(); - resultIsReadOnly = false; - MergeFrom(original); - } - return result; - } - - public override bool IsInitialized - { - get { return result.IsInitialized; } - } - - protected override EntityStarted MessageBeingBuilt - { - get { return PrepareBuilder(); } - } - - public override Builder Clear() - { - result = DefaultInstance; - resultIsReadOnly = true; - return this; - } - - public override Builder Clone() - { - if (resultIsReadOnly) - { - return new Builder(result); - } - else - { - return new Builder().MergeFrom(result); - } - } - - public override pbd::MessageDescriptor DescriptorForType - { - get { return global::EntityStarted.Descriptor; } - } - - public override EntityStarted DefaultInstanceForType - { - get { return global::EntityStarted.DefaultInstance; } - } - - public override EntityStarted BuildPartial() - { - if (resultIsReadOnly) - { - return result; - } - resultIsReadOnly = true; - return result.MakeReadOnly(); - } - - public override Builder MergeFrom(pb::IMessage other) - { - if (other is EntityStarted) - { - return MergeFrom((EntityStarted)other); - } - else - { - base.MergeFrom(other); - return this; - } - } - - public override Builder MergeFrom(EntityStarted other) - { - if (other == global::EntityStarted.DefaultInstance) return this; - PrepareBuilder(); - if (other.HasEntityId) - { - EntityId = other.EntityId; - } - this.MergeUnknownFields(other.UnknownFields); - return this; - } - - public override Builder MergeFrom(pb::ICodedInputStream input) - { - return MergeFrom(input, pb::ExtensionRegistry.Empty); - } - - public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - PrepareBuilder(); - pb::UnknownFieldSet.Builder unknownFields = null; - uint tag; - string field_name; - while (input.ReadTag(out tag, out field_name)) - { - if (tag == 0 && field_name != null) - { - int field_ordinal = global::System.Array.BinarySearch(_entityStartedFieldNames, field_name, global::System.StringComparer.Ordinal); - if (field_ordinal >= 0) - tag = _entityStartedFieldTags[field_ordinal]; - else - { - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - continue; - } - } - switch (tag) - { - case 0: - { - throw pb::InvalidProtocolBufferException.InvalidTag(); - } - default: - { - if (pb::WireFormat.IsEndGroupTag(tag)) - { - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - break; - } - case 10: - { - result.hasEntityId = input.ReadString(ref result.entityId_); - break; - } - } - } - - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - - - public bool HasEntityId - { - get { return result.hasEntityId; } - } - public string EntityId - { - get { return result.EntityId; } - set { SetEntityId(value); } - } - public Builder SetEntityId(string value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.hasEntityId = true; - result.entityId_ = value; - return this; - } - public Builder ClearEntityId() - { - PrepareBuilder(); - result.hasEntityId = false; - result.entityId_ = ""; - return this; - } - } - static EntityStarted() - { - object.ReferenceEquals(global::ClusterShardingMessages.Descriptor, null); - } -} - -[global::System.Diagnostics.DebuggerNonUserCodeAttribute()] -public sealed partial class EntityStopped : pb::GeneratedMessage -{ - private EntityStopped() { } - private static readonly EntityStopped defaultInstance = new EntityStopped().MakeReadOnly(); - private static readonly string[] _entityStoppedFieldNames = new string[] { "entityId" }; - private static readonly uint[] _entityStoppedFieldTags = new uint[] { 10 }; - public static EntityStopped DefaultInstance - { - get { return defaultInstance; } - } - - public override EntityStopped DefaultInstanceForType - { - get { return DefaultInstance; } - } - - protected override EntityStopped ThisMessage - { - get { return this; } - } - - public static pbd::MessageDescriptor Descriptor - { - get { return global::ClusterShardingMessages.internal__static_EntityStopped__Descriptor; } - } - - protected override pb::FieldAccess.FieldAccessorTable InternalFieldAccessors - { - get { return global::ClusterShardingMessages.internal__static_EntityStopped__FieldAccessorTable; } - } - - public const int EntityIdFieldNumber = 1; - private bool hasEntityId; - private string entityId_ = ""; - public bool HasEntityId - { - get { return hasEntityId; } - } - public string EntityId - { - get { return entityId_; } - } - - public override bool IsInitialized - { - get - { - if (!hasEntityId) return false; - return true; - } - } - - public override void WriteTo(pb::ICodedOutputStream output) - { - int size = SerializedSize; - string[] field_names = _entityStoppedFieldNames; - if (hasEntityId) - { - output.WriteString(1, field_names[0], EntityId); - } - UnknownFields.WriteTo(output); - } - - private int memoizedSerializedSize = -1; - public override int SerializedSize - { - get - { - int size = memoizedSerializedSize; - if (size != -1) return size; - - size = 0; - if (hasEntityId) - { - size += pb::CodedOutputStream.ComputeStringSize(1, EntityId); - } - size += UnknownFields.SerializedSize; - memoizedSerializedSize = size; - return size; - } - } - - public static EntityStopped ParseFrom(pb::ByteString data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static EntityStopped ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static EntityStopped ParseFrom(byte[] data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static EntityStopped ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static EntityStopped ParseFrom(global::System.IO.Stream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static EntityStopped ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - public static EntityStopped ParseDelimitedFrom(global::System.IO.Stream input) - { - return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); - } - public static EntityStopped ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); - } - public static EntityStopped ParseFrom(pb::ICodedInputStream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static EntityStopped ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - private EntityStopped MakeReadOnly() - { - return this; - } - - public static Builder CreateBuilder() { return new Builder(); } - public override Builder ToBuilder() { return CreateBuilder(this); } - public override Builder CreateBuilderForType() { return new Builder(); } - public static Builder CreateBuilder(EntityStopped prototype) - { - return new Builder(prototype); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class Builder : pb::GeneratedBuilder - { - protected override Builder ThisBuilder - { - get { return this; } - } - public Builder() - { - result = DefaultInstance; - resultIsReadOnly = true; - } - internal Builder(EntityStopped cloneFrom) - { - result = cloneFrom; - resultIsReadOnly = true; - } - - private bool resultIsReadOnly; - private EntityStopped result; - - private EntityStopped PrepareBuilder() - { - if (resultIsReadOnly) - { - EntityStopped original = result; - result = new EntityStopped(); - resultIsReadOnly = false; - MergeFrom(original); - } - return result; - } - - public override bool IsInitialized - { - get { return result.IsInitialized; } - } - - protected override EntityStopped MessageBeingBuilt - { - get { return PrepareBuilder(); } - } - - public override Builder Clear() - { - result = DefaultInstance; - resultIsReadOnly = true; - return this; - } - - public override Builder Clone() - { - if (resultIsReadOnly) - { - return new Builder(result); - } - else - { - return new Builder().MergeFrom(result); - } - } - - public override pbd::MessageDescriptor DescriptorForType - { - get { return global::EntityStopped.Descriptor; } - } - - public override EntityStopped DefaultInstanceForType - { - get { return global::EntityStopped.DefaultInstance; } - } - - public override EntityStopped BuildPartial() - { - if (resultIsReadOnly) - { - return result; - } - resultIsReadOnly = true; - return result.MakeReadOnly(); - } - - public override Builder MergeFrom(pb::IMessage other) - { - if (other is EntityStopped) - { - return MergeFrom((EntityStopped)other); - } - else - { - base.MergeFrom(other); - return this; - } - } - - public override Builder MergeFrom(EntityStopped other) - { - if (other == global::EntityStopped.DefaultInstance) return this; - PrepareBuilder(); - if (other.HasEntityId) - { - EntityId = other.EntityId; - } - this.MergeUnknownFields(other.UnknownFields); - return this; - } - - public override Builder MergeFrom(pb::ICodedInputStream input) - { - return MergeFrom(input, pb::ExtensionRegistry.Empty); - } - - public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - PrepareBuilder(); - pb::UnknownFieldSet.Builder unknownFields = null; - uint tag; - string field_name; - while (input.ReadTag(out tag, out field_name)) - { - if (tag == 0 && field_name != null) - { - int field_ordinal = global::System.Array.BinarySearch(_entityStoppedFieldNames, field_name, global::System.StringComparer.Ordinal); - if (field_ordinal >= 0) - tag = _entityStoppedFieldTags[field_ordinal]; - else - { - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - continue; - } - } - switch (tag) - { - case 0: - { - throw pb::InvalidProtocolBufferException.InvalidTag(); - } - default: - { - if (pb::WireFormat.IsEndGroupTag(tag)) - { - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - break; - } - case 10: - { - result.hasEntityId = input.ReadString(ref result.entityId_); - break; - } - } - } - - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - - - public bool HasEntityId - { - get { return result.hasEntityId; } - } - public string EntityId - { - get { return result.EntityId; } - set { SetEntityId(value); } - } - public Builder SetEntityId(string value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.hasEntityId = true; - result.entityId_ = value; - return this; - } - public Builder ClearEntityId() - { - PrepareBuilder(); - result.hasEntityId = false; - result.entityId_ = ""; - return this; - } - } - static EntityStopped() - { - object.ReferenceEquals(global::ClusterShardingMessages.Descriptor, null); - } -} - -#endregion - - -#endregion Designer generated code diff --git a/src/contrib/cluster/Akka.Cluster.Sharding/Shard.cs b/src/contrib/cluster/Akka.Cluster.Sharding/Shard.cs deleted file mode 100644 index de9bd4746d8..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Sharding/Shard.cs +++ /dev/null @@ -1,441 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using System.Collections.Immutable; -using System.Linq; -using Akka.Actor; -using Akka.Event; -using Akka.Persistence; - -namespace Akka.Cluster.Sharding -{ - using ShardId = String; - using EntityId = String; - using Msg = Object; - - //TODO: figure out how not to derive from persistent actor for the sake of alternative ddata based impl - public abstract class Shard : PersistentActor - { - #region messages - - public interface IShardCommand { } - public interface IShardQuery { } - - /// - /// When a fails to write to the journal, we will retry it after a back off. - /// - [Serializable] - public class RetryPersistence : IShardCommand - { - public readonly StateChange Payload; - - public RetryPersistence(StateChange payload) - { - Payload = payload; - } - } - - /// - /// The Snapshot tick for the shards. - /// - [Serializable] - public sealed class SnapshotTick : IShardCommand - { - public static readonly SnapshotTick Instance = new SnapshotTick(); - - private SnapshotTick() - { - } - } - - /// - /// When an remembering entries and the entity stops without issuing a , - /// we restart it after a back off using this message. - /// - [Serializable] - public sealed class RestartEntity : IShardCommand - { - public readonly EntityId EntityId; - - public RestartEntity(string entityId) - { - EntityId = entityId; - } - } - - public abstract class StateChange - { - public readonly EntityId EntityId; - - protected StateChange(EntityId entityId) - { - EntityId = entityId; - } - } - - /// - /// change for starting an entity in this `Shard` - /// - [Serializable] - public sealed class EntityStarted : StateChange - { - public EntityStarted(string entityId) : base(entityId) - { - } - } - - /// - /// change for an entity which has terminated. - /// - [Serializable] - public sealed class EntityStopped : StateChange - { - public EntityStopped(string entityId) : base(entityId) - { - } - } - - [Serializable] - public sealed class GetCurrentShardState : IShardQuery - { - public static readonly GetCurrentShardState Instance = new GetCurrentShardState(); - - private GetCurrentShardState() - { - } - } - - [Serializable] - public sealed class CurrentShardState - { - public readonly string ShardId; - public readonly string[] EntityIds; - - public CurrentShardState(string shardId, string[] entityIds) - { - ShardId = shardId; - EntityIds = entityIds; - } - } - - [Serializable] - public sealed class GetShardStats : IShardQuery - { - public static readonly GetShardStats Instance = new GetShardStats(); - - private GetShardStats() - { - } - } - - [Serializable] - public sealed class ShardStats - { - public readonly string ShardId; - public readonly int EntityCount; - - public ShardStats(string shardId, int entityCount) - { - ShardId = shardId; - EntityCount = entityCount; - } - } - - #endregion - - /// - /// Persistent state of the Shard. - /// - [Serializable] - public struct ShardState : IClusterShardingSerializable - { - public static readonly ShardState Empty = new ShardState(ImmutableHashSet.Empty); - public readonly IImmutableSet Entries; - - public ShardState(IImmutableSet entries) : this() - { - Entries = entries; - } - } - - public readonly string TypeName; - public readonly ShardId ShardId; - public readonly Actor.Props EntityProps; - public readonly ClusterShardingSettings Settings; - public readonly IdExtractor ExtractEntityId; - public readonly ShardResolver ExtractShardId; - public readonly object HandOffStopMessage; - - protected IImmutableDictionary IdByRef = ImmutableDictionary.Empty; - protected IImmutableDictionary RefById = ImmutableDictionary.Empty; - protected IImmutableSet Passivating = ImmutableHashSet.Empty; - - protected IImmutableDictionary>> MessageBuffers = - ImmutableDictionary>>.Empty; - - protected IActorRef HandOffStopper = null; - - protected ShardState State = ShardState.Empty; - - private ILoggingAdapter _log; - - protected Shard( - string typeName, - string shardId, - Props entityProps, - ClusterShardingSettings settings, - IdExtractor extractEntityId, - ShardResolver extractShardId, - object handOffStopMessage) - { - TypeName = typeName; - ShardId = shardId; - EntityProps = entityProps; - Settings = settings; - ExtractEntityId = extractEntityId; - ExtractShardId = extractShardId; - HandOffStopMessage = handOffStopMessage; - } - - protected ILoggingAdapter Log - { - get { return _log ?? (_log = Context.GetLogger()); } - } - - protected int TotalBufferSize - { - get { return MessageBuffers.Aggregate(0, (sum, entity) => sum + entity.Value.Count); } - } - - #region common shard methods - - protected virtual void Initialized() - { - Context.Parent.Tell(new ShardRegion.ShardInitialized(ShardId)); - } - - protected virtual void ProcessChange(T evt, Action handler) - { - handler(evt); - } - - protected bool HandleCommand(object message) - { - if (message is Terminated) HandleTerminated(((Terminated) message).ActorRef); - else if (message is PersistentShardCoordinator.ICoordinatorMessage) HandleCoordinatorMessage(message as PersistentShardCoordinator.ICoordinatorMessage); - else if (message is IShardCommand) HandleShardCommand(message as IShardCommand); - else if (message is ShardRegion.IShardRegionCommand) HandleShardRegionCommand(message as ShardRegion.IShardRegionCommand); - else if (message is IShardQuery) HandleShardRegionQuery(message as IShardQuery); - else if (ExtractEntityId(message) != null) DeliverMessage(message, Sender); - else return false; - return true; - } - - private void HandleShardRegionQuery(IShardQuery query) - { - if(query is GetCurrentShardState) Sender.Tell(new CurrentShardState(ShardId, RefById.Keys.ToArray())); - else if (query is GetShardStats) Sender.Tell(new ShardStats(ShardId, State.Entries.Count)); - } - - protected virtual void EntityTerminated(IActorRef tref) - { - ShardId id; - IImmutableList> buffer; - if (IdByRef.TryGetValue(tref, out id) && MessageBuffers.TryGetValue(id, out buffer) && buffer.Count != 0) - { - Log.Debug("Starting entity [{0}] again, there are buffered messages for it", id); - SendMessageBuffer(new EntityStarted(id)); - } - else - { - ProcessChange(new EntityStopped(id), PassivateCompleted); - } - - Passivating = Passivating.Remove(tref); - } - - protected void HandleShardCommand(IShardCommand message) - { - var restart = message as RestartEntity; - if (restart != null) - GetEntity(restart.EntityId); - } - - protected void HandleShardRegionCommand(ShardRegion.IShardRegionCommand message) - { - var passivate = message as ShardRegion.Passivate; - if (passivate != null) - Passivate(Sender, passivate.StopMessage); - else - Unhandled(message); - } - - protected void HandleCoordinatorMessage(PersistentShardCoordinator.ICoordinatorMessage message) - { - var handOff = message as PersistentShardCoordinator.HandOff; - if (handOff != null) - { - if (handOff.Shard == ShardId) HandOff(Sender); - else Log.Warning("Shard [{0}] can not hand off for another Shard [{1}]", ShardId, handOff.Shard); - } - else Unhandled(message); - } - - protected void HandOff(IActorRef replyTo) - { - if (HandOffStopper != null) Log.Warning("HandOff shard [{0}] received during existing handOff", ShardId); - else - { - Log.Debug("HandOff shard [{0}]", ShardId); - - if (State.Entries.Count != 0) - { - // handOffStopper = Some(context.watch(context.actorOf( - // handOffStopperProps(shardId, replyTo, idByRef.keySet, handOffStopMessage)))) - HandOffStopper = Context.Watch(Context.ActorOf( - ShardRegion.HandOffStopper.Props(ShardId, replyTo, IdByRef.Keys, HandOffStopMessage))); - - //During hand off we only care about watching for termination of the hand off stopper - Context.Become(message => - { - var terminated = message as Terminated; - if (terminated != null) - { - HandleTerminated(terminated.ActorRef); - return true; - } - return false; - }); - } - else - { - replyTo.Tell(new PersistentShardCoordinator.ShardStopped(ShardId)); - Context.Stop(Self); - } - } - } - - protected void HandleTerminated(IActorRef terminatedRef) - { - if (Equals(HandOffStopper, terminatedRef)) - Context.Stop(Self); - else if (IdByRef.ContainsKey(terminatedRef) && HandOffStopper == null) - EntityTerminated(terminatedRef); - } - - protected void Passivate(IActorRef entity, object stopMessage) - { - ShardId id; - if (IdByRef.TryGetValue(entity, out id) && !MessageBuffers.ContainsKey(id)) - { - Log.Debug("Passivating started on entity {0}", id); - - Passivating = Passivating.Add(entity); - MessageBuffers = MessageBuffers.Add(id, ImmutableList>.Empty); - - entity.Tell(stopMessage); - } - } - - protected void PassivateCompleted(EntityStopped evt) - { - var id = evt.EntityId; - Log.Debug("Entity stopped [{0}]", id); - - var entity = RefById[id]; - IdByRef = IdByRef.Remove(entity); - RefById = RefById.Remove(id); - - State = new ShardState(State.Entries.Remove(id)); - MessageBuffers = MessageBuffers.Remove(id); - } - - protected void SendMessageBuffer(EntityStarted message) - { - var id = message.EntityId; - - // Get the buffered messages and remove the buffer - IImmutableList> buffer; - if (MessageBuffers.TryGetValue(id, out buffer)) MessageBuffers = MessageBuffers.Remove(id); - - if (buffer.Count != 0) - { - Log.Debug("Sending message buffer for entity [{0}] ([{1}] messages)", id, buffer.Count); - - GetEntity(id); - - // Now there is no deliveryBuffer we can try to redeliver - // and as the child exists, the message will be directly forwarded - foreach (var pair in buffer) - DeliverMessage(pair.Item1, pair.Item2); - } - } - - protected void DeliverMessage(object message, IActorRef sender) - { - var t = ExtractEntityId(message); - var id = t.Item1; - var payload = t.Item2; - - if (string.IsNullOrEmpty(id)) - { - Log.Warning("Id must not be empty, dropping message [{0}]", message.GetType()); - Context.System.DeadLetters.Tell(message); - } - else - { - IImmutableList> buffer; - if (MessageBuffers.TryGetValue(id, out buffer)) - { - if (TotalBufferSize >= Settings.TunningParameters.BufferSize) - { - Log.Warning("Buffer is full, dropping message for entity [{0}]", message.GetType()); - Context.System.DeadLetters.Tell(message); - } - else - { - Log.Debug("Message for entity [{0}] buffered", id); - MessageBuffers.SetItem(id, buffer.Add(Tuple.Create(message, sender))); - } - } - else - DeliverTo(id, message, payload, sender); - } - } - - protected virtual void DeliverTo(string id, object message, object payload, IActorRef sender) - { - var name = Uri.EscapeDataString(id); - var child = Context.Child(name); - - if (Equals(child, ActorRefs.Nobody)) - GetEntity(id).Tell(payload, sender); - else - child.Tell(payload, sender); - } - - protected IActorRef GetEntity(string id) - { - var name = Uri.EscapeDataString(id); - var child = Context.Child(name); - if (Equals(child, ActorRefs.Nobody)) - { - Log.Debug("Starting entity [{0}] in shard [{1}]", id, ShardId); - - child = Context.Watch(Context.ActorOf(EntityProps, name)); - IdByRef = IdByRef.SetItem(child, id); - RefById = RefById.SetItem(id, child); - State = new ShardState(State.Entries.Add(id)); - } - - return child; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Sharding/ShardAllocationStrategy.cs b/src/contrib/cluster/Akka.Cluster.Sharding/ShardAllocationStrategy.cs deleted file mode 100644 index e213f59aea9..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Sharding/ShardAllocationStrategy.cs +++ /dev/null @@ -1,130 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Linq; -using System.Threading.Tasks; -using Akka.Actor; - -namespace Akka.Cluster.Sharding -{ - using ShardId = String; - - /// - /// Interface of the pluggable shard allocation and rebalancing logic used by the . - /// - public interface IShardAllocationStrategy : INoSerializationVerificationNeeded - { - /// - /// Invoked when the location of a new shard is to be decided. - /// - /// - /// Actor reference to the that requested the location of the shard, can be returned - /// if preference should be given to the node where the shard was first accessed. - /// - /// The id of the shard to allocate. - /// - /// All actor refs to and their current allocated shards, in the order they were allocated - /// - /// - /// of the actor ref of the that is to be responsible for the shard, - /// must be one of the references included in the parameter. - /// - Task AllocateShard(IActorRef requester, ShardId shardId, IImmutableDictionary> currentShardAllocations); - - /// - /// Invoked periodically to decide which shards to rebalance to another location. - /// - /// - /// All actor refs to and their current allocated shards, in the order they were allocated. - /// - /// - /// Set of shards that are currently being rebalanced, i.e. you should not include these in the returned set. - /// - /// of the shards to be migrated, may be empty to skip rebalance in this round. - Task> Rebalance(IImmutableDictionary> currentShardAllocations, IImmutableSet rebalanceInProgress); - } - - /// - /// The default implementation of allocates new shards - /// to the with least number of previously allocated shards. It picks shards - /// for rebalancing handoff from the with most number of previously allocated shards. - /// They will then be allocated to the with least number of previously allocated shards, - /// i.e. new members in the cluster. There is a configurable threshold of how large the difference - /// must be to begin the rebalancing. The number of ongoing rebalancing processes can be limited. - /// - [Serializable] - public class LeastShardAllocationStrategy : IShardAllocationStrategy - { - private readonly int _rebalanceThreshold; - private readonly int _maxSimultaneousRebalance; - - public LeastShardAllocationStrategy(int rebalanceThreshold, int maxSimultaneousRebalance) - { - _rebalanceThreshold = rebalanceThreshold; - _maxSimultaneousRebalance = maxSimultaneousRebalance; - } - - public Task AllocateShard(IActorRef requester, string shardId, IImmutableDictionary> currentShardAllocations) - { - var min = GetMinBy(currentShardAllocations, kv => kv.Value.Count); - return Task.FromResult(min.Key); - } - - public Task> Rebalance(IImmutableDictionary> currentShardAllocations, IImmutableSet rebalanceInProgress) - { - if (rebalanceInProgress.Count < _maxSimultaneousRebalance) - { - var leastShardsRegion = GetMinBy(currentShardAllocations, kv => kv.Value.Count); - var shards = - currentShardAllocations.Select(kv => kv.Value.Where(s => !rebalanceInProgress.Contains(s)).ToArray()); - var mostShards = GetMaxBy(shards, x => x.Length); - - if (mostShards.Length - leastShardsRegion.Value.Count >= _rebalanceThreshold) - { - return Task.FromResult>(ImmutableHashSet.Create(mostShards.First())); - } - } - - return Task.FromResult>(ImmutableHashSet.Empty); - } - - private static T GetMinBy(IEnumerable collection, Func extractor) - { - var minSize = int.MaxValue; - var result = default(T); - foreach (var value in collection) - { - var x = extractor(value); - if (x < minSize) - { - minSize = x; - result = value; - } - } - return result; - } - - private static T GetMaxBy(IEnumerable collection, Func extractor) - { - var minSize = int.MinValue; - var result = default(T); - foreach (var value in collection) - { - var x = extractor(value); - if (x > minSize) - { - minSize = x; - result = value; - } - } - return result; - } - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Sharding/ShardRegion.cs b/src/contrib/cluster/Akka.Cluster.Sharding/ShardRegion.cs deleted file mode 100644 index 0c12ae80949..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Sharding/ShardRegion.cs +++ /dev/null @@ -1,877 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using Akka.Actor; -using System.Collections.Immutable; -using System.Linq; -using System.Threading.Tasks; -using Akka.Event; -using Akka.Pattern; - -namespace Akka.Cluster.Sharding -{ - using ShardId = String; - using EntityId = String; - using Msg = Object; - - /// - /// This actor creates children entity actors on demand for the shards that it is told to be - /// responsible for. It delegates messages targeted to other shards to the responsible - /// actor on other nodes. - /// - public class ShardRegion : ActorBase - { - #region messages - - public interface IShardRegionCommand { } - public interface IShardRegionQuery { } - - /// - /// If the state of the entries are persistent you may stop entries that are not used to - /// reduce memory consumption. This is done by the application specific implementation of - /// the entity actors for example by defining receive timeout (). - /// If a message is already enqueued to the entity when it stops itself the enqueued message - /// in the mailbox will be dropped. To support graceful passivation without loosing such - /// messages the entity actor can send this message to its parent . - /// The specified wrapped will be sent back to the entity, which is - /// then supposed to stop itself. Incoming messages will be buffered by the `ShardRegion` - /// between reception of and termination of the entity. Such buffered messages - /// are thereafter delivered to a new incarnation of the entity. - /// - /// is a perfectly fine . - /// - [Serializable] - public sealed class Passivate : IShardRegionCommand - { - public Passivate(object stopMessage) - { - StopMessage = stopMessage; - } - - public object StopMessage { get; private set; } - } - - /// - /// Send this message to the actor to handoff all shards that are hosted by - /// the and then the actor will be stopped. You can - /// it to know when it is completed. - /// - [Serializable] - public sealed class GracefulShutdown : IShardRegionCommand - { - public static readonly GracefulShutdown Instance = new GracefulShutdown(); - - private GracefulShutdown() - { - } - } - - [Serializable] - public sealed class Retry : IShardRegionCommand - { - public static readonly Retry Instance = new Retry(); - private Retry() { } - } - - /// - /// We must be sure that a shard is initialized before to start send messages to it. - /// Shard could be terminated during initialization. - /// - [Serializable] - public sealed class ShardInitialized - { - public readonly ShardId ShardId; - - public ShardInitialized(ShardId shardId) - { - ShardId = shardId; - } - } - - /// - /// Send this message to the actor to request for , - /// which contains the addresses of all registered regions. - /// Intended for testing purpose to see when cluster sharding is "ready". - /// - [Serializable] - public sealed class GetCurrentRegions : IShardRegionQuery - { - public static readonly GetCurrentRegions Instance = new GetCurrentRegions(); - - private GetCurrentRegions() - { - } - } - - /// - /// Reply to . - /// - [Serializable] - public sealed class CurrentRegions - { - public readonly Address[] Regions; - public CurrentRegions(Address[] regions) - { - Regions = regions; - } - } - - /// - /// Send this message to the actor to request for , - /// which contains statistics about the currently running sharded entities in the - /// entire cluster. If the `timeout` is reached without answers from all shard regions - /// the reply will contain an empty map of regions. - /// - /// Intended for testing purpose to see when cluster sharding is "ready" or to monitor - /// the state of the shard regions. - /// - [Serializable] - public sealed class GetClusterShardingStats : IShardRegionQuery - { - public readonly TimeSpan Timeout; - - public GetClusterShardingStats(TimeSpan timeout) - { - Timeout = timeout; - } - } - - /// - /// Reply to , contains statistics about all the sharding regions in the cluster. - /// - [Serializable] - public sealed class ClusterShardingStats - { - public readonly IDictionary Regions; - - public ClusterShardingStats(IDictionary regions) - { - Regions = regions; - } - } - - /// - /// Send this message to the `ShardRegion` actor to request for , - /// which contains statistics about the currently running sharded entities in the - /// entire region. - /// Intended for testing purpose to see when cluster sharding is "ready" or to monitor - /// the state of the shard regions. - /// - /// For the statistics for the entire cluster, see . - /// - [Serializable] - public sealed class GetShardRegionStats : IShardRegionQuery - { - public static readonly GetShardRegionStats Instance = new GetShardRegionStats(); - - private GetShardRegionStats() - { - } - } - - [Serializable] - public sealed class ShardRegionStats - { - public readonly IDictionary Stats; - - public ShardRegionStats(IDictionary stats) - { - Stats = stats; - } - } - - /// - /// Send this message to a actor instance to request a - /// which describes the current state of the region. - /// The state contains information about what shards are running in this region - /// and what entities are running on each of those shards. - /// - [Serializable] - public sealed class GetShardRegionState : IShardRegionQuery - { - public static readonly GetShardRegionState Instance = new GetShardRegionState(); - - private GetShardRegionState() - { - } - } - - /// - /// Reply to If gathering the shard information times out the set of shards will be empty. - /// - [Serializable] - public sealed class CurrentShardRegionState - { - public readonly ISet Shards; - - public CurrentShardRegionState(ISet shards) - { - Shards = shards; - } - } - - [Serializable] - public sealed class ShardState - { - public readonly ShardId ShardId; - public readonly string[] EntityIds; - - public ShardState(string shardId, string[] entityIds) - { - ShardId = shardId; - EntityIds = entityIds; - } - } - - /// - /// When an remembering entities and the shard stops unexpected (e.g. persist failure), we - /// restart it after a back off using this message. - /// - [Serializable] - public sealed class RestartShard - { - public readonly ShardId ShardId; - public RestartShard(string shardId) - { - ShardId = shardId; - } - } - - #endregion - - /// - /// INTERNAL API. Sends stopMessage (e.g. ) to the entities and when all of them have terminated it replies with `ShardStopped`. - /// - internal class HandOffStopper : ReceiveActor - { - public static Actor.Props Props(ShardId shard, IActorRef replyTo, IEnumerable entities, object stopMessage) - { - return Actor.Props.Create(() => new HandOffStopper(shard, replyTo, entities, stopMessage)).WithDeploy(Deploy.Local); - } - - public HandOffStopper(ShardId shard, IActorRef replyTo, IEnumerable entities, object stopMessage) - { - var remaining = new HashSet(entities); - - Receive(t => - { - remaining.Remove(t.ActorRef); - if (remaining.Count == 0) - { - replyTo.Tell(new PersistentShardCoordinator.ShardStopped(shard)); - Context.Stop(Self); - } - }); - - foreach (var aref in remaining) - { - Context.Watch(aref); - aref.Tell(stopMessage); - } - } - } - - private class MemberAgeComparer : IComparer - { - public static readonly IComparer Instance = new MemberAgeComparer(); - - private MemberAgeComparer() { } - - public int Compare(Member x, Member y) - { - if (y.IsOlderThan(x)) return -1; - return x.IsOlderThan(y) ? 1 : 0; - } - } - - /// - /// Factory method for the of the actor. - /// - public static Props Props(string typeName, Props entityProps, ClusterShardingSettings settings, string coordinatorPath, IdExtractor extractEntityId, ShardResolver extractShardId, object handOffStopMessage) - { - return Actor.Props.Create(() => new ShardRegion(typeName, entityProps, settings, coordinatorPath, extractEntityId, extractShardId, handOffStopMessage)).WithDeploy(Deploy.Local); - } - - /// - /// Factory method for the of the actor when used in proxy only mode. - /// - public static Props ProxyProps(string typeName, ClusterShardingSettings settings, string coordinatorPath, IdExtractor extractEntityId, ShardResolver extractShardId) - { - return Actor.Props.Create(() => new ShardRegion(typeName, null, settings, coordinatorPath, extractEntityId, extractShardId, PoisonPill.Instance)).WithDeploy(Deploy.Local); - } - - public readonly string TypeName; - public readonly Props EntityProps; - public readonly ClusterShardingSettings Settings; - public readonly string CoordinatorPath; - public readonly IdExtractor IdExtractor; - public readonly ShardResolver ShardResolver; - public readonly object HandOffStopMessage; - - public readonly Cluster Cluster = Cluster.Get(Context.System); - - // sort by age, oldest first - private static readonly IComparer AgeOrdering = MemberAgeComparer.Instance; - - protected IImmutableDictionary> Regions = ImmutableDictionary>.Empty; - protected IImmutableDictionary RegionByShard = ImmutableDictionary.Empty; - protected IImmutableDictionary>> ShardBuffers = ImmutableDictionary>>.Empty; - protected IImmutableDictionary Shards = ImmutableDictionary.Empty; - protected IImmutableDictionary ShardsByRef = ImmutableDictionary.Empty; - protected IImmutableSet MembersByAge; - protected IImmutableSet HandingOff = ImmutableHashSet.Empty; - - private readonly ICancelable _retryTask; - private IActorRef _coordinator = null; - private int _retryCount = 0; - private bool _loggedFullBufferWarning = false; - private const int RetryCountThreshold = 5; - - public ShardRegion(string typeName, Props entityProps, ClusterShardingSettings settings, string coordinatorPath, IdExtractor extractEntityId, ShardResolver extractShardId, object handOffStopMessage) - { - TypeName = typeName; - EntityProps = entityProps; - Settings = settings; - CoordinatorPath = coordinatorPath; - IdExtractor = extractEntityId; - ShardResolver = extractShardId; - HandOffStopMessage = handOffStopMessage; - - //TODO: how to apply custom comparer different way? - var membersByAgeBuilder = ImmutableSortedSet.Empty.ToBuilder(); - membersByAgeBuilder.KeyComparer = AgeOrdering; - MembersByAge = membersByAgeBuilder.ToImmutable(); - - _retryTask = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(Settings.TunningParameters.RetryInterval, Settings.TunningParameters.RetryInterval, Self, Retry.Instance, Self); - } - - private ILoggingAdapter _log; - public ILoggingAdapter Log { get { return _log ?? (_log = Context.GetLogger()); } } - public bool GracefulShutdownInProgres { get; private set; } - public int TotalBufferSize { get { return ShardBuffers.Aggregate(0, (acc, entity) => acc + entity.Value.Count); } } - - protected ActorSelection CoordinatorSelection - { - get - { - var firstMember = MembersByAge.FirstOrDefault(); - return firstMember == null ? null : Context.ActorSelection(firstMember.Address.ToString() + CoordinatorPath); - } - } - - protected object RegistrationMessage - { - get - { - if (EntityProps != null && !EntityProps.Equals(Actor.Props.None)) - return new PersistentShardCoordinator.Register(Self); - else return new PersistentShardCoordinator.RegisterProxy(Self); - } - } - - protected override void PreStart() - { - Cluster.Subscribe(Self, new[] { typeof(ClusterEvent.IMemberEvent) }); - } - - protected override void PostStop() - { - base.PostStop(); - Cluster.Unsubscribe(Self); - _retryTask.Cancel(); - } - - protected bool MatchingRole(Member member) - { - return string.IsNullOrEmpty(Settings.Role) || member.HasRole(Settings.Role); - } - - private void ChangeMembers(IImmutableSet newMembers) - { - var before = MembersByAge.FirstOrDefault(); - var after = newMembers.FirstOrDefault(); - MembersByAge = newMembers; - if (!Equals(before, after)) - { - if (Log.IsDebugEnabled) - Log.Debug("Coordinator moved from [{0}] to [{1}]", - before == null ? string.Empty : before.Address.ToString(), - after == null ? string.Empty : after.Address.ToString()); - - _coordinator = null; - Register(); - } - } - - protected override bool Receive(object message) - { - if (message is Terminated) HandleTerminated(message as Terminated); - else if (message is ShardInitialized) InitializeShard(((ShardInitialized)message).ShardId, Sender); - else if (message is ClusterEvent.IClusterDomainEvent) HandleClusterEvent(message as ClusterEvent.IClusterDomainEvent); - else if (message is ClusterEvent.CurrentClusterState) HandleClusterState(message as ClusterEvent.CurrentClusterState); - else if (message is PersistentShardCoordinator.ICoordinatorMessage) HandleCoordinatorMessage(message as PersistentShardCoordinator.ICoordinatorMessage); - else if (message is IShardRegionCommand) HandleShardRegionCommand(message as IShardRegionCommand); - else if (message is IShardRegionQuery) HandleShardRegionQuery(message as IShardRegionQuery); - else if (IdExtractor(message) != null) DeliverMessage(message, Sender); - else if (message is RestartShard) DeliverMessage(message, Sender); - else return false; - return true; - } - - private void InitializeShard(ShardId id, IActorRef shardRef) - { - Log.Debug("Shard was initialized [{0}]", id); - Shards = Shards.SetItem(id, shardRef); - DeliverBufferedMessage(id, shardRef); - } - - private void Register() - { - var coordinator = CoordinatorSelection; - if (coordinator != null) - coordinator.Tell(RegistrationMessage); - - if (ShardBuffers.Count != 0 && _retryCount >= RetryCountThreshold) - Log.Warning("Trying to register to coordinator at [{0}], but no acknowledgement. Total [{1}] buffered messages.", - coordinator != null ? coordinator.PathString : string.Empty, TotalBufferSize); - } - - private void DeliverMessage(object message, IActorRef sender) - { - var restart = message as RestartShard; - if (restart != null) - { - var shardId = restart.ShardId; - IActorRef regionRef; - if (RegionByShard.TryGetValue(shardId, out regionRef)) - { - if (Self.Equals(regionRef)) GetShard(shardId); - } - else - { - IImmutableList> buffer; - if (!ShardBuffers.TryGetValue(shardId, out buffer)) - { - buffer = ImmutableList>.Empty; - Log.Debug("Request shard [{0}] home", shardId); - if (_coordinator != null) - _coordinator.Tell(new PersistentShardCoordinator.GetShardHome(shardId)); - } - - Log.Debug("Buffer message for shard [{0}]. Total [{1}] buffered messages.", shardId, buffer.Count + 1); - ShardBuffers = ShardBuffers.SetItem(shardId, buffer.Add(new KeyValuePair(message, sender))); - } - } - else - { - IActorRef region; - var shardId = ShardResolver(message); - if (RegionByShard.TryGetValue(shardId, out region)) - { - if (region.Equals(Self)) - { - var sref = GetShard(shardId); - if (Equals(sref, ActorRefs.Nobody)) - BufferMessage(shardId, message, sender); - else - { - IImmutableList> buffer; - if (ShardBuffers.TryGetValue(shardId, out buffer)) - { - // Since now messages to a shard is buffered then those messages must be in right order - BufferMessage(shardId, message, sender); - DeliverBufferedMessage(shardId, sref); - } - else - sref.Tell(message, sender); - } - } - else - { - Log.Debug("Forwarding request for shard [{0}] to [{1}]", shardId, region); - region.Tell(message, sender); - } - } - else - { - if (string.IsNullOrEmpty(shardId)) - { - Log.Warning("Shard must not be empty, dropping message [{0}]", message.GetType()); - Context.System.DeadLetters.Tell(message); - } - else - { - if (!ShardBuffers.ContainsKey(shardId)) - { - Log.Debug("Request shard [{0}] home", shardId); - if (_coordinator != null) - _coordinator.Tell(new PersistentShardCoordinator.GetShardHome(shardId)); - } - - BufferMessage(shardId, message, sender); - } - } - } - } - - private void BufferMessage(ShardId shardId, Msg message, IActorRef sender) - { - var totalBufferSize = TotalBufferSize; - if (totalBufferSize >= Settings.TunningParameters.BufferSize) - { - if (_loggedFullBufferWarning) - Log.Debug("Buffer is full, dropping message for shard [{0}]", shardId); - else - { - Log.Warning("Buffer is full, dropping message for shard [{0}]", shardId); - _loggedFullBufferWarning = true; - } - - Context.System.DeadLetters.Tell(message); - } - else - { - IImmutableList> buffer; - if (!ShardBuffers.TryGetValue(shardId, out buffer)) buffer = ImmutableList>.Empty; - ShardBuffers = ShardBuffers.SetItem(shardId, buffer.Add(new KeyValuePair(message, sender))); - - // log some insight to how buffers are filled up every 10% of the buffer capacity - var total = totalBufferSize + 1; - var bufferSize = Settings.TunningParameters.BufferSize; - if (total % (bufferSize / 10) == 0) - { - var logMsg = "ShardRegion for [{0}] is using [{1}] of it's buffer capacity"; - if ((total > bufferSize / 2)) - Log.Warning(logMsg + " The coordinator might not be available. You might want to check cluster membership status.", TypeName, 100 * total / bufferSize); - else - Log.Warning(logMsg, TypeName, 100 * total / bufferSize); - } - } - } - - private void HandleShardRegionCommand(IShardRegionCommand command) - { - if (command is Retry) - { - if (ShardBuffers.Count != 0) _retryCount++; - - if (_coordinator == null) Register(); - else - { - SendGracefulShutdownToCoordinator(); - RequestShardBufferHomes(); - TryCompleteGracefulShutdown(); - } - } - else if (command is GracefulShutdown) - { - Log.Debug("Starting graceful shutdown of region and all its shards"); - GracefulShutdownInProgres = true; - SendGracefulShutdownToCoordinator(); - TryCompleteGracefulShutdown(); - } - else Unhandled(command); - } - - private void HandleShardRegionQuery(IShardRegionQuery query) - { - if (query is GetCurrentRegions) - { - if (_coordinator != null) _coordinator.Forward(query); - else Sender.Tell(new CurrentRegions(new Address[0])); - } - else if (query is GetShardRegionState) ReplyToRegionStateQuery(Sender); - else if(query is GetShardRegionStats) ReplyToRegionStatsQuery(Sender); - else if (query is GetClusterShardingStats) - { - if(_coordinator != null) _coordinator.Tell(new ClusterShardingStats(new Dictionary(0))); - } - else Unhandled(query); - } - - private void ReplyToRegionStateQuery(IActorRef sender) - { - AskAllShardsAsync(Shard.GetCurrentShardState.Instance) - .PipeTo(sender, - success: shardStates => new CurrentShardRegionState(new HashSet(shardStates.Select(x => new ShardState(x.Item1, x.Item2.EntityIds)))), - failure: err => new CurrentShardRegionState(new HashSet())); - } - - private void ReplyToRegionStatsQuery(IActorRef sender) - { - AskAllShardsAsync(Shard.GetShardStats.Instance) - .PipeTo(sender, - success: shardStats => new ShardRegionStats(shardStats.ToDictionary(x => x.Item1, x => x.Item2.EntityCount)), - failure: err => new ShardRegionStats(new Dictionary(0))); - } - - private Task[]> AskAllShardsAsync(object message) - { - var timeout = TimeSpan.FromSeconds(3); - var tasks = Shards.Select(entity => entity.Value.Ask(message, timeout).ContinueWith(t => Tuple.Create(entity.Key, t.Result))); - return Task.WhenAll(tasks); - } - - private void TryCompleteGracefulShutdown() - { - if(GracefulShutdownInProgres && Shards.Count == 0 && ShardBuffers.Count == 0) - Context.Stop(Self); // all shards have been rebalanced, complete graceful shutdown - } - - private void SendGracefulShutdownToCoordinator() - { - if (GracefulShutdownInProgres && _coordinator != null) - _coordinator.Tell(new PersistentShardCoordinator.GracefulShutdownRequest(Self)); - } - - private void HandleCoordinatorMessage(PersistentShardCoordinator.ICoordinatorMessage message) - { - if (message is PersistentShardCoordinator.HostShard) - { - var shard = ((PersistentShardCoordinator.HostShard)message).Shard; - Log.Debug("Host shard [{0}]", shard); - RegionByShard = RegionByShard.SetItem(shard, Self); - UpdateRegionShards(Self, shard); - - // Start the shard, if already started this does nothing - GetShard(shard); - - Sender.Tell(new PersistentShardCoordinator.ShardStarted(shard)); - } - else if (message is PersistentShardCoordinator.ShardHome) - { - var home = (PersistentShardCoordinator.ShardHome)message; - Log.Debug("Shard [{0}] located at [{1}]", home.Shard, home.Ref); - IActorRef region; - - if (RegionByShard.TryGetValue(home.Shard, out region)) - { - if (region.Equals(Self) && !home.Ref.Equals(Self)) - { - // should not happen, inconsistency between ShardRegion and PersistentShardCoordinator - throw new IllegalStateException(string.Format("Unexpected change of shard [{0}] from self to [{1}]", home.Shard, home.Ref)); - } - } - - RegionByShard = RegionByShard.SetItem(home.Shard, home.Ref); - UpdateRegionShards(home.Ref, home.Shard); - - if (!home.Ref.Equals(Self)) - Context.Watch(home.Ref); - - if (home.Ref.Equals(Self)) - { - var shardRef = GetShard(home.Shard); - if (!Equals(shardRef, ActorRefs.Nobody)) - DeliverBufferedMessage(home.Shard, shardRef); - } - else - DeliverBufferedMessage(home.Shard, home.Ref); - } - else if (message is PersistentShardCoordinator.RegisterAck) - { - _coordinator = ((PersistentShardCoordinator.RegisterAck)message).Coordinator; - Context.Watch(_coordinator); - RequestShardBufferHomes(); - } - else if (message is PersistentShardCoordinator.BeginHandOff) - { - var shard = ((PersistentShardCoordinator.BeginHandOff)message).Shard; - Log.Debug("Begin hand off shard [{0}]", shard); - IActorRef regionRef; - if (RegionByShard.TryGetValue(shard, out regionRef)) - { - IImmutableSet updatedShards; - if (!Regions.TryGetValue(regionRef, out updatedShards)) - updatedShards = ImmutableHashSet.Empty; - - updatedShards = updatedShards.Remove(shard); - if (updatedShards.Count == 0) - Regions = Regions.Remove(regionRef); - else - Regions = Regions.SetItem(regionRef, updatedShards); - - RegionByShard = RegionByShard.Remove(shard); - } - - Sender.Tell(new PersistentShardCoordinator.BeginHandOffAck(shard)); - } - else if (message is PersistentShardCoordinator.HandOff) - { - var shard = ((PersistentShardCoordinator.HandOff)message).Shard; - Log.Debug("Hand off shard [{0}]", shard); - - // must drop requests that came in between the BeginHandOff and now, - // because they might be forwarded from other regions and there - // is a risk or message re-ordering otherwise - if (ShardBuffers.ContainsKey(shard)) - { - ShardBuffers = ShardBuffers.Remove(shard); - _loggedFullBufferWarning = false; - } - - IActorRef actorRef; - if (Shards.TryGetValue(shard, out actorRef)) - { - HandingOff = HandingOff.Add(actorRef); - actorRef.Forward(message); - } - else - Sender.Tell(new PersistentShardCoordinator.ShardStopped(shard)); - } - else Unhandled(message); - } - - private void UpdateRegionShards(IActorRef regionRef, string shard) - { - IImmutableSet shards; - if (!Regions.TryGetValue(regionRef, out shards)) shards = ImmutableSortedSet.Empty; - Regions = Regions.SetItem(regionRef, shards.Add(shard)); - } - - private void RequestShardBufferHomes() - { - if (_coordinator != null) - { - foreach (var buffer in ShardBuffers) - { - var logMsg = "Retry request for shard [{0}] homes from coordinator at [{1}]. [{2}] buffered messages."; - if (_retryCount >= RetryCountThreshold) - Log.Warning(logMsg, buffer.Key, _coordinator, buffer.Value.Count); - else - Log.Debug(logMsg, buffer.Key, _coordinator, buffer.Value.Count); - - _coordinator.Tell(new PersistentShardCoordinator.GetShardHome(buffer.Key)); - } - } - } - - private void DeliverBufferedMessage(ShardId shardId, IActorRef receiver) - { - IImmutableList> buffer; - if (ShardBuffers.TryGetValue(shardId, out buffer)) - { - Log.Debug("Deliver [{0}] buffered messages for shard [{1}]", buffer.Count, shardId); - - foreach (var m in buffer) - { - receiver.Tell(m.Key, m.Value); - } - ShardBuffers = ShardBuffers.Remove(shardId); - } - - _loggedFullBufferWarning = false; - _retryCount = 0; - } - - private IActorRef GetShard(ShardId id) - { - //TODO: change on ConcurrentDictionary.GetOrAdd? - IActorRef region = null; - if (!Shards.TryGetValue(id, out region)) - { - if (EntityProps == null || EntityProps.Equals(Actor.Props.Empty)) - { - throw new IllegalStateException("Shard must not be allocated to a proxy only ShardRegion"); - } - else if (ShardsByRef.Values.All(shardId => shardId != id)) - { - Log.Debug("Starting shard [{0}] in region", id); - - //val name = URLEncoder.encode(id, "utf-8") - var name = Uri.EscapeDataString(id); - var shardRef = Context.Watch(Context.ActorOf(PersistentShard.Props( - TypeName, - id, - EntityProps, - Settings, - IdExtractor, - ShardResolver, - HandOffStopMessage).WithDispatcher(Context.Props.Dispatcher), name)); - - ShardsByRef = ShardsByRef.SetItem(shardRef, id); - return shardRef; - } - } - - return region ?? ActorRefs.Nobody; - } - - private void HandleClusterState(ClusterEvent.CurrentClusterState state) - { - var builder = ImmutableSortedSet.Empty.ToBuilder(); - builder.KeyComparer = AgeOrdering; - var members = builder.ToImmutable() - .Union(state.Members.Where(m => m.Status == MemberStatus.Up && MatchingRole(m))); - - ChangeMembers(members); - } - - private void HandleClusterEvent(ClusterEvent.IClusterDomainEvent e) - { - if (e is ClusterEvent.MemberUp) - { - var m = ((ClusterEvent.MemberUp)e).Member; - if (MatchingRole(m)) - ChangeMembers(MembersByAge.Add(m)); - } - else if (e is ClusterEvent.MemberRemoved) - { - var m = ((ClusterEvent.MemberRemoved)e).Member; - if (m.UniqueAddress == Cluster.SelfUniqueAddress) - Context.Stop(Self); - else if (MatchingRole(m)) - ChangeMembers(MembersByAge.Remove(m)); - } - else Unhandled(e); - } - - private void HandleTerminated(Terminated terminated) - { - IImmutableSet shards; - ShardId shard; - if (_coordinator != null && _coordinator.Equals(terminated.ActorRef)) - { - _coordinator = null; - } - else if (Regions.TryGetValue(terminated.ActorRef, out shards)) - { - RegionByShard = RegionByShard.RemoveRange(shards); - Regions = Regions.Remove(terminated.ActorRef); - - if (Log.IsDebugEnabled) - Log.Debug("Region [{0}] with shards [{1}] terminated", terminated.ActorRef, string.Join(", ", shards)); - } - else if (ShardsByRef.TryGetValue(terminated.ActorRef, out shard)) - { - ShardsByRef = ShardsByRef.Remove(terminated.ActorRef); - Shards = Shards.Remove(shard); - //Are we meant to be handing off, or is this a unknown stop? - if (HandingOff.Contains(terminated.ActorRef)) - { - HandingOff = HandingOff.Remove(terminated.ActorRef); - Log.Debug("Shard [{0}] handoff complete", shard); - } - else - { - // if persist fails it will stop - Log.Debug("Shard [{0}] terminated while not being handed off", shard); - if (Settings.RememberEntities) - { - Context.System.Scheduler.ScheduleTellOnce(Settings.TunningParameters.ShardFailureBackoff, Self, new RestartShard(shard), Self); - } - } - - TryCompleteGracefulShutdown(); - } - } - } - -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Sharding/packages.config b/src/contrib/cluster/Akka.Cluster.Sharding/packages.config deleted file mode 100644 index 4ae7e7e980b..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Sharding/packages.config +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Sharding/paket.references b/src/contrib/cluster/Akka.Cluster.Sharding/paket.references deleted file mode 100644 index b4721cd0526..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Sharding/paket.references +++ /dev/null @@ -1,2 +0,0 @@ -Google.ProtocolBuffers -System.Collections.Immutable \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Sharding/reference.conf b/src/contrib/cluster/Akka.Cluster.Sharding/reference.conf deleted file mode 100644 index fb6c7a85387..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Sharding/reference.conf +++ /dev/null @@ -1,121 +0,0 @@ -############################################### -# Akka Cluster Sharding Reference Config File # -############################################### - -# This is the reference config file that contains all the default settings. -# Make your edits/overrides in your application.conf. - - -# //#sharding-ext-config -# Settings for the ClusterShardingExtension -akka.cluster.sharding { - - # The extension creates a top level actor with this name in top level system scope, - # e.g. '/system/sharding' - guardian-name = sharding - - # Specifies that entities runs on cluster nodes with a specific role. - # If the role is not specified (or empty) all nodes in the cluster are used. - role = "" - - # When this is set to 'on' the active entity actors will automatically be restarted - # upon Shard restart. i.e. if the Shard is started on a different ShardRegion - # due to rebalance or crash. - remember-entities = off - - # If the coordinator can't store state changes it will be stopped - # and started again after this duration, with an exponential back-off - # of up to 5 times this duration. - coordinator-failure-backoff = 5 s - - # The ShardRegion retries registration and shard location requests to the - # ShardCoordinator with this interval if it does not reply. - retry-interval = 2s - - # Maximum number of messages that are buffered by a ShardRegion actor. - buffer-size = 100000 - - # Timeout of the shard rebalancing process. - handoff-timeout = 60s - - # Time given to a region to acknowledge it's hosting a shard. - shard-start-timeout = 10s - - # If the shard is remembering entities and can't store state changes - # will be stopped and then started again after this duration. Any messages - # sent to an affected entity may be lost in this process. - shard-failure-backoff = 10s - - # If the shard is remembering entities and an entity stops itself without - # using passivate. The entity will be restarted after this duration or when - # the next message for it is received, which ever occurs first. - entity-restart-backoff = 10s - - # Rebalance check is performed periodically with this interval. - rebalance-interval = 10s - - # Absolute path to the journal plugin configuration entity that is to be - # used for the internal persistence of ClusterSharding. If not defined - # the default journal plugin is used. Note that this is not related to - # persistence used by the entity actors. - journal-plugin-id = "" - - # Absolute path to the snapshot plugin configuration entity that is to be - # used for the internal persistence of ClusterSharding. If not defined - # the default snapshot plugin is used. Note that this is not related to - # persistence used by the entity actors. - snapshot-plugin-id = "" - - # Parameter which determines how the coordinator will be store a state - # valid values either "persistence" or "ddata" - # The "ddata" mode is experimental, since it depends on the experimental - # module akka-distributed-data-experimental. - state-store-mode = "persistence" - - # The shard saves persistent snapshots after this number of persistent - # events. Snapshots are used to reduce recovery times. - snapshot-after = 1000 - - # Setting for the default shard allocation strategy - least-shard-allocation-strategy { - # Threshold of how large the difference between most and least number of - # allocated shards must be to begin the rebalancing. - rebalance-threshold = 10 - - # The number of ongoing rebalancing processes is limited to this number. - max-simultaneous-rebalance = 3 - } - - # Timeout of waiting the initial distributed state (an initial state will be queried again if the timeout happened) - # works only for state-store-mode = "ddata" - waiting-for-state-timeout = 5s - - # Timeout of waiting for update the distributed state (update will be retried if the timeout happened) - # works only for state-store-mode = "ddata" - updating-state-timeout = 5s - - # Settings for the coordinator singleton. Same layout as akka.cluster.singleton. - coordinator-singleton = "akka.cluster.singleton" - - # The id of the dispatcher to use for ClusterSharding actors. - # If not specified default dispatcher is used. - # If specified you need to define the settings of the actual dispatcher. - # This dispatcher for the entity actors is defined by the user provided - # Props, i.e. this dispatcher is not used for the entity actors. - use-dispatcher = "" -} -# //#sharding-ext-config - - -# Protobuf serializer for Cluster Sharding messages -akka.actor { - serializers { - akka-sharding = "Akka.Cluster.Sharding.Serialization.ClusterShardingMessageSerializer, Akka.Cluster.Sharding" - } - serialization-bindings { - "Akka.Cluster.Sharding.IClusterShardingSerializable, Akka.Cluster.Sharding" = akka-sharding - } - serialization-identifiers { - "Akka.Cluster.Sharding.Serialization.ClusterShardingMessageSerializer, Akka.Cluster.Sharding" = 13 - } -} diff --git a/src/contrib/cluster/Akka.Cluster.Tools.Tests/Akka.Cluster.Tools.Tests.csproj b/src/contrib/cluster/Akka.Cluster.Tools.Tests/Akka.Cluster.Tools.Tests.csproj deleted file mode 100644 index e2b41cf6d64..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools.Tests/Akka.Cluster.Tools.Tests.csproj +++ /dev/null @@ -1,402 +0,0 @@ - - - - - Debug - AnyCPU - {9D8D62C7-7B4B-4CDF-8FE8-675DB71F6B21} - Library - Properties - Akka.Cluster.Tools.Tests - Akka.Cluster.Tools.Tests - v4.5 - 512 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\..\..\packages\FluentAssertions.4.1.0\lib\net45\FluentAssertions.dll - True - - - ..\..\..\packages\FluentAssertions.4.1.0\lib\net45\FluentAssertions.Core.dll - True - - - ..\..\..\packages\Google.ProtocolBuffers.2.4.1.555\lib\net40\Google.ProtocolBuffers.dll - True - - - ..\..\..\packages\Google.ProtocolBuffers.2.4.1.555\lib\net40\Google.ProtocolBuffers.Serialization.dll - True - - - - ..\..\..\packages\System.Collections.Immutable.1.1.37\lib\dotnet\System.Collections.Immutable.dll - True - - - - - - - - - - ..\..\..\packages\xunit.abstractions.2.0.0\lib\net35\xunit.abstractions.dll - True - - - ..\..\..\packages\xunit.assert.2.1.0\lib\dotnet\xunit.assert.dll - True - - - ..\..\..\packages\xunit.extensibility.core.2.1.0\lib\dotnet\xunit.core.dll - True - - - ..\..\..\packages\xunit.extensibility.execution.2.1.0\lib\net45\xunit.execution.desktop.dll - True - - - - - - - - - - - - - - - - - {f0781bea-5ba0-4af0-bb15-e3f209b681f5} - Akka.Cluster.Tests.MultiNode - - - {6ab00f61-269a-4501-b06a-026707f000a7} - Akka.Cluster - - - {e5957c3e-2b1e-469f-a680-7953b4dea31b} - Akka.Remote.TestKit - - - {ea4ff8fd-7c53-49c8-b9aa-02e458b3e6a7} - Akka.Remote - - - {0d3cbad0-bbdb-43e5-afc4-ed1d3ecdc224} - Akka.TestKit - - - {5deddf90-37f0-48d3-a0b0-a5cbd8a7e377} - Akka - - - {7dbd5c17-5e9d-40c4-9201-d092751532a7} - Akka.TestKit.Xunit2 - - - {5cf8a8be-b634-473f-bb01-eba878746bd4} - Akka.Cluster.Tools - - - - - - - - - ..\..\..\..\packages\Google.ProtocolBuffers\lib\net35\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\packages\Google.ProtocolBuffers\lib\net35\Google.ProtocolBuffers.dll - True - True - - - - - - - ..\..\..\..\packages\Google.ProtocolBuffers\lib\net20\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\packages\Google.ProtocolBuffers\lib\net20\Google.ProtocolBuffers.dll - True - True - - - - - - - - ..\..\..\..\packages\Google.ProtocolBuffers\lib\sl30\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\packages\Google.ProtocolBuffers\lib\sl30\Google.ProtocolBuffers.dll - True - True - - - - - - - ..\..\..\..\packages\Google.ProtocolBuffers\lib\sl40\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\packages\Google.ProtocolBuffers\lib\sl40\Google.ProtocolBuffers.dll - True - True - - - - - - - ..\..\..\..\packages\Google.ProtocolBuffers\lib\portable-net40+sl4+sl5+wp7+wp8+win8\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\packages\Google.ProtocolBuffers\lib\portable-net40+sl4+sl5+wp7+wp8+win8\Google.ProtocolBuffers.dll - True - True - - - - - - - - - - - - ..\..\..\..\packages\test\FluentAssertions\lib\win8\FluentAssertions.Core.dll - True - True - - - ..\..\..\..\packages\test\FluentAssertions\lib\win8\FluentAssertions.dll - True - True - - - - - - - ..\..\..\..\packages\test\FluentAssertions\lib\net40\FluentAssertions.Core.dll - True - True - - - ..\..\..\..\packages\test\FluentAssertions\lib\net40\FluentAssertions.dll - True - True - - - - - - - - ..\..\..\..\packages\test\FluentAssertions\lib\sl5\FluentAssertions.Core.dll - True - True - - - ..\..\..\..\packages\test\FluentAssertions\lib\sl5\FluentAssertions.dll - True - True - - - ..\..\..\..\packages\test\FluentAssertions\lib\sl5\Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight.dll - True - True - - - - - - - ..\..\..\..\packages\test\FluentAssertions\lib\wp8\FluentAssertions.Core.dll - True - True - - - ..\..\..\..\packages\test\FluentAssertions\lib\wp8\FluentAssertions.dll - True - True - - - - - - - ..\..\..\..\packages\test\FluentAssertions\lib\portable-monotouch+monoandroid+xamarin.ios\FluentAssertions.Core.dll - True - True - - - - - - - ..\..\..\..\packages\test\FluentAssertions\lib\portable-win81+wpa81\FluentAssertions.Core.dll - True - True - - - ..\..\..\..\packages\test\FluentAssertions\lib\portable-win81+wpa81\FluentAssertions.dll - True - True - - - - - - - ..\..\..\..\packages\test\FluentAssertions\lib\portable-net40+sl5+win8+wp8+wpa81\FluentAssertions.Core.dll - True - True - - - ..\..\..\..\packages\test\FluentAssertions\lib\portable-net40+sl5+win8+wp8+wpa81\FluentAssertions.dll - True - True - - - - - - - - - - ..\..\..\..\packages\test\xunit.abstractions\lib\portable-net45+win+wpa81+wp80+monotouch+monoandroid+Xamarin.iOS\xunit.abstractions.dll - True - True - - - - - - - - - - - <__paket__xunit_core_props>win81\xunit.core - - - - - <__paket__xunit_core_props>wpa81\xunit.core - - - - - <__paket__xunit_core_props>portable-net45+win8+wp8+wpa81\xunit.core - - - - - - - - - - - ..\..\..\..\packages\test\xunit.extensibility.execution\lib\win8\xunit.execution.dotnet.dll - True - True - - - - - - - - ..\..\..\..\packages\test\xunit.extensibility.execution\lib\monoandroid\xunit.execution.dotnet.dll - True - True - - - - - - - ..\..\..\..\packages\test\xunit.extensibility.execution\lib\monotouch\xunit.execution.dotnet.dll - True - True - - - - - - - ..\..\..\..\packages\test\xunit.extensibility.execution\lib\wp8\xunit.execution.dotnet.dll - True - True - - - - - - - ..\..\..\..\packages\test\xunit.extensibility.execution\lib\xamarinios\xunit.execution.dotnet.dll - True - True - - - - - - - ..\..\..\..\packages\test\xunit.extensibility.execution\lib\portable-net45+win8+wp8+wpa81\xunit.execution.dotnet.dll - True - True - - - - - - \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Tools.Tests/ClusterClient/ClusterClientSpec.cs b/src/contrib/cluster/Akka.Cluster.Tools.Tests/ClusterClient/ClusterClientSpec.cs deleted file mode 100644 index 6533ad3bc3c..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools.Tests/ClusterClient/ClusterClientSpec.cs +++ /dev/null @@ -1,333 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using Akka.Actor; -using Akka.Cluster.Tests.MultiNode; -using Akka.Cluster.Tools.Client; -using Akka.Cluster.Tools.PublishSubscribe; -using Akka.Cluster.Tools.PublishSubscribe.Internal; -using Akka.Configuration; -using Akka.Remote.TestKit; -using Akka.Remote.Transport; -using Xunit; - -namespace Akka.Cluster.Tools.Tests.Client -{ - public class ClusterClientSpecConfig : MultiNodeConfig - { - public readonly RoleName Client; - public readonly RoleName First; - public readonly RoleName Second; - public readonly RoleName Third; - public readonly RoleName Fourth; - - public ClusterClientSpecConfig() - { - Client = Role("client"); - First = Role("first"); - Second = Role("second"); - Third = Role("third"); - Fourth = Role("fourth"); - - CommonConfig = ConfigurationFactory.ParseString(@" - akka.loglevel = INFO - akka.actor.provider = ""Akka.Cluster.ClusterActorRefProvider, Akka.Cluster"" - akka.remote.log-remote-lifecycle-events = off - akka.cluster.auto-down-unreachable-after = 0s - akka.cluster.client.heartbeat-interval = 1s - akka.cluster.client.acceptable-heartbeat-pause = 3s - ").WithFallback(MultiNodeClusterSpec.ClusterConfig()); - - TestTransport = true; - } - } - - public class ClusterClientNode1 : ClusterClientSpec { } - public class ClusterClientNode2 : ClusterClientSpec { } - public class ClusterClientNode3 : ClusterClientSpec { } - public class ClusterClientNode4 : ClusterClientSpec { } - public class ClusterClientNode5 : ClusterClientSpec { } - - public abstract class ClusterClientSpec : MultiNodeClusterSpec - { - #region setup - - public class TestService : ReceiveActor - { - public TestService(IActorRef testActorRef) - { - ReceiveAny(msg => - { - testActorRef.Forward(msg); - Sender.Tell(msg.ToString() + "-ack"); - }); - } - } - - public class Service : ReceiveActor - { - public Service() - { - ReceiveAny(msg => Sender.Tell(msg)); - } - } - - private readonly RoleName _client; - private readonly RoleName _first; - private readonly RoleName _second; - private readonly RoleName _third; - private readonly RoleName _fourth; - - private ISet _remainingServerRoleNames; - - private ActorPath[] InitialContacts - { - get - { - return _remainingServerRoleNames.Except(new[] { _first, _fourth }).Select(r => Node(r) / "user" / "receptionist").ToArray(); - } - } - - protected ClusterClientSpec() : this(new ClusterClientSpecConfig()) - { - } - - protected ClusterClientSpec(ClusterClientSpecConfig config) : base(config) - { - _client = config.Client; - _first = config.First; - _second = config.Second; - _third = config.Third; - _fourth = config.Fourth; - - _remainingServerRoleNames = new HashSet(new[] { _first, _second, _third, _fourth }); - } - - private void Join(RoleName from, RoleName to) - { - RunOn(() => - { - Cluster.Join(Node(to).Address); - CreateReceptionist(); - }, from); - EnterBarrier(to.Name + "-joined"); - } - - private void CreateReceptionist() - { - var x = ClusterClientReceptionist.Get(Sys); - } - - private void AwaitCount(int expected) - { - AwaitAssert(() => - { - DistributedPubSub.Get(Sys).Mediator.Tell(Count.Instance); - Assert.Equal(expected, ExpectMsg()); - }); - } - - private RoleName GetRoleName(Address address) - { - return _remainingServerRoleNames.FirstOrDefault(r => Node(r).Address.Equals(address)); - } - - #endregion - - //[MultiNodeFact(Skip = "TODO")] - public void ClusterClient_should_startup_cluster() - { - Within(TimeSpan.FromSeconds(30), () => - { - Join(_first, _first); - Join(_second, _first); - Join(_third, _first); - Join(_fourth, _first); - - RunOn(() => - { - var service = Sys.ActorOf(Props.Create(() => new TestService(TestActor)), "testService"); - ClusterClientReceptionist.Get(Sys).RegisterService(service); - }, _fourth); - - RunOn(() => - { - AwaitCount(1); - }, _first, _second, _third, _fourth); - EnterBarrier("after-1"); - }); - } - - //[MultiNodeFact(Skip = "TODO")] - public void ClusterClient_should_communicate_to_any_node_in_cluster() - { - ClusterClient_should_startup_cluster(); - - Within(TimeSpan.FromSeconds(10), () => - { - RunOn(() => - { - var c = Sys.ActorOf(ClusterClient.Props(ClusterClientSettings.Create(Sys).WithInitialContacts(InitialContacts)), "client1"); - c.Tell(new ClusterClient.Send("/user/testService", "hello", localAffinity: true)); - ExpectMsg("hello-ack"); - Sys.Stop(c); - }, _client); - - RunOn(() => - { - ExpectMsg("hello"); - }, _fourth); - - EnterBarrier("after-2"); - }); - } - - //[MultiNodeFact(Skip = "TODO")] - public void ClusterClient_should_demonstrate_usage() - { - ClusterClient_should_communicate_to_any_node_in_cluster(); - - Within(TimeSpan.FromSeconds(15), () => - { - RunOn(() => - { - var serviceA = Sys.ActorOf(Props.Create(), "serviceA"); - ClusterClientReceptionist.Get(Sys).RegisterService(serviceA); - }, _first); - - RunOn(() => - { - var serviceB = Sys.ActorOf(Props.Create(), "serviceB"); - ClusterClientReceptionist.Get(Sys).RegisterService(serviceB); - }, _second, _third); - - RunOn(() => - { - AwaitCount(4); - }, _first, _second, _third, _fourth); - - RunOn(() => - { - var c = Sys.ActorOf(ClusterClient.Props(ClusterClientSettings.Create(Sys).WithInitialContacts(InitialContacts)), "client"); - c.Tell(new ClusterClient.Send("/user/serviceA", "hello", localAffinity: true)); - c.Tell(new ClusterClient.SendToAll("/user/serviceB", "hi")); - }, _client); - - RunOn(() => - { - // note that "hi" was sent to 2 "serviceB" - var received = ReceiveN(3); - Assert.True(received.Contains("hello")); - Assert.True(received.Contains("hi")); - }, _client); - - // strange, barriers fail without this sleep - Thread.Sleep(1000); - EnterBarrier("after-3"); - }); - } - - //[MultiNodeFact(Skip = "TODO")] - public void ClusterClient_should_reestablish_connection_to_another_receptionist_when_server_is_shutdown() - { - ClusterClient_should_demonstrate_usage(); - - Within(TimeSpan.FromSeconds(30), () => - { - RunOn(() => - { - var service2 = Sys.ActorOf(Props.Create(() => new TestService(TestActor)), "service2"); - ClusterClientReceptionist.Get(Sys).RegisterService(service2); - AwaitCount(8); - }, _first, _second, _third, _fourth); - EnterBarrier("service2-replicated"); - - RunOn(() => - { - var c = Sys.ActorOf(ClusterClient.Props(ClusterClientSettings.Create(Sys).WithInitialContacts(InitialContacts)), "client2"); - c.Tell(new ClusterClient.Send("/user/service2", "bonjour", localAffinity: true)); - ExpectMsg("bonjour-ack"); - var lastSenderAddress = LastSender.Path.Address; - - var receptionistRoleName = RoleName(lastSenderAddress); - if (receptionistRoleName == null) throw new Exception("Unexpected missing role name: " + lastSenderAddress); - - TestConductor.Exit(receptionistRoleName, 0).Wait(); - _remainingServerRoleNames.Remove(receptionistRoleName); - - Within(Remaining - TimeSpan.FromSeconds(3), () => - { - AwaitAssert(() => - { - c.Tell(new ClusterClient.Send("/user/service2", "hi again", localAffinity: true)); - ExpectMsg("hi again-ack", TimeSpan.FromSeconds(1)); - }); - }); - Sys.Stop(c); - }, _client); - EnterBarrier("verified-3"); - - ReceiveWhile(TimeSpan.FromSeconds(2), msg => - { - if (msg.Equals("hi again")) return msg; - else throw new Exception("unexpected message: " + msg); - }); - EnterBarrier("after-4"); - }); - } - - [MultiNodeFact(Skip = "TODO")] - public void ClusterClient_should_reestablish_connection_to_receptionist_after_partition() - { - ClusterClient_should_reestablish_connection_to_another_receptionist_when_server_is_shutdown(); - - Within(TimeSpan.FromSeconds(30), () => - { - RunOn(() => - { - var c = Sys.ActorOf(ClusterClient.Props(ClusterClientSettings.Create(Sys).WithInitialContacts(InitialContacts)), "client3"); - c.Tell(new ClusterClient.Send("/user/service2", "bonjour2", localAffinity: true)); - ExpectMsg("bonjour2-ack"); - var lastSenderAddress = LastSender.Path.Address; - - var receptionistRoleName = RoleName(lastSenderAddress); - if (receptionistRoleName == null) throw new Exception("Unexpected missing role name: " + lastSenderAddress); - - // shutdown all but the one that the client is connected to - foreach (var roleName in _remainingServerRoleNames.ToArray()) - if (!roleName.Equals(receptionistRoleName)) TestConductor.Exit(roleName, 0).Wait(); - _remainingServerRoleNames = new HashSet(new[] { receptionistRoleName }); - - // network partition between client and server - TestConductor.Blackhole(_client, receptionistRoleName, ThrottleTransportAdapter.Direction.Both).Wait(); - c.Tell(new ClusterClient.Send("/user/service2", "ping", localAffinity: true)); - // if we would use remote watch the failure detector would trigger and - // connection quarantined - ExpectNoMsg(TimeSpan.FromSeconds(5)); - - TestConductor.PassThrough(_client, receptionistRoleName, ThrottleTransportAdapter.Direction.Both).Wait(); - - var expectedAddress = Node(receptionistRoleName).Address; - AwaitAssert(() => - { - c.Tell(new ClusterClient.Send("/user/service2", "bonjour3", localAffinity: true)); - ExpectMsg("bonjour3-ack", TimeSpan.FromSeconds(1)); - var lastSenderAddress2 = LastSender.Path.Address; - Assert.Equal(expectedAddress, lastSenderAddress2); - }); - Sys.Stop(c); - - }, _client); - EnterBarrier("after-5"); - }); - } - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Tools.Tests/Properties/AssemblyInfo.cs b/src/contrib/cluster/Akka.Cluster.Tools.Tests/Properties/AssemblyInfo.cs deleted file mode 100644 index 2d88700b66f..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools.Tests/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Akka.Cluster.Tools.Tests")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Akka.Cluster.Tools.Tests")] -[assembly: AssemblyCopyright("Copyright © 2015")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("9d8d62c7-7b4b-4cdf-8fe8-675db71f6b21")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/contrib/cluster/Akka.Cluster.Tools.Tests/PublishSubscribe/DistributedPubSubMediatorSpec.cs b/src/contrib/cluster/Akka.Cluster.Tools.Tests/PublishSubscribe/DistributedPubSubMediatorSpec.cs deleted file mode 100644 index 0de15f76cd0..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools.Tests/PublishSubscribe/DistributedPubSubMediatorSpec.cs +++ /dev/null @@ -1,769 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; -using Akka.Actor; -using Akka.Cluster.Tests.MultiNode; -using Akka.Cluster.Tools.PublishSubscribe; -using Akka.Cluster.Tools.PublishSubscribe.Internal; -using Akka.Configuration; -using Akka.Event; -using Akka.Remote.TestKit; -using Xunit; - -namespace Akka.Cluster.Tools.Tests.PublishSubscribe -{ - public class DistributedPubSubMediatorSpecConfig : MultiNodeConfig - { - public readonly RoleName First; - public readonly RoleName Second; - public readonly RoleName Third; - - public DistributedPubSubMediatorSpecConfig() - { - First = Role("first"); - Second = Role("second"); - Third = Role("third"); - - CommonConfig = ConfigurationFactory.ParseString(@" - akka.loglevel = INFO - akka.actor.provider = ""Akka.Cluster.ClusterActorRefProvider, Akka.Cluster"" - akka.remote.log-remote-lifecycle-events = off - akka.cluster.auto-down-unreachable-after = 0s - akka.cluster.pub-sub.max-delta-elements = 500 - ").WithFallback(MultiNodeClusterSpec.ClusterConfig()); - } - } - - public class DistributedPubSubMediatorNode1 : DistributedPubSubMediatorSpec { } - public class DistributedPubSubMediatorNode2 : DistributedPubSubMediatorSpec { } - public class DistributedPubSubMediatorNode3 : DistributedPubSubMediatorSpec { } - - public abstract class DistributedPubSubMediatorSpec : MultiNodeClusterSpec - { - #region setup - - [Serializable] - public sealed class Whisper - { - public readonly string Path; - public readonly object Message; - - public Whisper(string path, object message) - { - Path = path; - Message = message; - } - } - - [Serializable] - public sealed class Talk - { - public readonly string Path; - public readonly object Message; - - public Talk(string path, object message) - { - Path = path; - Message = message; - } - } - - [Serializable] - public sealed class TalkToOthers - { - public readonly string Path; - public readonly object Message; - - public TalkToOthers(string path, object message) - { - Path = path; - Message = message; - } - } - - [Serializable] - public sealed class Shout - { - public readonly string Topic; - public readonly object Message; - - public Shout(string topic, object message) - { - Topic = topic; - Message = message; - } - } - - [Serializable] - public sealed class ShoutToGroup - { - public readonly string Topic; - public readonly object Message; - - public ShoutToGroup(string topic, object message) - { - Topic = topic; - Message = message; - } - } - - [Serializable] - public sealed class JoinGroup - { - public readonly string Topic; - public readonly string Group; - - public JoinGroup(string topic, string @group) - { - Topic = topic; - Group = @group; - } - } - - [Serializable] - public sealed class ExitGroup - { - public readonly string Topic; - public readonly string Group; - - public ExitGroup(string topic, string @group) - { - Topic = topic; - Group = @group; - } - } - - public class TestChatUser : ReceiveActor - { - public TestChatUser(IActorRef mediator, IActorRef testActorRef) - { - Receive(w => mediator.Tell(new Distributed.Send(w.Path, w.Message, true))); - Receive(t => mediator.Tell(new Distributed.SendToAll(t.Path, t.Message))); - Receive(t => mediator.Tell(new Distributed.SendToAll(t.Path, t.Message, true))); - Receive(s => mediator.Tell(new Distributed.Publish(s.Topic, s.Message))); - Receive(s => mediator.Tell(new Distributed.Publish(s.Topic, s.Message, true))); - Receive(j => mediator.Tell(new Distributed.Subscribe(j.Topic, Self, j.Group))); - Receive(j => mediator.Tell(new Distributed.Unsubscribe(j.Topic, Self, j.Group))); - ReceiveAny(msg => testActorRef.Tell(msg)); - } - } - - public class Publisher : ReceiveActor - { - public Publisher() - { - var mediator = DistributedPubSub.Get(Context.System).Mediator; - Receive(input => mediator.Tell(new Distributed.Publish("content", input.ToUpperInvariant()))); - } - } - - public class Subscriber : UntypedActor - { - private readonly IActorRef _mediator; - private readonly ILoggingAdapter _log; - - public Subscriber() - { - _log = Context.GetLogger(); - _mediator = DistributedPubSub.Get(Context.System).Mediator; - _mediator.Tell(new Distributed.Subscribe("content", Self)); - } - - protected override void OnReceive(object message) - { - var ack = message as Distributed.SubscribeAck; - if (ack != null && ack.Subscribe.Topic == "content" && ack.Subscribe.Ref.Equals(Self)) - { - Context.Become(Ready); - } - } - - private void Ready(object message) - { - if (message is string) _log.Info("Got {0}", message); - } - } - - private readonly RoleName _first; - private readonly RoleName _second; - private readonly RoleName _third; - - private readonly ConcurrentDictionary _chatUsers = new ConcurrentDictionary(); - - protected DistributedPubSubMediatorSpec() : this(new DistributedPubSubMediatorSpecConfig()) - { - } - - protected DistributedPubSubMediatorSpec(DistributedPubSubMediatorSpecConfig config) : base(config) - { - _first = config.First; - _second = config.Second; - _third = config.Third; - } - - public IActorRef Mediator { get { return DistributedPubSub.Get(Sys).Mediator; } } - - private IActorRef CreateChatUser(string name) - { - var a = Sys.ActorOf(Props.Create(() => new TestChatUser(Mediator, TestActor)), name); - _chatUsers.TryAdd(name, a); - return a; - } - - private IActorRef ChatUser(string name) - { - IActorRef a; - return _chatUsers.TryGetValue(name, out a) ? a : ActorRefs.Nobody; - } - - private void Join(RoleName from, RoleName to) - { - RunOn(() => - { - Cluster.Join(Node(to).Address); - CreateMediator(); - }, from); - EnterBarrier(from.Name + "-joined"); - } - - private void CreateMediator() - { - var m = DistributedPubSub.Get(Sys).Mediator; - } - - private void AwaitCount(int expected) - { - AwaitAssert(() => - { - Mediator.Tell(Count.Instance); - Assert.Equal(expected, ExpectMsg()); - }); - } - - #endregion - - //[MultiNodeFact(Skip = "TODO")] - public void DistributedPubSubMediator_should_startup_2_nodes_cluster() - { - Within(TimeSpan.FromSeconds(15), () => - { - Join(_first, _first); - Join(_second, _first); - EnterBarrier("after-1"); - }); - } - - //[MultiNodeFact(Skip = "TODO")] - public void DistributedPubSubMediator_should_keep_track_of_added_users() - { - DistributedPubSubMediator_should_startup_2_nodes_cluster(); - - Within(TimeSpan.FromSeconds(15), () => - { - RunOn(() => - { - var u1 = CreateChatUser("u1"); - Mediator.Tell(new Distributed.Put(u1)); - var u2 = CreateChatUser("u2"); - Mediator.Tell(new Distributed.Put(u2)); - - AwaitCount(2); - - // send to actor at the same node - u1.Tell(new Whisper("/user/u2", "hello")); - ExpectMsg("hello"); - Assert.Equal(u2, LastSender); - }, _first); - - RunOn(() => - { - var u3 = CreateChatUser("u3"); - Mediator.Tell(new Distributed.Put(u3)); - }, _second); - - RunOn(() => - { - AwaitCount(3); - }, _first, _second); - EnterBarrier("3-registered"); - - RunOn(() => - { - var u4 = CreateChatUser("u4"); - Mediator.Tell(new Distributed.Put(u4)); - }, _second); - - RunOn(() => - { - AwaitCount(4); - }, _first, _second); - EnterBarrier("4-registered"); - - RunOn(() => - { - // send to an actor on another node - ChatUser("u1").Tell(new Whisper("/user/u4", "hi there")); - }, _first); - - RunOn(() => - { - ExpectMsg("hi there"); - Assert.Equal("u4", LastSender.Path.Name); - }, _second); - EnterBarrier("after-2"); - }); - } - - //[MultiNodeFact(Skip = "TODO")] - public void DistributedPubSubMediator_should_replicate_users_to_new_node() - { - DistributedPubSubMediator_should_keep_track_of_added_users(); - - Within(TimeSpan.FromSeconds(20), () => - { - Join(_third, _first); - RunOn(() => - { - var u5 = CreateChatUser("u5"); - Mediator.Tell(new Distributed.Put(u5)); - }, _third); - - AwaitCount(5); - EnterBarrier("5-registered"); - - RunOn(() => - { - ChatUser("u5").Tell(new Whisper("/user/u4", "go")); - }, _third); - - RunOn(() => - { - ExpectMsg("go"); - Assert.Equal("u4", LastSender.Path.Name); - }, _second); - EnterBarrier("after-3"); - }); - } - - //[MultiNodeFact(Skip = "TODO")] - public void DistributedPubSubMediator_should_keep_track_of_removed_users() - { - DistributedPubSubMediator_should_replicate_users_to_new_node(); - - Within(TimeSpan.FromSeconds(15), () => - { - var u6 = CreateChatUser("u6"); - Mediator.Tell(new Distributed.Put(u6)); - }); - AwaitCount(6); - EnterBarrier("6-registered"); - - RunOn(() => - { - Mediator.Tell(new Distributed.Remove("/user/u6")); - }, _first); - AwaitCount(5); - EnterBarrier("after-4"); - } - - //[MultiNodeFact(Skip = "TODO")] - public void DistributedPubSubMediator_should_remove_terminated_users() - { - DistributedPubSubMediator_should_keep_track_of_removed_users(); - - Within(TimeSpan.FromSeconds(5), () => - { - RunOn(() => - { - ChatUser("u3").Tell(PoisonPill.Instance); - }, _second); - - AwaitCount(4); - EnterBarrier("after-5"); - }); - } - - //[MultiNodeFact(Skip = "TODO")] - public void DistributedPubSubMediator_should_publish() - { - DistributedPubSubMediator_should_remove_terminated_users(); - - Within(TimeSpan.FromSeconds(15), () => - { - RunOn(() => - { - var u7 = CreateChatUser("u7"); - Mediator.Tell(new Distributed.Put(u7)); - }, _first, _second); - AwaitCount(6); - EnterBarrier("7-registered"); - - RunOn(() => - { - ChatUser("u5").Tell(new Talk("/user/u7", "hi")); - }, _third); - - RunOn(() => - { - ExpectMsg("hi"); - Assert.Equal("u7", LastSender.Path.Name); - }, _first, _second); - - RunOn(() => - { - ExpectNoMsg(TimeSpan.FromSeconds(3)); - }, _third); - EnterBarrier("after-6"); - }); - } - - //[MultiNodeFact(Skip = "TODO")] - public void DistributedPubSubMediator_should_publish_to_topic() - { - DistributedPubSubMediator_should_publish(); - - Within(TimeSpan.FromSeconds(15), () => - { - RunOn(() => - { - var s8 = new Distributed.Subscribe("topic1", CreateChatUser("u8")); - Mediator.Tell(s8); - ExpectMsg(x => x.Subscribe.Equals(s8)); - var s9 = new Distributed.Subscribe("topic1", CreateChatUser("u9")); - Mediator.Tell(s9); - ExpectMsg(x => x.Subscribe.Equals(s9)); - }, _first); - - RunOn(() => - { - var s10 = new Distributed.Subscribe("topic1", CreateChatUser("u10")); - Mediator.Tell(s10); - ExpectMsg(x => x.Subscribe.Equals(s10)); - }, _second); - - // one topic on two nodes - AwaitCount(8); - EnterBarrier("topic1-registered"); - - RunOn(() => - { - ChatUser("u5").Tell(new Shout("topic1", "hello all")); - }, _third); - - RunOn(() => - { - var names = ReceiveWhile(x => "hello all".Equals(x) ? LastSender.Path.Name : null, msgs: 2); - Assert.True(names.All(x => x == "u8" || x == "u9")); - }, _first); - - RunOn(() => - { - ExpectMsg("hello all"); - Assert.Equal("u10", LastSender.Path.Name); - }, _second); - - RunOn(() => - { - ExpectNoMsg(TimeSpan.FromSeconds(2)); - }, _third); - EnterBarrier("after-7"); - }); - } - - //[MultiNodeFact(Skip = "TODO")] - public void DistributedPubSubMediator_should_demonstrate_usage() - { - DistributedPubSubMediator_should_publish_to_topic(); - - Within(TimeSpan.FromSeconds(15), () => - { - RunOn(() => - { - Sys.ActorOf(Props.Create(), "subscriber1"); - }, _first); - - RunOn(() => - { - Sys.ActorOf(Props.Create(), "subscriber2"); - Sys.ActorOf(Props.Create(), "subscriber3"); - }, _second); - - RunOn(() => - { - var publisher = Sys.ActorOf(Props.Create(), "publisher"); - AwaitCount(10); - // after a while the subscriptions are replicated - publisher.Tell("hello"); - }, _third); - EnterBarrier("after-8"); - }); - } - - //[MultiNodeFact(Skip = "TODO")] - public void DistributedPubSubMediator_should_SendAll_to_all_other_nodes() - { - DistributedPubSubMediator_should_demonstrate_usage(); - - Within(TimeSpan.FromSeconds(15), () => - { - RunOn(() => - { - var u11 = CreateChatUser("u11"); - Mediator.Tell(new Distributed.Put(u11)); - }, _first, _second, _third); - AwaitCount(13); - EnterBarrier("11-registered"); - - RunOn(() => - { - ChatUser("u5").Tell(new TalkToOthers("/user/u11", "hi")); - }, _third); - - RunOn(() => - { - ExpectMsg("hi"); - Assert.Equal("u1", LastSender.Path.Name); - }, _first, _second); - - RunOn(() => - { - ExpectNoMsg(TimeSpan.FromSeconds(2)); - }, _third); - EnterBarrier("after-11"); - }); - } - - //[MultiNodeFact(Skip = "TODO")] - public void DistributedPubSubMediator_should_send_one_message_to_each_group() - { - DistributedPubSubMediator_should_SendAll_to_all_other_nodes(); - - Within(TimeSpan.FromSeconds(20), () => - { - RunOn(() => - { - var u12 = CreateChatUser("u12"); - u12.Tell(new JoinGroup("topic2", "group1")); - ExpectMsg(s => s.Subscribe.Topic == "topic2" - && s.Subscribe.Group == "group1" - && s.Subscribe.Ref.Equals(u12)); - }, _first); - - RunOn(() => - { - var u12 = CreateChatUser("u12"); - u12.Tell(new JoinGroup("topic2", "group2")); - ExpectMsg(s => s.Subscribe.Topic == "topic2" - && s.Subscribe.Group == "group2" - && s.Subscribe.Ref.Equals(u12)); - - var u13 = CreateChatUser("u13"); - u12.Tell(new JoinGroup("topic2", "group2")); - ExpectMsg(s => s.Subscribe.Topic == "topic2" - && s.Subscribe.Group == "group2" - && s.Subscribe.Ref.Equals(u13)); - }, _second); - - AwaitCount(17); - EnterBarrier("12-registered"); - - RunOn(() => - { - ChatUser("u12").Tell(new ShoutToGroup("topic12", "hi")); - }, _first); - - RunOn(() => - { - ExpectMsg("hi"); - ExpectNoMsg(TimeSpan.FromSeconds(2)); // each group receive only one message - }, _first, _second); - EnterBarrier("12-published"); - - RunOn(() => - { - var u12 = ChatUser("u12"); - u12.Tell(new ExitGroup("topic2", "group1")); - ExpectMsg(s => s.Unsubscribe.Topic == "topic2" - && s.Unsubscribe.Group == "group1" - && s.Unsubscribe.Ref.Equals(u12)); - }, _first); - - RunOn(() => - { - var u12 = ChatUser("u12"); - u12.Tell(new ExitGroup("topic2", "group2")); - ExpectMsg(s => s.Unsubscribe.Topic == "topic2" - && s.Unsubscribe.Group == "group2" - && s.Unsubscribe.Ref.Equals(u12)); - var u13 = ChatUser("u13"); - u12.Tell(new ExitGroup("topic2", "group2")); - ExpectMsg(s => s.Unsubscribe.Topic == "topic2" - && s.Unsubscribe.Group == "group2" - && s.Unsubscribe.Ref.Equals(u13)); - }, _second); - EnterBarrier("after-12"); - }); - } - - //[MultiNodeFact(Skip = "TODO")] - public void DistributedPubSubMediator_should_transfer_delta_correctly() - { - DistributedPubSubMediator_should_send_one_message_to_each_group(); - - var firstAddress = Node(_first).Address; - var secondAddress = Node(_second).Address; - var thirdAddress = Node(_third).Address; - - RunOn(() => - { - Mediator.Tell(new Tools.PublishSubscribe.Internal.Status(new Dictionary())); - var deltaBuckets = ExpectMsg().Buckets; - Assert.Equal(3, deltaBuckets.Count()); - Assert.Equal(9, deltaBuckets.First(x => x.Owner == firstAddress).Content.Count); - Assert.Equal(8, deltaBuckets.First(x => x.Owner == secondAddress).Content.Count); - Assert.Equal(2, deltaBuckets.First(x => x.Owner == thirdAddress).Content.Count); - }, _first); - EnterBarrier("verified-initial-delta"); - - // this test is configured with max-delta-elements = 500 - var many = 1010; - RunOn(() => - { - for (int i = 1; i <= many; i++) - { - Mediator.Tell(new Distributed.Put(CreateChatUser("u" + (i + 1000)))); - } - - Mediator.Tell(new Tools.PublishSubscribe.Internal.Status(new Dictionary())); - var deltaBuckets1 = ExpectMsg().Buckets; - Assert.Equal(500, deltaBuckets1.Sum(x => x.Content.Count)); - - Mediator.Tell(new Tools.PublishSubscribe.Internal.Status(deltaBuckets1.ToDictionary(b => b.Owner, b => b.Version))); - var deltaBuckets2 = ExpectMsg().Buckets; - Assert.Equal(500, deltaBuckets2.Sum(x => x.Content.Count)); - - Mediator.Tell(new Tools.PublishSubscribe.Internal.Status(deltaBuckets2.ToDictionary(b => b.Owner, b => b.Version))); - var deltaBuckets3 = ExpectMsg().Buckets; - Assert.Equal(9 + 8 + 2 + many - 500 - 500, deltaBuckets3.Sum(x => x.Content.Count)); - - }, _first); - EnterBarrier("verified-delta-with-many"); - - Within(TimeSpan.FromSeconds(10), () => - { - AwaitCount(17 + many); - }); - EnterBarrier("after-13"); - } - - //[MultiNodeFact(Skip = "TODO")] - public void DistributedPubSubMediator_should_remove_entries_when_node_is_removed() - { - DistributedPubSubMediator_should_transfer_delta_correctly(); - - Within(TimeSpan.FromSeconds(30), () => - { - Mediator.Tell(Count.Instance); - var countBefore = ExpectMsg(); - - RunOn(() => - { - TestConductor.Exit(_third, 0).Wait(); - }, _first); - EnterBarrier("third-shutdown"); - - // third had 2 entries u5 and u11, and those should be removed everywhere - RunOn(() => - { - AwaitCount(countBefore - 2); - }, _first, _second); - EnterBarrier("after-14"); - }); - } - - //[MultiNodeFact(Skip = "TODO")] - public void DistributedPubSubMediator_should_receive_proper_UnsubscribeAck_message() - { - DistributedPubSubMediator_should_remove_entries_when_node_is_removed(); - - Within(TimeSpan.FromSeconds(15), () => - { - RunOn(() => - { - var user = CreateChatUser("u111"); - var topic = "sample-topic-14"; - var s1 = new Distributed.Subscribe(topic, user); - Mediator.Tell(s1); - ExpectMsg(x => x.Subscribe.Equals(s1)); - var uns = new Distributed.Unsubscribe(topic, user); - Mediator.Tell(uns); - ExpectMsg(x => x.Unsubscribe.Equals(uns)); - }, _first); - EnterBarrier("after-15"); - }); - } - - [MultiNodeFact(Skip = "TODO")] - public void DistributedPubSubMediator_should_get_topics_after_simple_publish() - { - DistributedPubSubMediator_should_receive_proper_UnsubscribeAck_message(); - - Within(TimeSpan.FromSeconds(15), () => - { - RunOn(() => - { - var s1 = new Distributed.Subscribe("topic_a1", CreateChatUser("u14")); - Mediator.Tell(s1); - ExpectMsg(x => x.Subscribe.Equals(s1)); - - var s2 = new Distributed.Subscribe("topic_a1", CreateChatUser("u15")); - Mediator.Tell(s2); - ExpectMsg(x => x.Subscribe.Equals(s2)); - - var s3 = new Distributed.Subscribe("topic_a2", CreateChatUser("u16")); - Mediator.Tell(s3); - ExpectMsg(x => x.Subscribe.Equals(s3)); - - }, _first); - - RunOn(() => - { - var s3 = new Distributed.Subscribe("topic_a1", CreateChatUser("u17")); - Mediator.Tell(s3); - ExpectMsg(x => x.Subscribe.Equals(s3)); - - }, _second); - EnterBarrier("topics-registered"); - - RunOn(() => - { - Mediator.Tell(Distributed.GetTopics.Instance); - ExpectMsg( - x => x.Topics.Contains("topic_a1") && x.Topics.Contains("topic_a2")); - }, _first); - - RunOn(() => - { - // topics will eventually be replicated - AwaitAssert(() => - { - Mediator.Tell(Distributed.GetTopics.Instance); - var topics = ExpectMsg().Topics; - - Assert.True(topics.Contains("topic_a1")); - Assert.True(topics.Contains("topic_a2")); - }); - }, _second); - EnterBarrier("after-get-topics"); - }); - } - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Tools.Tests/Singleton/ClusterSingletonManagerChaosSpec.cs b/src/contrib/cluster/Akka.Cluster.Tools.Tests/Singleton/ClusterSingletonManagerChaosSpec.cs deleted file mode 100644 index 0af5dd3bb19..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools.Tests/Singleton/ClusterSingletonManagerChaosSpec.cs +++ /dev/null @@ -1,241 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using System.Collections.Generic; -using System.Linq; -using Akka.Actor; -using Akka.Cluster.Tests.MultiNode; -using Akka.Cluster.Tools.Singleton; -using Akka.Configuration; -using Akka.Remote.TestKit; -using Akka.TestKit; -using Akka.TestKit.Internal; -using Akka.TestKit.TestEvent; -using Xunit; - -namespace Akka.Cluster.Tools.Tests.Singleton -{ - public sealed class EchoStarted - { - public static readonly EchoStarted Instance = new EchoStarted(); - - private EchoStarted() { } - } - - public class Echo : ReceiveActor - { - public Echo(IActorRef testActor) - { - testActor.Tell(EchoStarted.Instance); - ReceiveAny(_ => Sender.Tell(Self)); - } - } - public class ClusterSingletonManagerChaosConfig : MultiNodeConfig - { - public readonly RoleName Controller; - public readonly RoleName First; - public readonly RoleName Second; - public readonly RoleName Third; - public readonly RoleName Fourth; - public readonly RoleName Fifth; - public readonly RoleName Sixth; - - public ClusterSingletonManagerChaosConfig() - { - Controller = Role("controller"); - First = Role("first"); - Second = Role("second"); - Third = Role("third"); - Fourth = Role("fourth"); - Fifth = Role("fifth"); - Sixth = Role("sixth"); - - CommonConfig = ConfigurationFactory.ParseString(@" - akka.loglevel = DEBUG - akka.actor.provider = ""Akka.Cluster.ClusterActorRefProvider, Akka.Cluster"" - akka.remote.log-remote-lifecycle-events = off - akka.cluster.auto-down-unreachable-after = 0s - ") - .WithFallback(ClusterSingletonManager.DefaultConfig()) - .WithFallback(MultiNodeClusterSpec.ClusterConfig()); - } - } - - public class ClusterSingletonManagerChaosNode1 : ClusterSingletonManagerChaosConfig { } - public class ClusterSingletonManagerChaosNode2 : ClusterSingletonManagerChaosConfig { } - public class ClusterSingletonManagerChaosNode3 : ClusterSingletonManagerChaosConfig { } - public class ClusterSingletonManagerChaosNode4 : ClusterSingletonManagerChaosConfig { } - public class ClusterSingletonManagerChaosNode5 : ClusterSingletonManagerChaosConfig { } - public class ClusterSingletonManagerChaosNode6 : ClusterSingletonManagerChaosConfig { } - public class ClusterSingletonManagerChaosNode7 : ClusterSingletonManagerChaosConfig { } - - public abstract class ClusterSingletonManagerChaosSpec : MultiNodeClusterSpec - { - protected ClusterSingletonManagerChaosSpec() : base(new ClusterSingletonManagerChaosConfig()) - { - } - - protected override int InitialParticipantsValueFactory { get { return Roles.Count; } } - - //[MultiNodeFact(Skip = "TODO")] - public void ClusterSingletonManager_in_chaotic_cluster_should_startup_6_node_cluster() - { - Within(TimeSpan.FromMinutes(1), () => - { - var memberProbe = CreateTestProbe(); - Cluster.Get(Sys).Subscribe(memberProbe.Ref, new[] { typeof(ClusterEvent.MemberUp) }); - memberProbe.ExpectMsg(); - - var first = GetRole("first"); - var second = GetRole("second"); - var third = GetRole("third"); - var fourth = GetRole("fourth"); - var fifth = GetRole("fifth"); - var sixth = GetRole("sixth"); - - AwaitClusterUp(first, second, third, fourth, fifth, sixth); - - Join(first, first); - AwaitMemberUp(memberProbe, first); - RunOn(() => - { - ExpectMsg(); - }, first); - EnterBarrier("first-started"); - - Join(second, first); - AwaitMemberUp(memberProbe, second, first); - - Join(third, first); - AwaitMemberUp(memberProbe, third, second, first); - - Join(fourth, first); - AwaitMemberUp(memberProbe, fourth, third, second, first); - - Join(fifth, first); - AwaitMemberUp(memberProbe, fifth, fourth, third, second, first); - - Join(sixth, first); - AwaitMemberUp(memberProbe, sixth, fifth, fourth, third, second, first); - - RunOn(() => - { - Echo(first).Tell("hello"); - Assert.Equal(ExpectMsg(TimeSpan.FromSeconds(3)).Path.Address, Node(first).Address); - }, GetRole("controller")); - - EnterBarrier("first-verified"); - }); - } - - [MultiNodeFact] - public void ClusterSingletonManager_in_chaotic_cluster_should_take_over_when_tree_oldest_nodes_crash_in_6_nodes_cluster() - { - ClusterSingletonManager_in_chaotic_cluster_should_startup_6_node_cluster(); - - Within(TimeSpan.FromSeconds(90), () => - { - // mute logging of deadLetters during shutdown of systems - if (!Log.IsDebugEnabled) - Sys.EventStream.Publish(new Mute(new WarningFilter())); - EnterBarrier("logs-muted"); - - var first = GetRole("first"); - var second = GetRole("second"); - var third = GetRole("third"); - var fourth = GetRole("fourth"); - - Crash(first, second, third); - EnterBarrier("after-crash"); - RunOn(() => - { - ExpectMsg(); - }, fourth); - EnterBarrier("fourth-active"); - - RunOn(() => - { - Echo(fourth).Tell("hello"); - var address = ExpectMsg(TimeSpan.FromSeconds(3)).Path.Address; - Assert.Equal(address, Node(fourth).Address); - }, GetRole("controller")); - EnterBarrier("fourth-verified"); - }); - } - - private void Join(RoleName from, RoleName to) - { - RunOn(() => - { - Cluster.Get(Sys).Join(Node(to).Address); - CreateSingleton(); - }, from); - } - - private RoleName GetRole(string name) - { - return Roles.First(roleName => roleName.Name == name); - } - - private IActorRef CreateSingleton() - { - /** - system.actorOf(ClusterSingletonManager.props( - singletonProps = Props(classOf[Echo], testActor), - terminationMessage = PoisonPill, - settings = ClusterSingletonManagerSettings(system)), - name = "echo") - */ - return Sys.ActorOf(ClusterSingletonManager.Props( - singletonProps: Props.Create(() => new Echo(TestActor)), - terminationMessage: PoisonPill.Instance, - settings: ClusterSingletonManagerSettings.Create(Sys)), - name: "echo"); - } - - private void Crash(params RoleName[] roles) - { - RunOn(() => - { - foreach (var roleName in roles) - { - Log.Info("Shutdown [{0}]", roleName); - TestConductor.Exit(roleName, 0).Wait(TimeSpan.FromSeconds(10)); - } - }, GetRole("controller") /*controller*/); - } - - private ActorSelection Echo(RoleName oldest) - { - return Sys.ActorSelection(Node(oldest) / "user" / "echo" / "singleton"); - } - - private void AwaitMemberUp(TestProbe memberProbe, params RoleName[] nodes) - { - RunOn(() => - { - var address = memberProbe.ExpectMsg(TimeSpan.FromSeconds(15)).Member.Address; - var headAddress = Node(nodes[0]).Address; - Assert.Equal(address, headAddress); - }, nodes.Where(n => n != nodes[0]).ToArray()); - - RunOn(() => - { - var addresses = new HashSet
(memberProbe.ReceiveN(nodes.Length, TimeSpan.FromSeconds(15)) - .Where(x => x is ClusterEvent.MemberUp) - .Select(x => (x as ClusterEvent.MemberUp).Member.Address)); - - var rolenodes = nodes.Select(n => Node(n).Address).ToList(); - Assert.Equal(addresses, rolenodes); - - EnterBarrier(nodes[0].Name + "-up"); - - }, nodes[0]); - } - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Tools.Tests/Singleton/ClusterSingletonManagerLeaveSpec.cs b/src/contrib/cluster/Akka.Cluster.Tools.Tests/Singleton/ClusterSingletonManagerLeaveSpec.cs deleted file mode 100644 index 5d445cd28ca..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools.Tests/Singleton/ClusterSingletonManagerLeaveSpec.cs +++ /dev/null @@ -1,158 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using Akka.Actor; -using Akka.Cluster.Tools.Singleton; -using Akka.Configuration; -using Akka.Remote.TestKit; -using Xunit; -using System.Linq; -using Akka.Cluster.Tests.MultiNode; - -namespace Akka.Cluster.Tools.Tests.Singleton -{ - public class ClusterSingletonManagerLeaveSpecConfig : MultiNodeConfig - { - public readonly RoleName First; - public readonly RoleName Second; - public readonly RoleName Third; - - public ClusterSingletonManagerLeaveSpecConfig() - { - First = Role("first"); - Second = Role("second"); - Third = Role("third"); - - CommonConfig = ConfigurationFactory.ParseString(@" - akka.loglevel = DEBUG - akka.actor.provider = ""Akka.Cluster.ClusterActorRefProvider, Akka.Cluster"" - akka.remote.log-remote-lifecycle-events = off - akka.cluster.auto-down-unreachable-after = off - ") - .WithFallback(ClusterSingletonManager.DefaultConfig()) - .WithFallback(MultiNodeClusterSpec.ClusterConfig()); - } - } - - public class ClusterSingletonManagerLeaveNode1 : ClusterSingletonManagerLeaveSpec { } - public class ClusterSingletonManagerLeaveNode2 : ClusterSingletonManagerLeaveSpec { } - public class ClusterSingletonManagerLeaveNode3 : ClusterSingletonManagerLeaveSpec { } - - public abstract class ClusterSingletonManagerLeaveSpec : MultiNodeClusterSpec - { - public sealed class EchoStarted - { - public static readonly EchoStarted Instance = new EchoStarted(); - - private EchoStarted() - { - } - } - - public class Echo : ReceiveActor - { - private readonly IActorRef _testActorRef; - - public Echo(IActorRef testActorRef) - { - _testActorRef = testActorRef; - ReceiveAny(x => Sender.Tell(Self)); - } - - protected override void PostStop() - { - base.PostStop(); - _testActorRef.Tell("stopped"); - } - } - - private readonly RoleName _first; - private readonly RoleName _second; - private readonly RoleName _third; - - private readonly Lazy _echoProxy; - - protected ClusterSingletonManagerLeaveSpec() : this(new ClusterSingletonManagerLeaveSpecConfig()) - { - } - - protected ClusterSingletonManagerLeaveSpec(ClusterSingletonManagerLeaveSpecConfig config) : base(config) - { - _first = config.First; - _second = config.Second; - _third = config.Third; - - _echoProxy = new Lazy(() => Sys.ActorOf(ClusterSingletonProxy.Props( - singletonManagerPath: "/user/echo", - settings: ClusterSingletonProxySettings.Create(Sys)), - "echoProxy")); - } - - private void Join(RoleName from, RoleName to) - { - RunOn(() => - { - Cluster.Join(Node(to).Address); - CreateSingleton(); - }, from); - } - - private IActorRef CreateSingleton() - { - return Sys.ActorOf(ClusterSingletonManager.Props( - singletonProps: Props.Create(() => new Echo(TestActor)), - terminationMessage: PoisonPill.Instance, - settings: ClusterSingletonManagerSettings.Create(Sys)), - "echo"); - } - - [MultiNodeFact] - public void Leaving_ClusterSingletonManager_should_handover_to_new_instance() - { - Join(_first, _first); - RunOn(() => - { - - }, _first); - EnterBarrier("first-active"); - - Join(_second, _first); - Join(_third, _first); - Within(TimeSpan.FromSeconds(10), () => - { - AwaitAssert(() => Assert.Equal(3, Cluster.ReadView.State.Members.Count(m => m.Status == MemberStatus.Up))); - }); - EnterBarrier("all-up"); - - RunOn(() => - { - Cluster.Leave(Node(_first).Address); - }, _second); - RunOn(() => - { - ExpectMsg("stopped", TimeSpan.FromSeconds(10)); - }, _first); - EnterBarrier("first-stopped"); - - RunOn(() => - { - var p = CreateTestProbe(); - var firstAddress = Node(_first).Address; - p.Within(TimeSpan.FromSeconds(10), () => - { - p.AwaitAssert(() => - { - _echoProxy.Value.Tell("hello2", p.Ref); - Assert.NotEqual(firstAddress, p.ExpectMsg(TimeSpan.FromSeconds(1)).Path.Address); - }); - }); - }, _second, _third); - EnterBarrier("handover-done"); - } - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Tools.Tests/Singleton/ClusterSingletonManagerSpec.cs b/src/contrib/cluster/Akka.Cluster.Tools.Tests/Singleton/ClusterSingletonManagerSpec.cs deleted file mode 100644 index 43e3f6ebf0d..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools.Tests/Singleton/ClusterSingletonManagerSpec.cs +++ /dev/null @@ -1,631 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using System.Linq; -using Akka.Actor; -using Akka.Cluster.Tests.MultiNode; -using Akka.Cluster.Tools.Singleton; -using Akka.Configuration; -using Akka.Event; -using Akka.Remote.TestKit; -using Akka.TestKit; -using Akka.TestKit.Internal.StringMatcher; -using Akka.TestKit.TestEvent; -using Xunit; - -namespace Akka.Cluster.Tools.Tests.Singleton -{ - public class ClusterSingletonManagerSpecConfig : MultiNodeConfig - { - public readonly RoleName Controller; - public readonly RoleName Observer; - public readonly RoleName First; - public readonly RoleName Second; - public readonly RoleName Third; - public readonly RoleName Fourth; - public readonly RoleName Fifth; - public readonly RoleName Sixth; - - public ClusterSingletonManagerSpecConfig() - { - Controller = Role("controller"); - Observer = Role("observer"); - First = Role("first"); - Second = Role("second"); - Third = Role("third"); - Fourth = Role("fourth"); - Fifth = Role("fifth"); - Sixth = Role("sixth"); - - CommonConfig = ConfigurationFactory.ParseString(@" - akka.loglevel = DEBUG - akka.actor.provider = ""Akka.Cluster.ClusterActorRefProvider, Akka.Cluster"" - akka.remote.log-remote-lifecycle-events = off - akka.cluster.auto-down-unreachable-after = 0s - ") - .WithFallback(ClusterSingletonManager.DefaultConfig()) - .WithFallback(MultiNodeClusterSpec.ClusterConfig()); - - NodeConfig(new[] { First, Second, Third, Fourth, Fifth, Sixth }, new[] { ConfigurationFactory.ParseString(@"akka.cluster.roles =[worker]") }); - } - } - - public class ClusterSingletonManagerNode1 : ClusterSingletonManagerSpec { } - public class ClusterSingletonManagerNode2 : ClusterSingletonManagerSpec { } - public class ClusterSingletonManagerNode3 : ClusterSingletonManagerSpec { } - public class ClusterSingletonManagerNode4 : ClusterSingletonManagerSpec { } - public class ClusterSingletonManagerNode5 : ClusterSingletonManagerSpec { } - public class ClusterSingletonManagerNode6 : ClusterSingletonManagerSpec { } - public class ClusterSingletonManagerNode7 : ClusterSingletonManagerSpec { } - public class ClusterSingletonManagerNode8 : ClusterSingletonManagerSpec { } - - /** - * This channel is extremely strict with regards to - * registration and unregistration of consumer to - * be able to detect misbehaviour (e.g. two active - * singleton instances). - */ - internal class PointToPointChannel : UntypedActor - { - #region messages - - public sealed class UnregisterConsumer - { - public static readonly UnregisterConsumer Instance = new UnregisterConsumer(); - - private UnregisterConsumer() - { - } - } - - public sealed class RegisterConsumer - { - public static readonly RegisterConsumer Instance = new RegisterConsumer(); - - private RegisterConsumer() - { - } - } - - public sealed class RegistrationOk - { - public static readonly RegistrationOk Instance = new RegistrationOk(); - - private RegistrationOk() - { - } - } - - public sealed class UnexpectedRegistration - { - public static readonly UnexpectedRegistration Instance = new UnexpectedRegistration(); - - private UnexpectedRegistration() - { - } - } - - public sealed class UnregistrationOk - { - public static readonly UnregistrationOk Instance = new UnregistrationOk(); - - private UnregistrationOk() - { - } - } - - public sealed class UnexpectedUnregistration - { - public static readonly UnexpectedUnregistration Instance = new UnexpectedUnregistration(); - - private UnexpectedUnregistration() - { - } - } - - public sealed class Reset - { - public static readonly Reset Instance = new Reset(); - - private Reset() - { - } - } - - public sealed class ResetOk - { - public static readonly ResetOk Instance = new ResetOk(); - - private ResetOk() - { - } - } - - #endregion - - private readonly ILoggingAdapter _log; - public PointToPointChannel() - { - _log = Context.GetLogger(); - - Become(Idle); - } - - private void Idle(object message) - { - message.Match() - .With(_ => - { - _log.Info("Register consumer [{0}]", Sender.Path); - Sender.Tell(RegistrationOk.Instance); - Context.Become(Active(Sender)); - }) - .With(_ => - { - _log.Info("Unexpected unregistration: [{0}]", Sender.Path); - Sender.Tell(UnexpectedRegistration.Instance); - Context.Stop(Self); - }) - .With(_ => Sender.Tell(ResetOk.Instance)); - } - - private UntypedReceive Active(IActorRef consumer) - { - return message => - { - message.Match() - .With(_ => - { - if (Sender.Equals(consumer)) - { - _log.Info("Unregistration ok: [{0}]", Sender.Path); - Sender.Tell(UnregistrationOk.Instance); - Context.Become(Idle); - } - else - { - _log.Info("Unexpected unregistration: [{0}], expected: [{1}]", Sender.Path, consumer.Path); - Sender.Tell(UnexpectedUnregistration.Instance); - Context.Stop(Self); - } - }) - .With(_ => - { - _log.Info("Unexpected registration: [{0}], active consumer: [{1}]", Sender.Path, consumer.Path); - Sender.Tell(UnexpectedRegistration.Instance); - Context.Stop(Self); - }) - .With(_ => - { - Context.Become(Idle); - Sender.Tell(ResetOk.Instance); - }) - .Default(m => Sender.Tell(m)); - }; - } - - protected override void OnReceive(object message) { } - } - - internal class Consumer : ReceiveActor - { - private readonly IActorRef _queue; - - #region messages - - public sealed class Ping - { - public static readonly Ping Instance = new Ping(); - - private Ping() - { - } - } - - public sealed class Pong - { - public static readonly Pong Instance = new Pong(); - - private Pong() - { - } - } - - public sealed class End - { - public static readonly End Instance = new End(); - - private End() - { - } - } - - public sealed class GetCurrent - { - public static readonly GetCurrent Instance = new GetCurrent(); - - private GetCurrent() - { - } - } - - #endregion - - private int current = 0; - - public Consumer(IActorRef queue, IActorRef delegateTo) - { - _queue = queue; - Receive(n => n <= current, n => Context.Stop(Self)); - Receive(n => - { - current = n; - delegateTo.Tell(n); - }); - Receive(x => delegateTo.Tell(x)); - Receive(x => delegateTo.Tell(x)); - Receive(_ => Sender.Tell(current)); - Receive(_ => queue.Tell(PointToPointChannel.UnregisterConsumer.Instance)); - Receive(_ => Context.Stop(Self)); - Receive(_ => Sender.Tell(Pong.Instance)); - } - - protected override void PreStart() - { - _queue.Tell(PointToPointChannel.RegisterConsumer.Instance); - } - } - - public abstract class ClusterSingletonManagerSpec : MultiNodeClusterSpec - { - #region Setup - - private readonly TestProbe _identifyProbe; - private readonly ActorPath _controllerRootActorPath; - private int _msg = 0; - - private readonly RoleName _controller; - private readonly RoleName _observer; - private readonly RoleName _first; - private readonly RoleName _second; - private readonly RoleName _third; - private readonly RoleName _fourth; - private readonly RoleName _fifth; - private readonly RoleName _sixth; - - public int Msg { get { return (_msg++); } } - - public IActorRef Queue - { - get - { - // this is used from inside actor construction, i.e. other thread, and must therefore not call `node(controller` - Sys.ActorSelection(_controllerRootActorPath / "user" / "queue").Tell(new Identify("queue"), _identifyProbe.Ref); - return _identifyProbe.ExpectMsg().Subject; - } - } - - protected ClusterSingletonManagerSpec() : base(new ClusterSingletonManagerSpecConfig()) - { - } - - protected ClusterSingletonManagerSpec(ClusterSingletonManagerSpecConfig config) : base(config) - { - _controller = config.Controller; - _observer = config.Observer; - _first = config.First; - _second = config.Second; - _third = config.Third; - _fourth = config.Fourth; - _fifth = config.Fifth; - _sixth = config.Sixth; - - _identifyProbe = CreateTestProbe(); - _controllerRootActorPath = Node(config.Controller); - } - - private void Join(RoleName from, RoleName to) - { - RunOn(() => - { - Cluster.Join(Node(to).Address); - if (Cluster.SelfRoles.Contains("worker")) - { - CreateSingleton(); - CreateSingletonProxy(); - } - }, from); - } - - private void AwaitMemberUp(TestProbe memberProbe, params RoleName[] nodes) - { - RunOn(() => - { - Assert.Equal(Node(nodes[0]).Address, memberProbe.ExpectMsg(TimeSpan.FromSeconds(15)).Member.Address); - }, nodes.Skip(1).ToArray()); - RunOn(() => - { - var membersUp = memberProbe.ReceiveN(nodes.Length, TimeSpan.FromSeconds(15)) - .Where(x => x is ClusterEvent.MemberUp) - .Select(x => (x as ClusterEvent.MemberUp).Member.Address) - .Distinct() - .ToArray(); - - Assert.True(nodes.Select(x => Node(x).Address).ToArray().All(x => membersUp.Contains(x))); - }, nodes[0]); - EnterBarrier(nodes[0].Name + "-up"); - } - - private void CreateSingleton() - { - Sys.ActorOf(ClusterSingletonManager.Props( - singletonProps: Props.Create(() => new Consumer(Queue, TestActor)), - terminationMessage: Akka.Cluster.Tools.Tests.Singleton.Consumer.End.Instance, - settings: ClusterSingletonManagerSettings.Create(Sys).WithRole("worker")), - "consumer"); - } - - private void CreateSingletonProxy() - { - Sys.ActorOf(ClusterSingletonProxy.Props( - singletonManagerPath: "/user/consumer", - settings: ClusterSingletonProxySettings.Create(Sys).WithRole("worker")), - "consumerProxy"); - } - - private void VerifyProxyMsg(RoleName oldest, RoleName proxyNode, int msg) - { - EnterBarrier("before-" + msg + "-proxy-verified"); - - // send message to the proxy - RunOn(() => - { - // make sure that the proxy has received membership changes - // and points to the current singleton - var p = CreateTestProbe(); - Within(TimeSpan.FromSeconds(5), () => - { - AwaitAssert(() => - { - Sys.ActorSelection("/user/consumerProxy").Tell(Akka.Cluster.Tools.Tests.Singleton.Consumer.Ping.Instance, p.Ref); - p.ExpectMsg(TimeSpan.FromSeconds(1)); - }); - }); - - // send a real message - Sys.ActorSelection("/user/consumerProxy").Tell(msg); - }, proxyNode); - - // expect a message on the oldest node - RunOn(() => - { - ExpectMsg(msg, TimeSpan.FromSeconds(5)); - }, oldest); - - EnterBarrier("after-" + msg + "-proxy-verified"); - } - - private ActorSelection GetConsumer(RoleName oldest) - { - return Sys.ActorSelection(new RootActorPath(Node(oldest).Address) / "user" / "consumer" / "singleton"); - } - - private void VerifyRegistration(RoleName oldest) - { - EnterBarrier("before-" + oldest.Name + "-registration-verified"); - - RunOn(() => - { - ExpectMsg(); - GetConsumer(oldest).Tell(Consumer.GetCurrent.Instance); - ExpectMsg(0); - }, oldest); - - EnterBarrier("after-" + oldest.Name + "-registration-verified"); - } - - private void VerifyMsg(RoleName oldest, int msg) - { - EnterBarrier("before-" + msg + "-verified"); - - RunOn(() => - { - Queue.Tell(msg); - // make sure it's not terminated, which would be wrong - ExpectNoMsg(TimeSpan.FromSeconds(1)); - }, _controller); - - RunOn(() => - { - ExpectMsg(msg, TimeSpan.FromSeconds(1)); - }, oldest); - - RunOn(() => - { - ExpectNoMsg(TimeSpan.FromSeconds(1)); - }, Roles.Where(r => r != oldest && r != _controller && r != _observer).ToArray()); - - EnterBarrier("after-" + msg + "-verified"); - } - - private void Crash(params RoleName[] roles) - { - RunOn(() => - { - Queue.Tell(PointToPointChannel.Reset.Instance); - ExpectMsg(); - foreach (var role in roles) - { - Log.Info("Shutdown [{0}]", Node(role).Address); - TestConductor.Exit(role, 0).Wait(); - } - }, _controller); - } - - #endregion - - //[MultiNodeFact()] - public void ClusterSingletonManager_should_startup_6_node_cluster() - { - AwaitClusterUp(_controller, _observer, _first, _second, _third, _fourth, _fifth, _sixth); - - Within(TimeSpan.FromSeconds(60), () => - { - var memberProbe = CreateTestProbe(); - Cluster.Subscribe(memberProbe.Ref, new[] { typeof(ClusterEvent.MemberUp) }); - memberProbe.ExpectMsg(); - - RunOn(() => - { - // watch that it is not terminated, which would indicate misbehaviour - Watch(Sys.ActorOf(Props.Create(), "queue")); - }, _controller); - EnterBarrier("queue-started"); - - Join(_first, _first); - AwaitMemberUp(memberProbe, _first); - VerifyRegistration(_first); - VerifyMsg(_first, Msg); - - // join the observer node as well, which should not influence since it doesn't have the "worker" role - Join(_observer, _first); - AwaitMemberUp(memberProbe, _observer, _first); - VerifyProxyMsg(_first, _first, Msg); - - Join(_second, _first); - AwaitMemberUp(memberProbe, _second, _observer, _first); - VerifyMsg(_first, Msg); - VerifyProxyMsg(_first, _second, Msg); - - Join(_third, _first); - AwaitMemberUp(memberProbe, _third, _second, _observer, _first); - VerifyMsg(_first, Msg); - VerifyProxyMsg(_first, _third, Msg); - - Join(_fourth, _first); - AwaitMemberUp(memberProbe, _fourth, _third, _second, _observer, _first); - VerifyMsg(_first, Msg); - VerifyProxyMsg(_first, _fourth, Msg); - - Join(_fifth, _first); - AwaitMemberUp(memberProbe, _fifth, _fourth, _third, _second, _observer, _first); - VerifyMsg(_first, Msg); - VerifyProxyMsg(_first, _fifth, Msg); - - Join(_sixth, _first); - AwaitMemberUp(memberProbe, _sixth, _fifth, _fourth, _third, _second, _observer, _first); - VerifyMsg(_first, Msg); - VerifyProxyMsg(_first, _sixth, Msg); - }); - } - - //[MultiNodeFact(Skip = "TODO")] - public void ClusterSingletonManager_should_let_the_proxy_messages_to_the_singleton_in_a_6_node_cluster() - { - ClusterSingletonManager_should_startup_6_node_cluster(); - Within(TimeSpan.FromSeconds(60), () => - { - VerifyProxyMsg(_first, _first, Msg); - VerifyProxyMsg(_first, _second, Msg); - VerifyProxyMsg(_first, _third, Msg); - VerifyProxyMsg(_first, _fourth, Msg); - VerifyProxyMsg(_first, _fifth, Msg); - VerifyProxyMsg(_first, _sixth, Msg); - }); - } - - //[MultiNodeFact(Skip = "TODO")] - public void ClusterSingletonManager_should_handover_when_oldest_leaves_in_6_node_cluster() - { - ClusterSingletonManager_should_let_the_proxy_messages_to_the_singleton_in_a_6_node_cluster(); - - Within(TimeSpan.FromSeconds(30), () => - { - var leaveNode = _first; - var newOldestNode = _second; - - RunOn(() => - { - Cluster.Leave(Node(leaveNode).Address); - }, leaveNode); - - VerifyRegistration(_second); - VerifyMsg(_second, Msg); - VerifyProxyMsg(_second, _second, Msg); - VerifyProxyMsg(_second, _third, Msg); - VerifyProxyMsg(_second, _fourth, Msg); - VerifyProxyMsg(_second, _fifth, Msg); - VerifyProxyMsg(_second, _sixth, Msg); - - RunOn(() => - { - Sys.ActorSelection("/user/consumer").Tell(new Identify("singleton"), _identifyProbe.Ref); - _identifyProbe.ExpectMsg(i => - { - if (i.MessageId.Equals("singleton") && i.Subject != null) - { - Watch(i.Subject); - ExpectTerminated(i.Subject); - } - }); - }, leaveNode); - EnterBarrier("after-leave"); - }); - } - - //[MultiNodeFact(Skip = "TODO")] - public void ClusterSingletonManager_should_takeover_when_oldest_crashes_in_5_node_cluster() - { - ClusterSingletonManager_should_handover_when_oldest_leaves_in_6_node_cluster(); - - Within(TimeSpan.FromSeconds(60), () => - { - // mute logging of deadLetters during shutdown of systems - if (!Log.IsDebugEnabled) - Sys.EventStream.Publish(new Mute(new DeadLettersFilter(new PredicateMatcher(s => true), new PredicateMatcher(s => true)))); - EnterBarrier("logs-muted"); - - Crash(_second); - VerifyRegistration(_third); - VerifyMsg(_third, Msg); - VerifyProxyMsg(_third, _third, Msg); - VerifyProxyMsg(_third, _fourth, Msg); - VerifyProxyMsg(_third, _fifth, Msg); - VerifyProxyMsg(_third, _sixth, Msg); - }); - } - - //[MultiNodeFact(Skip = "TODO")] - public void ClusterSingletonManager_should_takeover_when_two_oldest_crash_in_3_node_cluster() - { - ClusterSingletonManager_should_takeover_when_oldest_crashes_in_5_node_cluster(); - Within(TimeSpan.FromSeconds(60), () => - { - Crash(_third, _fourth); - VerifyRegistration(_fifth); - VerifyMsg(_fifth, Msg); - VerifyProxyMsg(_fifth, _fifth, Msg); - VerifyProxyMsg(_fifth, _fifth, Msg); - }); - } - - [MultiNodeFact] - public void ClusterSingletonManager_should_takeover_when_oldest_crashes_in_2_node_cluster() - { - ClusterSingletonManager_should_takeover_when_two_oldest_crash_in_3_node_cluster(); - - Within(TimeSpan.FromSeconds(60), () => - { - Crash(_fifth); - VerifyRegistration(_sixth); - VerifyMsg(_sixth, Msg); - VerifyProxyMsg(_sixth, _sixth, Msg); - }); - } - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Tools.Tests/Singleton/ClusterSingletonManagerStartupSpec.cs b/src/contrib/cluster/Akka.Cluster.Tools.Tests/Singleton/ClusterSingletonManagerStartupSpec.cs deleted file mode 100644 index ceb61bf6b76..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools.Tests/Singleton/ClusterSingletonManagerStartupSpec.cs +++ /dev/null @@ -1,110 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using System.Linq; -using Akka.Actor; -using Akka.Cluster.Tests.MultiNode; -using Akka.Cluster.Tools.Singleton; -using Akka.Configuration; -using Akka.Remote.TestKit; -using Xunit; - -namespace Akka.Cluster.Tools.Tests.Singleton -{ - public class ClusterSingletonManagerStartupConfig : MultiNodeConfig - { - public ClusterSingletonManagerStartupConfig() - { - var first = Role("first"); - var second = Role("second"); - var third = Role("third"); - - CommonConfig = ConfigurationFactory.ParseString(@" - akka.loglevel = DEBUG - akka.actor.provider = ""Akka.Aluster.ClusterActorRefProvider, Akka.Cluster"" - akka.remote.log-remote-lifecycle-events = off - akka.cluster.auto-down-unreachable-after = 0s") - .WithFallback(ClusterSingletonManager.DefaultConfig()) - .WithFallback(MultiNodeClusterSpec.ClusterConfig()); - } - } - - public class ClusterSingletonManagerStartupNode1 : ClusterSingletonManagerStartupConfig { } - public class ClusterSingletonManagerStartupNode2 : ClusterSingletonManagerStartupConfig { } - public class ClusterSingletonManagerStartupNode3 : ClusterSingletonManagerStartupConfig { } - - public abstract class ClusterSingletonManagerStartupSpec : MultiNodeClusterSpec - { - protected ClusterSingletonManagerStartupSpec() : base(new ClusterSingletonManagerStartupConfig()) - { - EchoProxy = new Lazy(() => Sys.ActorOf(ClusterSingletonProxy.Props( - singletonManagerPath: "/user/echo", - settings: ClusterSingletonProxySettings.Create(Sys)), - name: "echoProxy")); - } - - protected override int InitialParticipantsValueFactory { get { return Roles.Count; } } - - protected Lazy EchoProxy; - - [MultiNodeFact] - public void Startup_of_ClusterSingleton_should_be_quick() - { - var first = GetRole("first"); - var second = GetRole("second"); - var third = GetRole("third"); - - Join(first, first); - Join(second, first); - Join(third, first); - - Within(TimeSpan.FromSeconds(7), () => - { - AwaitAssert(() => - { - var members = Cluster.Get(Sys).ReadView.State.Members; - Assert.Equal(3, members.Count); - foreach (var member in members) - { - Assert.Equal(MemberStatus.Up, member.Status); - } - }); - }); - EnterBarrier("all-up"); - - // the singleton instance is expected to start "instantly" - EchoProxy.Value.Tell("hello"); - ExpectMsg(TimeSpan.FromSeconds(3)); - - EnterBarrier("done"); - } - - private RoleName GetRole(string name) - { - return Roles.First(roleName => roleName.Name == name); - } - - private void Join(RoleName from, RoleName to) - { - RunOn(() => - { - Cluster.Get(Sys).Join(Node(to).Address); - CreateSingleton(); - }, from); - } - - private IActorRef CreateSingleton() - { - return Sys.ActorOf(ClusterSingletonManager.Props( - singletonProps: Props.Create(() => new Echo(TestActor)), - settings: ClusterSingletonManagerSettings.Create(Sys), - terminationMessage: PoisonPill.Instance), - name: "echo"); - } - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Tools.Tests/packages.config b/src/contrib/cluster/Akka.Cluster.Tools.Tests/packages.config deleted file mode 100644 index b38d620f250..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools.Tests/packages.config +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Tools/Akka.Cluster.Tools.csproj b/src/contrib/cluster/Akka.Cluster.Tools/Akka.Cluster.Tools.csproj deleted file mode 100644 index 1b59ba70576..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools/Akka.Cluster.Tools.csproj +++ /dev/null @@ -1,183 +0,0 @@ - - - - - Debug - AnyCPU - {5CF8A8BE-B634-473F-BB01-EBA878746BD4} - Library - Properties - Akka.Cluster.Tools - Akka.Cluster.Tools - v4.5 - 512 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\..\..\packages\Google.ProtocolBuffers.2.4.1.555\lib\net40\Google.ProtocolBuffers.dll - True - - - ..\..\..\packages\Google.ProtocolBuffers.2.4.1.555\lib\net40\Google.ProtocolBuffers.Serialization.dll - True - - - - ..\..\..\packages\System.Collections.Immutable.1.1.37\lib\dotnet\System.Collections.Immutable.dll - True - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {6ab00f61-269a-4501-b06a-026707f000a7} - Akka.Cluster - - - {ea4ff8fd-7c53-49c8-b9aa-02e458b3e6a7} - Akka.Remote - - - {5deddf90-37f0-48d3-a0b0-a5cbd8a7e377} - Akka - - - - - - - - - ..\..\..\..\packages\Google.ProtocolBuffers\lib\net35\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\packages\Google.ProtocolBuffers\lib\net35\Google.ProtocolBuffers.dll - True - True - - - - - - - ..\..\..\..\packages\Google.ProtocolBuffers\lib\net20\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\packages\Google.ProtocolBuffers\lib\net20\Google.ProtocolBuffers.dll - True - True - - - - - - - - ..\..\..\..\packages\Google.ProtocolBuffers\lib\sl30\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\packages\Google.ProtocolBuffers\lib\sl30\Google.ProtocolBuffers.dll - True - True - - - - - - - ..\..\..\..\packages\Google.ProtocolBuffers\lib\sl40\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\packages\Google.ProtocolBuffers\lib\sl40\Google.ProtocolBuffers.dll - True - True - - - - - - - ..\..\..\..\packages\Google.ProtocolBuffers\lib\portable-net40+sl4+sl5+wp7+wp8+win8\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\packages\Google.ProtocolBuffers\lib\portable-net40+sl4+sl5+wp7+wp8+win8\Google.ProtocolBuffers.dll - True - True - - - - - - - - \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Tools/Client/ClusterClient.cs b/src/contrib/cluster/Akka.Cluster.Tools/Client/ClusterClient.cs deleted file mode 100644 index a5467324168..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools/Client/ClusterClient.cs +++ /dev/null @@ -1,314 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using System.Collections.Generic; -using System.Linq; -using Akka.Actor; -using Akka.Cluster.Tools.PublishSubscribe; -using Akka.Event; -using Akka.Remote; - -namespace Akka.Cluster.Tools.Client -{ - /// - /// - /// This actor is intended to be used on an external node that is not member - /// of the cluster. It acts like a gateway for sending messages to actors - /// somewhere in the cluster. From the initial contact points it will establish - /// a connection to a somewhere in the cluster. It will - /// monitor the connection to the receptionist and establish a new connection if - /// the link goes down. When looking for a new receptionist it uses fresh contact - /// points retrieved from previous establishment, or periodically refreshed - /// contacts, i.e. not necessarily the initial contact points. - /// - /// - /// You can send messages via the `ClusterClient` to any actor in the cluster - /// that is registered in the . - /// Messages are wrapped in , - /// or . - /// - /// - /// 1. - - /// The message will be delivered to one recipient with a matching path, if any such - /// exists. If several entries match the path the message will be delivered - /// to one random destination. The sender of the message can specify that local - /// affinity is preferred, i.e. the message is sent to an actor in the same local actor - /// system as the used receptionist actor, if any such exists, otherwise random to any other - /// matching entry. - /// - /// - /// 2. - - /// The message will be delivered to all recipients with a matching path. - /// - /// - /// 3. - - /// The message will be delivered to all recipients Actors that have been registered as subscribers to - /// to the named topic. - /// - /// - /// Use the factory method to create the for the actor. - /// - /// - public class ClusterClient : ActorBase - { - #region Messages - - [Serializable] - public sealed class Send - { - public readonly string Path; - public readonly object Message; - public readonly bool LocalAffinity; - - public Send(string path, object message, bool localAffinity = false) - { - Path = path; - Message = message; - LocalAffinity = localAffinity; - } - } - - [Serializable] - public sealed class SendToAll - { - public readonly string Path; - public readonly object Message; - - public SendToAll(string path, object message) - { - Path = path; - Message = message; - } - } - - [Serializable] - public sealed class Publish - { - public readonly string Topic; - public readonly object Message; - - public Publish(string topic, object message) - { - Topic = topic; - Message = message; - } - } - - internal enum InternalMessage - { - RefreshContactsTick, - HeartbeatTick - } - - #endregion - - /// - /// Factory method for . - /// - public static Actor.Props Props(ClusterClientSettings settings) - { - if (settings == null) - throw new ArgumentNullException("settings"); - - return Actor.Props.Create(() => new ClusterClient(settings)).WithDeploy(Deploy.Local); - } - - public readonly ClusterClientSettings Settings; - private readonly DeadlineFailureDetector _failureDetector; - private readonly ActorSelection[] _initialContactsSelections; - private readonly ICancelable _heartbeatCancelable; - private readonly Queue> _buffer; - - private ILoggingAdapter _log; - private ActorSelection[] _contacts; - private ICancelable _refreshContactsCancelable = null; - - public ClusterClient(ClusterClientSettings settings) - { - if (!settings.InitialContacts.Any()) throw new ArgumentException("Initial contacts for cluster client cannot be empty"); - Settings = settings; - _failureDetector = new DeadlineFailureDetector(Settings.AcceptableHeartbeatPause, () => Settings.HeartbeatInterval.Ticks); - _initialContactsSelections = settings.InitialContacts.Select(Context.ActorSelection).ToArray(); - _contacts = _initialContactsSelections; - _buffer = new Queue>(); - - SendGetContacts(); - - _heartbeatCancelable = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable( - settings.HeartbeatInterval, settings.HeartbeatInterval, Self, InternalMessage.HeartbeatTick, Self); - - ScheduleRefreshContactsTick(settings.EstablishingGetContactsInterval); - Self.Tell(InternalMessage.RefreshContactsTick); - } - - public ILoggingAdapter Log { get { return _log ?? (_log = Context.GetLogger()); } } - - private void ScheduleRefreshContactsTick(TimeSpan interval) - { - if (_refreshContactsCancelable != null) _refreshContactsCancelable.Cancel(); - - _refreshContactsCancelable = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(interval, - interval, Self, InternalMessage.RefreshContactsTick, Self); - } - - protected override void PostStop() - { - base.PostStop(); - _heartbeatCancelable.Cancel(); - if (_refreshContactsCancelable != null) - { - _refreshContactsCancelable.Cancel(); - _refreshContactsCancelable = null; - } - } - - protected override bool Receive(object message) - { - return Establishing(message); - } - - private bool Establishing(object message) - { - return message.Match() - .With(msg => - { - if (msg.ContactPoints.Length != 0) - { - _contacts = msg.ContactPoints.Select(Context.ActorSelection).ToArray(); - foreach (var contact in _contacts) - { - contact.Tell(new Identify(null)); - } - } - }) - .With(msg => - { - if (msg.Subject != null) - { - Log.Info("Connected to [{0}]", msg.Subject.Path); - ScheduleRefreshContactsTick(Settings.RefreshContactsInterval); - - var receptionist = msg.Subject; - SendBuffered(receptionist); - Context.Become(Active(receptionist)); - _failureDetector.HeartBeat(); - } - }) - .With(msg => - { - switch (msg) - { - case InternalMessage.HeartbeatTick: - _failureDetector.HeartBeat(); - break; - case InternalMessage.RefreshContactsTick: - SendGetContacts(); - break; - } - }) - .With(send => Buffer(new Distributed.Send(send.Path, send.Message, send.LocalAffinity))) - .With(send => Buffer(new Distributed.SendToAll(send.Path, send.Message))) - .With(publish => Buffer(new Distributed.Publish(publish.Topic, publish.Message))) - .WasHandled; - } - - private Receive Active(IActorRef receptionist) - { - return message => - message.Match() - .With(send => - receptionist.Forward(new Distributed.Send(send.Path, send.Message, send.LocalAffinity))) - .With(toAll => - receptionist.Forward(new Distributed.SendToAll(toAll.Path, toAll.Message))) - .With(publish => - receptionist.Forward(new Distributed.Publish(publish.Topic, publish.Message))) - .With(m => - { - switch (m) - { - case InternalMessage.HeartbeatTick: - if (!_failureDetector.IsAvailable) - { - Log.Info("Lost contact with [{0}], restablishing connection", receptionist); - SendGetContacts(); - ScheduleRefreshContactsTick(Settings.EstablishingGetContactsInterval); - Context.Become(Establishing); - _failureDetector.HeartBeat(); - } - else - { - receptionist.Tell(ClusterReceptionist.Heartbeat.Instance); - } - break; - case InternalMessage.RefreshContactsTick: - receptionist.Tell(ClusterReceptionist.GetContacts.Instance); - break; - } - }) - .With(_ => _failureDetector.HeartBeat()) - .With(contacts => - { - if (contacts.ContactPoints.Length != 0) - _contacts = contacts.ContactPoints.Select(Context.ActorSelection).ToArray(); - }) - .With(terminated => - { - Log.Info("Lost contact with [{0}], restablishing connection", receptionist); - SendGetContacts(); - ScheduleRefreshContactsTick(Settings.EstablishingGetContactsInterval); - Context.Become(Establishing); - }) - .With(_ => { /* ok, from previous establish, already handled */ }) - .WasHandled; - } - - private void SendGetContacts() - { - ActorSelection[] toSend; - if (_contacts.Length == 0) - toSend = _initialContactsSelections; - else if (_contacts.Length == 1) - toSend = _initialContactsSelections.Union(_contacts).ToArray(); - else - toSend = _contacts; - - if (Log.IsDebugEnabled) - Log.Debug("Sending GetContacts to [{0}]", string.Join(", ", toSend.AsEnumerable())); - - foreach (var contact in toSend) - contact.Tell(ClusterReceptionist.GetContacts.Instance); - } - - private void Buffer(object message) - { - if (Settings.BufferSize == 0) - Log.Debug("Receptionist not available and buffering is disabled, dropping message [{0}]", message.GetType()); - else if (_buffer.Count == Settings.BufferSize) - { - var m = _buffer.Dequeue(); - Log.Debug("Receptionist not available, buffer is full, dropping first message [{0}]", m.Item1.GetType()); - _buffer.Enqueue(Tuple.Create(message, Sender)); - } - else - { - Log.Debug("Receptionist not available, buffering message type [{0}]", message.GetType()); - _buffer.Enqueue(Tuple.Create(message, Sender)); - } - } - - private void SendBuffered(IActorRef receptionist) - { - Log.Debug("Sending buffered messages to receptionist"); - while (_buffer.Count != 0) - { - var t = _buffer.Dequeue(); - receptionist.Tell(t.Item1, t.Item2); - } - } - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Tools/Client/ClusterClientReceptionist.cs b/src/contrib/cluster/Akka.Cluster.Tools/Client/ClusterClientReceptionist.cs deleted file mode 100644 index 25a684d43d6..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools/Client/ClusterClientReceptionist.cs +++ /dev/null @@ -1,130 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using Akka.Actor; -using Akka.Cluster.Tools.PublishSubscribe; -using Akka.Configuration; -using Akka.Dispatch; - -namespace Akka.Cluster.Tools.Client -{ - - public class ClusterClientReceptionistExtensionProvider : ExtensionIdProvider - { - public override ClusterClientReceptionist CreateExtension(ExtendedActorSystem system) - { - return new ClusterClientReceptionist(system); - } - } - - /// - /// Extension that starts and accompanying - /// with settings defined in config section "akka.cluster.client.receptionist". - /// The is started by the extension. - /// - public class ClusterClientReceptionist : IExtension - { - private readonly ExtendedActorSystem _system; - private readonly string _role; - - private readonly IActorRef _receptionist; - private readonly Cluster _cluster; - - public static Config DefaultConfig() - { - return ConfigurationFactory.FromResource("Akka.Cluster.Tools.Client.reference.conf"); - } - - public static ClusterClientReceptionist Get(ActorSystem system) - { - return system.WithExtension(); - } - - public ClusterClientReceptionist(ExtendedActorSystem system) - { - _system = system; - _system.Settings.InjectTopLevelFallback(DefaultConfig()); - _cluster = Cluster.Get(_system); - var config = system.Settings.Config.GetConfig("akka.cluster.client.receptionist"); - _role = config.GetString("role"); - _receptionist = CreateReceptionist(config); - } - - /// - /// Returns true if this member is not tagged with the role configured for the receptionist. - /// - public bool IsTerminated - { - get - { - return _cluster.IsTerminated || !(string.IsNullOrEmpty(_role) || _cluster.SelfRoles.Contains(_role)); - } - } - - /// - /// Register the actors that should be reachable for the clients in this . - /// - public IActorRef PubSubMediator - { - get { return DistributedPubSub.Get(_system).Mediator; } - } - - /// - /// Register an actor that should be reachable for the clients. The clients can send messages to this actor with - /// or using the path elements - /// of the , e.g. "/user/myservice". - /// - public void RegisterService(IActorRef actorRef) - { - PubSubMediator.Tell(new Distributed.Put(actorRef)); - } - - /// - /// A registered actor will be automatically unregistered when terminated, - /// but it can also be explicitly unregistered before termination. - /// - public void UnregisterService(IActorRef actorRef) - { - PubSubMediator.Tell(new Distributed.Remove(actorRef.Path.ToStringWithoutAddress())); - } - - /// - /// Register an actor that should be reachable for the clients to a named topic. - /// Several actors can be registered to the same topic name, and all will receive - /// published messages. - /// The client can publish messages to this topic with . - /// - public void RegisterSubscriber(string topic, IActorRef actorRef) - { - PubSubMediator.Tell(new Distributed.Subscribe(topic, actorRef)); - } - - /// - /// A registered subscriber will be automatically unregistered when terminated, - /// but it can also be explicitly unregistered before termination. - /// - public void UnregisterSubscriber(string topic, IActorRef actorRef) - { - PubSubMediator.Tell(new Distributed.Unsubscribe(topic, actorRef)); - } - - private IActorRef CreateReceptionist(Config config) - { - if (IsTerminated) return _system.DeadLetters; - else - { - var name = config.GetString("name"); - var dispatcher = config.GetString("use-dispatcher"); - if (string.IsNullOrEmpty(dispatcher)) dispatcher = Dispatchers.DefaultDispatcherId; - - // important to use val mediator here to activate it outside of ClusterReceptionist constructor - var mediator = PubSubMediator; - return _system.SystemActorOf(ClusterReceptionist.Props(mediator, ClusterReceptionistSettings.Create(config)).WithDispatcher(dispatcher), name); - } - } - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Tools/Client/ClusterClientSettings.cs b/src/contrib/cluster/Akka.Cluster.Tools/Client/ClusterClientSettings.cs deleted file mode 100644 index ee2de0790ca..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools/Client/ClusterClientSettings.cs +++ /dev/null @@ -1,125 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Linq; -using Akka.Actor; -using Akka.Remote; - -namespace Akka.Cluster.Tools.Client -{ - [Serializable] - public sealed class ClusterClientSettings - { - public static ClusterClientSettings Create(ActorSystem system) - { - var config = system.Settings.Config.GetConfig("akka.cluster.client"); - var initialContacts = config.GetStringList("initial-contacts").Select(ActorPath.Parse).ToImmutableSortedSet(); - - return new ClusterClientSettings(initialContacts, - config.GetTimeSpan("establishing-get-contacts-interval"), - config.GetTimeSpan("refresh-contacts-interval"), - config.GetTimeSpan("heartbeat-interval"), - config.GetTimeSpan("acceptable-heartbeat-pause"), - config.GetInt("buffer-size")); - } - - /// - /// Actor paths of the actors on the servers (cluster nodes) that the client will try to contact initially. - /// - public readonly IImmutableSet InitialContacts; - - /// - /// Interval at which the client retries to establish contact with one of ClusterReceptionist on the servers (cluster nodes) - /// - public readonly TimeSpan EstablishingGetContactsInterval; - - /// - /// Interval at which the client will ask the for new contact points to be used for next reconnect. - /// - public readonly TimeSpan RefreshContactsInterval; - - /// - /// How often failure detection heartbeat messages for detection of failed connections should be sent. - /// - public readonly TimeSpan HeartbeatInterval; - - /// - /// Number of potentially lost/delayed heartbeats that will be accepted before considering it to be an anomaly. - /// The ClusterClient is using the , which will trigger if there are - /// no heartbeats within the duration + . - /// - public readonly TimeSpan AcceptableHeartbeatPause; - - /// - /// If connection to the receptionist is not established the client will buffer this number of messages and deliver - /// them the connection is established. When the buffer is full old messages will be dropped when new messages are sent via the client. - /// Use 0 to disable buffering, i.e. messages will be dropped immediately if the location of the receptionist is unavailable. - /// - public readonly int BufferSize; - - public ClusterClientSettings( - IImmutableSet initialContacts, - TimeSpan establishingGetContactsInterval, - TimeSpan refreshContactsInterval, - TimeSpan heartbeatInterval, - TimeSpan acceptableHeartbeatPause, - int bufferSize) - { - InitialContacts = initialContacts; - EstablishingGetContactsInterval = establishingGetContactsInterval; - RefreshContactsInterval = refreshContactsInterval; - HeartbeatInterval = heartbeatInterval; - AcceptableHeartbeatPause = acceptableHeartbeatPause; - BufferSize = bufferSize; - } - - public ClusterClientSettings WithInitialContacts(IEnumerable initialContacts) - { - return Copy(initialContacts: initialContacts); - } - - public ClusterClientSettings WithEstablishingGetContactsInterval(TimeSpan value) - { - return Copy(establishingGetContactsInterval: value); - } - - public ClusterClientSettings WithRefreshContactsInterval(TimeSpan value) - { - return Copy(refreshContactsInterval: value); - } - - public ClusterClientSettings WithHeartbeatInterval(TimeSpan value) - { - return Copy(heartbeatInterval: value); - } - - public ClusterClientSettings WithBufferSize(int bufferSize) - { - return Copy(bufferSize: bufferSize); - } - - private ClusterClientSettings Copy( - IEnumerable initialContacts = null, - TimeSpan? establishingGetContactsInterval = null, - TimeSpan? refreshContactsInterval = null, - TimeSpan? heartbeatInterval = null, - TimeSpan? acceptableHeartbeatPause = null, - int? bufferSize = null) - { - return new ClusterClientSettings( - initialContacts == null ? InitialContacts : ImmutableHashSet.CreateRange(initialContacts), - establishingGetContactsInterval ?? EstablishingGetContactsInterval, - refreshContactsInterval ?? RefreshContactsInterval, - heartbeatInterval ?? HeartbeatInterval, - acceptableHeartbeatPause ?? AcceptableHeartbeatPause, - bufferSize ?? BufferSize); - } - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Tools/Client/ClusterReceptionist.cs b/src/contrib/cluster/Akka.Cluster.Tools/Client/ClusterReceptionist.cs deleted file mode 100644 index 30bb8f1b824..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools/Client/ClusterReceptionist.cs +++ /dev/null @@ -1,287 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using System.Collections.Generic; -using System.Linq; -using Akka.Actor; -using Akka.Cluster.Tools.PublishSubscribe; -using Akka.Event; -using Akka.Pattern; -using Akka.Routing; -using Akka.Util; - -namespace Akka.Cluster.Tools.Client -{ - public interface IClusterClientMessage { } - - /// - /// - /// connects to this actor to retrieve. The `ClusterReceptionist` is - /// supposed to be started on all nodes, or all nodes with specified role, in the cluster. - /// The receptionist can be started with the or as an - /// ordinary actor (use the factory method ). - /// - /// - /// The receptionist forwards messages from the client to the associated , - /// i.e. the client can send messages to any actor in the cluster that is registered in the - /// `DistributedPubSubMediator`. Messages from the client are wrapped in - /// , - /// or with the semantics described in - /// . - /// - /// - /// Response messages from the destination actor are tunneled via the receptionist - /// to avoid inbound connections from other cluster nodes to the client, i.e. - /// the , as seen by the destination actor, is not the client itself. - /// The of the response messages, as seen by the client, is preserved - /// as the original sender, so the client can choose to send subsequent messages - /// directly to the actor in the cluster. - /// - /// - public class ClusterReceptionist : ActorBase - { - #region Messages - - [Serializable] - public sealed class GetContacts : IClusterClientMessage - { - public static readonly GetContacts Instance = new GetContacts(); - private GetContacts() { } - } - - [Serializable] - public sealed class Contacts : IClusterClientMessage - { - public readonly string[] ContactPoints; - - public Contacts(string[] contactPoints) - { - ContactPoints = contactPoints ?? new string[0]; - } - } - - [Serializable] - public sealed class Heartbeat : IClusterClientMessage - { - public static readonly Heartbeat Instance = new Heartbeat(); - private Heartbeat() { } - } - - [Serializable] - public sealed class HeartbeatRsp : IClusterClientMessage - { - public static readonly HeartbeatRsp Instance = new HeartbeatRsp(); - private HeartbeatRsp() { } - } - - [Serializable] - public sealed class Ping - { - public static readonly Ping Instance = new Ping(); - private Ping() { } - } - - #endregion - - internal class RingOrdering : IComparer
- { - public static readonly RingOrdering Instance = new RingOrdering(); - private RingOrdering() { } - - public static int HashFor(Address node) - { - // cluster node identifier is the host and port of the address; protocol and system is assumed to be the same - if (!string.IsNullOrEmpty(node.Host) && node.Port.HasValue) - return MurmurHash.StringHash(node.Host + ":" + node.Port.Value.ToString()); - else - throw new IllegalStateException("Unexpected address without host/port: " + node); - } - - public int Compare(Address x, Address y) - { - var hx = HashFor(x); - var hy = HashFor(y); - - if (hx == hy) return 0; - return hx < hy || Member.AddressOrdering.Compare(x, y) < 0 ? -1 : 1; - } - } - - /// - /// Factory method for . - /// - public static Actor.Props Props(IActorRef mediator, ClusterReceptionistSettings settings) - { - return Actor.Props.Create(() => new ClusterReceptionist(mediator, settings)).WithDeploy(Deploy.Local); - } - - private const int VirtualNodesFactor = 10; - private readonly IActorRef _pubSubMediator; - private readonly ClusterReceptionistSettings _settings; - private readonly Cluster _cluster = Cluster.Get(Context.System); - - private ConsistentHash
_consistentHash; - private SortedDictionary _nodes; - private ILoggingAdapter _log; - - public ILoggingAdapter Log { get { return _log ?? (_log = Context.GetLogger()); } } - - public ClusterReceptionist(IActorRef pubSubMediator, ClusterReceptionistSettings settings) - { - _pubSubMediator = pubSubMediator; - _settings = settings; - - if (!(_settings.Role == null || _cluster.SelfRoles.Contains(_settings.Role))) - throw new ArgumentException(string.Format("This cluster member [{0}] does not have a role [{1}]", _cluster.SelfAddress, _settings.Role)); - - _nodes = GetNodes(); - _consistentHash = new ConsistentHash
(_nodes, VirtualNodesFactor); - } - - protected override bool Receive(object message) - { - if (message is Distributed.Send || message is Distributed.SendToAll || message is Distributed.Publish) - { - var tunnel = ResponseTunnel(Sender); - tunnel.Tell(Ping.Instance); - _pubSubMediator.Tell(message, tunnel); - } - else if (message is Heartbeat) - { - Log.Debug("Heartbeat from client [{0}]", Sender.Path); - Sender.Tell(HeartbeatRsp.Instance); - } - else if (message is GetContacts) - { - // Consistent hashing is used to ensure that the reply to GetContacts - // is the same from all nodes (most of the time) and it also - // load balances the client connections among the nodes in the cluster. - if (_settings.NumberOfContacts > _nodes.Count) - { - var contacts = _nodes.Select(kv => Self.Path.ToStringWithAddress(kv.Value)).ToArray(); - if (Log.IsDebugEnabled) - Log.Debug("Client [{0}] gets contactPoints [{1}] (all nodes)", Sender.Path, string.Join(", ", contacts)); - - Sender.Tell(new Contacts(contacts)); - } - else - { - // using toStringWithAddress in case the client is local, normally it is not, and - // toStringWithAddress will use the remote address of the client - - var addr = _consistentHash.NodeFor(Sender.Path.ToStringWithAddress(_cluster.SelfAddress)); - //TODO: this should be changed to some kind of _nodes.GetGreaterThan(addr) - var first = _nodes.Where(a => RingOrdering.Instance.Compare(a.Value, addr) == 1).Take(_settings.NumberOfContacts).ToArray(); - var slice = first.Length == _settings.NumberOfContacts - ? first - : first.Union(_nodes.Take(_settings.NumberOfContacts - first.Length)).ToArray(); - var contacts = new Contacts(slice.Select(a => Self.Path.ToStringWithAddress(a.Value)).ToArray()); - - if (Log.IsDebugEnabled) - Log.Debug("Client [{0}] gets contactPoints [{1}]", Sender.Path, string.Join(", ", contacts.ContactPoints)); - - Sender.Tell(contacts); - } - } - else if (message is ClusterEvent.CurrentClusterState) - { - var state = (ClusterEvent.CurrentClusterState)message; - - _nodes = GetNodes(); - foreach (var member in state.Members.Where(m => m.Status != MemberStatus.Joining && IsMatchingRole(m))) - { - _nodes.Add(RingOrdering.HashFor(member.Address), member.Address); - } - _consistentHash = new ConsistentHash
(_nodes, VirtualNodesFactor); - - } - else if (message is ClusterEvent.MemberUp) - { - var up = (ClusterEvent.MemberUp)message; - if (IsMatchingRole(up.Member)) - { - _nodes.Add(RingOrdering.HashFor(up.Member.Address), up.Member.Address); - _consistentHash = new ConsistentHash
(_nodes, VirtualNodesFactor); - } - } - else if (message is ClusterEvent.MemberRemoved) - { - var removed = (ClusterEvent.MemberRemoved)message; - if (removed.Member.Address == _cluster.SelfAddress) - { - Context.Stop(Self); - } - else if (IsMatchingRole(removed.Member)) - { - _nodes.Remove(RingOrdering.HashFor(removed.Member.Address)); - _consistentHash = new ConsistentHash
(_nodes, VirtualNodesFactor); - } - } - else if (message is ClusterEvent.IMemberEvent) - { - /* ignore */ - } - else return false; - return true; - } - - protected override void PreStart() - { - base.PreStart(); - if (_cluster.IsTerminated) throw new IllegalStateException("Cluster node must not be terminated"); - _cluster.Subscribe(Self, new[] { typeof(ClusterEvent.IMemberEvent) }); - } - - protected override void PostStop() - { - base.PostStop(); - _cluster.Unsubscribe(Self); - } - - private SortedDictionary GetNodes() - { - return new SortedDictionary(); - } - - private bool IsMatchingRole(Member member) - { - return string.IsNullOrEmpty(_settings.Role) || member.HasRole(_settings.Role); - } - - private IActorRef ResponseTunnel(IActorRef client) - { - var encName = Uri.EscapeDataString(client.Path.ToSerializationFormat()); - var child = Context.Child(encName); - - return !Equals(child, ActorRefs.Nobody) - ? child - : Context.ActorOf(Actor.Props.Create(() => new ClientResponseTunnel(client, _settings.ResponseTunnelReceiveTimeout)), encName); - } - } - - /// - /// Replies are tunneled via this actor, child of the receptionist, to avoid inbound connections from other cluster nodes to the client. - /// - internal class ClientResponseTunnel : UntypedActor - { - private readonly IActorRef _client; - - public ClientResponseTunnel(IActorRef client, TimeSpan timeout) - { - _client = client; - Context.SetReceiveTimeout(timeout); - } - - protected override void OnReceive(object message) - { - if (message is ClusterReceptionist.Ping) { /* ignore */ } - else if (message is ReceiveTimeout) Context.Stop(Self); - else _client.Tell(message, ActorRefs.NoSender); - } - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Tools/Client/ClusterReceptionistSettings.cs b/src/contrib/cluster/Akka.Cluster.Tools/Client/ClusterReceptionistSettings.cs deleted file mode 100644 index 4dd032bc6ec..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools/Client/ClusterReceptionistSettings.cs +++ /dev/null @@ -1,85 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using Akka.Actor; -using Akka.Configuration; - -namespace Akka.Cluster.Tools.Client -{ - [Serializable] - public sealed class ClusterReceptionistSettings - { - /// - /// Create settings from the default configuration "akka.cluster.client.receptionist". - /// - public static ClusterReceptionistSettings Create(ActorSystem system) - { - var config = system.Settings.Config.GetConfig("akka.cluster.client.receptionist"); - if (config == null) - throw new ArgumentException(string.Format("Actor system [{0}] doesn't have `akka.cluster.client.receptionist` config set up", system.Name)); - - return Create(config); - } - - /// - /// Create settings from a configuration with the same layout as the default configuration "akka.cluster.client.receptionist". - /// - public static ClusterReceptionistSettings Create(Config config) - { - return new ClusterReceptionistSettings(config.GetString("role"), config.GetInt("number-of-contacts"), config.GetTimeSpan("response-tunnel-receive-timeout")); - } - - /// - /// Start the receptionist on members tagged with this role. All members are used if undefined. - /// - public readonly string Role; - - /// - /// The receptionist will send this number of contact points to the client. - /// - public readonly int NumberOfContacts; - - /// - /// The actor that tunnel response messages to the client will be stopped after this time of inactivity. - /// - public readonly TimeSpan ResponseTunnelReceiveTimeout; - - public ClusterReceptionistSettings(string role, int numberOfContacts, TimeSpan responseTunnelReceiveTimeout) - { - Role = !string.IsNullOrEmpty(role) ? role : null; - NumberOfContacts = numberOfContacts; - ResponseTunnelReceiveTimeout = responseTunnelReceiveTimeout; - } - - public ClusterReceptionistSettings WithRole(string role) - { - return Copy(role: role); - } - - public ClusterReceptionistSettings WithoutRole() - { - return Copy(role: null); - } - - public ClusterReceptionistSettings WithNumberOfContacts(int numberOfContacts) - { - return Copy(numberOfContacts: numberOfContacts); - } - - public ClusterReceptionistSettings WithResponseTunnelReceiveTimeout(TimeSpan responseTunnelReceiveTimeout) - { - return Copy(responseTunnelReceiveTimeout: responseTunnelReceiveTimeout); - } - - private ClusterReceptionistSettings Copy(string role = null, int? numberOfContacts = null, - TimeSpan? responseTunnelReceiveTimeout = null) - { - return new ClusterReceptionistSettings(role ?? Role, numberOfContacts ?? NumberOfContacts, responseTunnelReceiveTimeout ?? ResponseTunnelReceiveTimeout); - } - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Tools/Client/Serialization/ClusterClientMessageSerializer.cs b/src/contrib/cluster/Akka.Cluster.Tools/Client/Serialization/ClusterClientMessageSerializer.cs deleted file mode 100644 index 8b8a53d503f..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools/Client/Serialization/ClusterClientMessageSerializer.cs +++ /dev/null @@ -1,77 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Akka.Actor; -using Akka.Serialization; - -namespace Akka.Cluster.Tools.Client.Serialization -{ - public class ClusterClientMessageSerializer : SerializerWithStringManifest - { - private const string ContactsManifest = "A"; - private const string GetContactsManifest = "B"; - private const string HeartbeatManifest = "C"; - private const string HeartbeatRspManifest = "D"; - - private static readonly byte[] EmptyBytes = new byte[0]; - private static readonly IDictionary> FromBinaryMap = new Dictionary> - { - {ContactsManifest, ContactsFromBinary}, - {GetContactsManifest, _ => ClusterReceptionist.GetContacts.Instance}, - {HeartbeatManifest, _ => ClusterReceptionist.Heartbeat.Instance}, - {HeartbeatRspManifest, _ => ClusterReceptionist.HeartbeatRsp.Instance} - }; - - private readonly int _identifier; - public ClusterClientMessageSerializer(ExtendedActorSystem system) : base(system) - { - _identifier = SerializerIdentifierHelper.GetSerializerIdentifierFromConfig(this.GetType(), system); - } - - public override int Identifier { get { return _identifier; } } - - public override byte[] ToBinary(object o) - { - if (o is ClusterReceptionist.Contacts) return ContactsToProto((ClusterReceptionist.Contacts)o).ToByteArray(); - if (o is ClusterReceptionist.GetContacts) return EmptyBytes; - if (o is ClusterReceptionist.Heartbeat) return EmptyBytes; - if (o is ClusterReceptionist.HeartbeatRsp) return EmptyBytes; - - throw new ArgumentException(string.Format("Can't serialize object of type [{0}] in [{1}]", o.GetType(), GetType())); - } - - public override object FromBinary(byte[] binary, string manifest) - { - Func mapper; - if (FromBinaryMap.TryGetValue(manifest, out mapper)) - { - return mapper(binary); - } - - throw new ArgumentException(string.Format("Unimplemented deserialization of message with manifest [{0}] in [{1}]", manifest, GetType())); - } - - public override string Manifest(object o) - { - if (o is ClusterReceptionist.Contacts) return ContactsManifest; - if (o is ClusterReceptionist.GetContacts) return GetContactsManifest; - if (o is ClusterReceptionist.Heartbeat) return HeartbeatManifest; - if (o is ClusterReceptionist.HeartbeatRsp) return HeartbeatRspManifest; - - throw new ArgumentException(string.Format("Can't serialize object of type [{0}] in [{1}]", o.GetType(), GetType())); - } - - private Contacts ContactsToProto(ClusterReceptionist.Contacts message) - { - return Contacts.CreateBuilder() - .AddRangeContactPoints(message.ContactPoints) - .Build(); - } - - private static ClusterReceptionist.Contacts ContactsFromBinary(byte[] binary) - { - var proto = Contacts.ParseFrom(binary); - return new ClusterReceptionist.Contacts(proto.ContactPointsList.ToArray()); - } - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Tools/Client/Serialization/Proto/ClusterClientMessages.cs b/src/contrib/cluster/Akka.Cluster.Tools/Client/Serialization/Proto/ClusterClientMessages.cs deleted file mode 100644 index 32cb5c31a53..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools/Client/Serialization/Proto/ClusterClientMessages.cs +++ /dev/null @@ -1,417 +0,0 @@ -// Generated by ProtoGen, Version=2.4.1.521, Culture=neutral, PublicKeyToken=55f7125234beb589. DO NOT EDIT! -#pragma warning disable 1591, 0612, 3021 -#region Designer generated code - -using pb = global::Google.ProtocolBuffers; -using pbc = global::Google.ProtocolBuffers.Collections; -using pbd = global::Google.ProtocolBuffers.Descriptors; -using scg = global::System.Collections.Generic; -[global::System.Diagnostics.DebuggerNonUserCodeAttribute()] -public static partial class ClusterClientMessages -{ - - #region Extension registration - public static void RegisterAllExtensions(pb::ExtensionRegistry registry) - { - } - #endregion - #region Static variables - internal static pbd::MessageDescriptor internal__static_Contacts__Descriptor; - internal static pb::FieldAccess.FieldAccessorTable internal__static_Contacts__FieldAccessorTable; - #endregion - #region Descriptor - public static pbd::FileDescriptor Descriptor - { - get { return descriptor; } - } - private static pbd::FileDescriptor descriptor; - - static ClusterClientMessages() - { - byte[] descriptorData = global::System.Convert.FromBase64String( - "ChtDbHVzdGVyQ2xpZW50TWVzc2FnZXMucHJvdG8iIQoIQ29udGFjdHMSFQoN" + - "Y29udGFjdFBvaW50cxgBIAMoCUIkCiBha2thLmNsdXN0ZXIuY2xpZW50LnBy" + - "b3RvYnVmLm1zZ0gB"); - pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate (pbd::FileDescriptor root) { - descriptor = root; - internal__static_Contacts__Descriptor = Descriptor.MessageTypes[0]; - internal__static_Contacts__FieldAccessorTable = - new pb::FieldAccess.FieldAccessorTable(internal__static_Contacts__Descriptor, - new string[] { "ContactPoints", }); - return null; - }; - pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, - new pbd::FileDescriptor[] { - }, assigner); - } - #endregion - -} -#region Messages -[global::System.Diagnostics.DebuggerNonUserCodeAttribute()] -public sealed partial class Contacts : pb::GeneratedMessage -{ - private Contacts() { } - private static readonly Contacts defaultInstance = new Contacts().MakeReadOnly(); - private static readonly string[] _contactsFieldNames = new string[] { "contactPoints" }; - private static readonly uint[] _contactsFieldTags = new uint[] { 10 }; - public static Contacts DefaultInstance - { - get { return defaultInstance; } - } - - public override Contacts DefaultInstanceForType - { - get { return DefaultInstance; } - } - - protected override Contacts ThisMessage - { - get { return this; } - } - - public static pbd::MessageDescriptor Descriptor - { - get { return global::ClusterClientMessages.internal__static_Contacts__Descriptor; } - } - - protected override pb::FieldAccess.FieldAccessorTable InternalFieldAccessors - { - get { return global::ClusterClientMessages.internal__static_Contacts__FieldAccessorTable; } - } - - public const int ContactPointsFieldNumber = 1; - private pbc::PopsicleList contactPoints_ = new pbc::PopsicleList(); - public scg::IList ContactPointsList - { - get { return pbc::Lists.AsReadOnly(contactPoints_); } - } - public int ContactPointsCount - { - get { return contactPoints_.Count; } - } - public string GetContactPoints(int index) - { - return contactPoints_[index]; - } - - public override bool IsInitialized - { - get - { - return true; - } - } - - public override void WriteTo(pb::ICodedOutputStream output) - { - int size = SerializedSize; - string[] field_names = _contactsFieldNames; - if (contactPoints_.Count > 0) - { - output.WriteStringArray(1, field_names[0], contactPoints_); - } - UnknownFields.WriteTo(output); - } - - private int memoizedSerializedSize = -1; - public override int SerializedSize - { - get - { - int size = memoizedSerializedSize; - if (size != -1) return size; - - size = 0; - { - int dataSize = 0; - foreach (string element in ContactPointsList) - { - dataSize += pb::CodedOutputStream.ComputeStringSizeNoTag(element); - } - size += dataSize; - size += 1 * contactPoints_.Count; - } - size += UnknownFields.SerializedSize; - memoizedSerializedSize = size; - return size; - } - } - - public static Contacts ParseFrom(pb::ByteString data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static Contacts ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static Contacts ParseFrom(byte[] data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static Contacts ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static Contacts ParseFrom(global::System.IO.Stream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static Contacts ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - public static Contacts ParseDelimitedFrom(global::System.IO.Stream input) - { - return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); - } - public static Contacts ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); - } - public static Contacts ParseFrom(pb::ICodedInputStream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static Contacts ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - private Contacts MakeReadOnly() - { - contactPoints_.MakeReadOnly(); - return this; - } - - public static Builder CreateBuilder() { return new Builder(); } - public override Builder ToBuilder() { return CreateBuilder(this); } - public override Builder CreateBuilderForType() { return new Builder(); } - public static Builder CreateBuilder(Contacts prototype) - { - return new Builder(prototype); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class Builder : pb::GeneratedBuilder - { - protected override Builder ThisBuilder - { - get { return this; } - } - public Builder() - { - result = DefaultInstance; - resultIsReadOnly = true; - } - internal Builder(Contacts cloneFrom) - { - result = cloneFrom; - resultIsReadOnly = true; - } - - private bool resultIsReadOnly; - private Contacts result; - - private Contacts PrepareBuilder() - { - if (resultIsReadOnly) - { - Contacts original = result; - result = new Contacts(); - resultIsReadOnly = false; - MergeFrom(original); - } - return result; - } - - public override bool IsInitialized - { - get { return result.IsInitialized; } - } - - protected override Contacts MessageBeingBuilt - { - get { return PrepareBuilder(); } - } - - public override Builder Clear() - { - result = DefaultInstance; - resultIsReadOnly = true; - return this; - } - - public override Builder Clone() - { - if (resultIsReadOnly) - { - return new Builder(result); - } - else - { - return new Builder().MergeFrom(result); - } - } - - public override pbd::MessageDescriptor DescriptorForType - { - get { return global::Contacts.Descriptor; } - } - - public override Contacts DefaultInstanceForType - { - get { return global::Contacts.DefaultInstance; } - } - - public override Contacts BuildPartial() - { - if (resultIsReadOnly) - { - return result; - } - resultIsReadOnly = true; - return result.MakeReadOnly(); - } - - public override Builder MergeFrom(pb::IMessage other) - { - if (other is Contacts) - { - return MergeFrom((Contacts)other); - } - else - { - base.MergeFrom(other); - return this; - } - } - - public override Builder MergeFrom(Contacts other) - { - if (other == global::Contacts.DefaultInstance) return this; - PrepareBuilder(); - if (other.contactPoints_.Count != 0) - { - result.contactPoints_.Add(other.contactPoints_); - } - this.MergeUnknownFields(other.UnknownFields); - return this; - } - - public override Builder MergeFrom(pb::ICodedInputStream input) - { - return MergeFrom(input, pb::ExtensionRegistry.Empty); - } - - public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - PrepareBuilder(); - pb::UnknownFieldSet.Builder unknownFields = null; - uint tag; - string field_name; - while (input.ReadTag(out tag, out field_name)) - { - if (tag == 0 && field_name != null) - { - int field_ordinal = global::System.Array.BinarySearch(_contactsFieldNames, field_name, global::System.StringComparer.Ordinal); - if (field_ordinal >= 0) - tag = _contactsFieldTags[field_ordinal]; - else - { - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - continue; - } - } - switch (tag) - { - case 0: - { - throw pb::InvalidProtocolBufferException.InvalidTag(); - } - default: - { - if (pb::WireFormat.IsEndGroupTag(tag)) - { - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - break; - } - case 10: - { - input.ReadStringArray(tag, field_name, result.contactPoints_); - break; - } - } - } - - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - - - public pbc::IPopsicleList ContactPointsList - { - get { return PrepareBuilder().contactPoints_; } - } - public int ContactPointsCount - { - get { return result.ContactPointsCount; } - } - public string GetContactPoints(int index) - { - return result.GetContactPoints(index); - } - public Builder SetContactPoints(int index, string value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.contactPoints_[index] = value; - return this; - } - public Builder AddContactPoints(string value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.contactPoints_.Add(value); - return this; - } - public Builder AddRangeContactPoints(scg::IEnumerable values) - { - PrepareBuilder(); - result.contactPoints_.Add(values); - return this; - } - public Builder ClearContactPoints() - { - PrepareBuilder(); - result.contactPoints_.Clear(); - return this; - } - } - static Contacts() - { - object.ReferenceEquals(global::ClusterClientMessages.Descriptor, null); - } -} - -#endregion - - -#endregion Designer generated code diff --git a/src/contrib/cluster/Akka.Cluster.Tools/Client/reference.conf b/src/contrib/cluster/Akka.Cluster.Tools/Client/reference.conf deleted file mode 100644 index 797aeaabf82..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools/Client/reference.conf +++ /dev/null @@ -1,83 +0,0 @@ -############################################ -# Akka Cluster Tools Reference Config File # -############################################ - -# This is the reference config file that contains all the default settings. -# Make your edits/overrides in your application.conf. - - -# //#receptionist-ext-config -# Settings for the ClusterClientReceptionist extension -akka.cluster.client.receptionist { - # Actor name of the ClusterReceptionist actor, /system/receptionist - name = receptionist - - # Start the receptionist on members tagged with this role. - # All members are used if undefined or empty. - role = "" - - # The receptionist will send this number of contact points to the client - number-of-contacts = 3 - - # The actor that tunnel response messages to the client will be stopped - # after this time of inactivity. - response-tunnel-receive-timeout = 30s - - # The id of the dispatcher to use for ClusterReceptionist actors. - # If not specified default dispatcher is used. - # If specified you need to define the settings of the actual dispatcher. - use-dispatcher = "" -} -# //#receptionist-ext-config - -# //#cluster-client-config -# Settings for the ClusterClient -akka.cluster.client { - # Actor paths of the ClusterReceptionist actors on the servers (cluster nodes) - # that the client will try to contact initially. It is mandatory to specify - # at least one initial contact. - # Comma separated full actor paths defined by a string on the form of - # "akka.tcp://system@hostname:port/system/receptionist" - initial-contacts = [] - - # Interval at which the client retries to establish contact with one of - # ClusterReceptionist on the servers (cluster nodes) - establishing-get-contacts-interval = 3s - - # Interval at which the client will ask the ClusterReceptionist for - # new contact points to be used for next reconnect. - refresh-contacts-interval = 60s - - # How often failure detection heartbeat messages should be sent - heartbeat-interval = 2s - - # Number of potentially lost/delayed heartbeats that will be - # accepted before considering it to be an anomaly. - # The ClusterClient is using the akka.remote.DeadlineFailureDetector, which - # will trigger if there are no heartbeats within the duration - # heartbeat-interval + acceptable-heartbeat-pause, i.e. 15 seconds with - # the default settings. - acceptable-heartbeat-pause = 13s - - # If connection to the receptionist is not established the client will buffer - # this number of messages and deliver them the connection is established. - # When the buffer is full old messages will be dropped when new messages are sent - # via the client. Use 0 to disable buffering, i.e. messages will be dropped - # immediately if the location of the singleton is unknown. - # Maximum allowed buffer size is 10000. - buffer-size = 1000 -} -# //#cluster-client-config - -# Protobuf serializer for ClusterClient messages -akka.actor { - serializers { - akka-cluster-client = "Akka.Cluster.Tools.Client.Serialization.ClusterClientMessageSerializer, Akka.Cluster.Tools" - } - serialization-bindings { - "Akka.Cluster.Tools.Client.IClusterClientMessage, Akka.Cluster.Tools" = akka-cluster-client - } - serialization-identifiers { - "Akka.Cluster.Tools.Client.Serialization.ClusterClientMessageSerializer, Akka.Cluster.Tools" = 15 - } -} diff --git a/src/contrib/cluster/Akka.Cluster.Tools/Properties/AssemblyInfo.cs b/src/contrib/cluster/Akka.Cluster.Tools/Properties/AssemblyInfo.cs deleted file mode 100644 index 403721cd645..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Akka.Cluster.Tools")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Akka.Cluster.Tools")] -[assembly: AssemblyCopyright("Copyright © 2015")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("5cf8a8be-b634-473f-bb01-eba878746bd4")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/contrib/cluster/Akka.Cluster.Tools/PublishSubscribe/DistributedMessages.cs b/src/contrib/cluster/Akka.Cluster.Tools/PublishSubscribe/DistributedMessages.cs deleted file mode 100644 index cdae6fb6336..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools/PublishSubscribe/DistributedMessages.cs +++ /dev/null @@ -1,438 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using Akka.Actor; - -namespace Akka.Cluster.Tools.PublishSubscribe -{ - public static class Distributed - { - #region Messages - - [Serializable] - public sealed class Put : IEquatable - { - public readonly IActorRef Ref; - - public Put(IActorRef @ref) - { - Ref = @ref; - } - - public bool Equals(Put other) - { - if (ReferenceEquals(other, null)) return false; - if (ReferenceEquals(other, this)) return true; - return Equals(Ref, other.Ref); - } - - public override bool Equals(object obj) - { - return Equals(obj as Put); - } - - public override int GetHashCode() - { - return (Ref != null ? Ref.GetHashCode() : 0); - } - - public override string ToString() - { - return string.Format("Put", Ref); - } - } - - [Serializable] - public sealed class Remove : IEquatable - { - public readonly string Path; - - public Remove(string path) - { - Path = path; - } - - public bool Equals(Remove other) - { - if (ReferenceEquals(other, null)) return false; - if (ReferenceEquals(other, this)) return true; - return Equals(Path, other.Path); - } - - public override bool Equals(object obj) - { - return Equals(obj as Remove); - } - - public override int GetHashCode() - { - return (Path != null ? Path.GetHashCode() : 0); - } - - public override string ToString() - { - return string.Format("Remove", Path); - } - } - - [Serializable] - public sealed class Subscribe : IEquatable - { - public readonly string Topic; - public readonly string Group; - public readonly IActorRef Ref; - - public Subscribe(string topic, IActorRef @ref, string @group = null) - { - if (string.IsNullOrEmpty(topic)) throw new ArgumentException("topic must be defined"); - - Topic = topic; - Group = @group; - Ref = @ref; - } - - public bool Equals(Subscribe other) - { - if (ReferenceEquals(other, null)) return false; - if (ReferenceEquals(other, this)) return true; - return Equals(Topic, other.Topic) && - Equals(Group, other.Group) && - Equals(Ref, other.Ref); - } - - public override bool Equals(object obj) - { - return Equals(obj as Subscribe); - } - - public override int GetHashCode() - { - unchecked - { - var hashCode = (Topic != null ? Topic.GetHashCode() : 0); - hashCode = (hashCode * 397) ^ (Group != null ? Group.GetHashCode() : 0); - hashCode = (hashCode * 397) ^ (Ref != null ? Ref.GetHashCode() : 0); - return hashCode; - } - } - - public override string ToString() - { - return string.Format("Subscribe", Topic, Group, Ref); - } - } - - [Serializable] - public sealed class Unsubscribe : IEquatable - { - public readonly string Topic; - public readonly string Group; - public readonly IActorRef Ref; - - public Unsubscribe(string topic, IActorRef @ref, string @group = null) - { - if (string.IsNullOrEmpty(topic)) throw new ArgumentException("topic must be defined"); - - Topic = topic; - Group = @group; - Ref = @ref; - } - - public bool Equals(Unsubscribe other) - { - if (ReferenceEquals(other, null)) return false; - if (ReferenceEquals(other, this)) return true; - return Equals(Topic, other.Topic) && - Equals(Group, other.Group) && - Equals(Ref, other.Ref); - } - - public override bool Equals(object obj) - { - return Equals(obj as Unsubscribe); - } - - public override int GetHashCode() - { - unchecked - { - var hashCode = (Topic != null ? Topic.GetHashCode() : 0); - hashCode = (hashCode * 397) ^ (Group != null ? Group.GetHashCode() : 0); - hashCode = (hashCode * 397) ^ (Ref != null ? Ref.GetHashCode() : 0); - return hashCode; - } - } - - public override string ToString() - { - return string.Format("Unsubscribe", Topic, Group, Ref); - } - } - - [Serializable] - public sealed class SubscribeAck : IEquatable - { - public readonly Subscribe Subscribe; - - public SubscribeAck(Subscribe subscribe) - { - Subscribe = subscribe; - } - - public bool Equals(SubscribeAck other) - { - if (ReferenceEquals(other, null)) return false; - if (ReferenceEquals(other, this)) return true; - return Equals(Subscribe, other.Subscribe); - } - - public override bool Equals(object obj) - { - return Equals(obj as SubscribeAck); - } - - public override int GetHashCode() - { - return (Subscribe != null ? Subscribe.GetHashCode() : 0); - } - - public override string ToString() - { - return string.Format("SubscribeAck<{0}>", Subscribe); - } - } - - [Serializable] - public sealed class UnsubscribeAck : IEquatable - { - public readonly Unsubscribe Unsubscribe; - - public UnsubscribeAck(Unsubscribe unsubscribe) - { - Unsubscribe = unsubscribe; - } - - public bool Equals(UnsubscribeAck other) - { - if (ReferenceEquals(other, null)) return false; - if (ReferenceEquals(other, this)) return true; - return Equals(Unsubscribe, other.Unsubscribe); - } - - public override bool Equals(object obj) - { - return Equals(obj as UnsubscribeAck); - } - - public override int GetHashCode() - { - return (Unsubscribe != null ? Unsubscribe.GetHashCode() : 0); - } - - public override string ToString() - { - return string.Format("UnsubscribeAck<{0}>", Unsubscribe); - } - } - - [Serializable] - public sealed class Publish : IDistributedPubSubMessage, IEquatable - { - public readonly string Topic; - public readonly object Message; - public readonly bool SendOneMessageToEachGroup; - - public Publish(string topic, object message, bool sendOneMessageToEachGroup = false) - { - Topic = topic; - Message = message; - SendOneMessageToEachGroup = sendOneMessageToEachGroup; - } - - public bool Equals(Publish other) - { - if (ReferenceEquals(other, null)) return false; - if (ReferenceEquals(other, this)) return true; - return Equals(Topic, other.Topic) && - Equals(SendOneMessageToEachGroup, other.SendOneMessageToEachGroup) && - Equals(Message, other.Message); - } - - public override bool Equals(object obj) - { - return Equals(obj as Publish); - } - - public override int GetHashCode() - { - unchecked - { - var hashCode = (Topic != null ? Topic.GetHashCode() : 0); - hashCode = (hashCode * 397) ^ (Message != null ? Message.GetHashCode() : 0); - hashCode = (hashCode * 397) ^ SendOneMessageToEachGroup.GetHashCode(); - return hashCode; - } - } - - public override string ToString() - { - return string.Format("Publish", Topic, SendOneMessageToEachGroup, Message); - } - } - - [Serializable] - public sealed class Send : IDistributedPubSubMessage, IEquatable - { - public readonly string Path; - public readonly object Message; - public readonly bool LocalAffinity; - - public Send(string path, object message, bool localAffinity = false) - { - Path = path; - Message = message; - LocalAffinity = localAffinity; - } - - public bool Equals(Send other) - { - if (ReferenceEquals(other, null)) return false; - if (ReferenceEquals(other, this)) return true; - return Equals(Path, other.Path) && - Equals(LocalAffinity, other.LocalAffinity) && - Equals(Message, other.Message); - } - - public override bool Equals(object obj) - { - return Equals(obj as Send); - } - - public override int GetHashCode() - { - unchecked - { - var hashCode = (Path != null ? Path.GetHashCode() : 0); - hashCode = (hashCode * 397) ^ (Message != null ? Message.GetHashCode() : 0); - hashCode = (hashCode * 397) ^ LocalAffinity.GetHashCode(); - return hashCode; - } - } - - public override string ToString() - { - return string.Format("Send", Path, LocalAffinity, Message); - } - } - - [Serializable] - public sealed class SendToAll : IDistributedPubSubMessage, IEquatable - { - public readonly string Path; - public readonly object Message; - public readonly bool ExcludeSelf; - - public SendToAll(string path, object message, bool excludeSelf = false) - { - Path = path; - Message = message; - ExcludeSelf = excludeSelf; - } - - public bool Equals(SendToAll other) - { - if (ReferenceEquals(other, null)) return false; - if (ReferenceEquals(other, this)) return true; - return Equals(ExcludeSelf, other.ExcludeSelf) && - Equals(Path, other.Path) && - Equals(Message, other.Message); - } - - public override bool Equals(object obj) - { - return Equals(obj as SendToAll); - } - - public override int GetHashCode() - { - unchecked - { - var hashCode = (Path != null ? Path.GetHashCode() : 0); - hashCode = (hashCode * 397) ^ (Message != null ? Message.GetHashCode() : 0); - hashCode = (hashCode * 397) ^ ExcludeSelf.GetHashCode(); - return hashCode; - } - } - - public override string ToString() - { - return string.Format("SendToAll", Path, ExcludeSelf, Message); - } - } - - [Serializable] - public sealed class GetTopics : IEquatable - { - public static readonly GetTopics Instance = new GetTopics(); - private GetTopics() { } - - public bool Equals(GetTopics other) - { - if (other == null) return false; - return true; - } - - public override bool Equals(object obj) - { - return Equals(obj as GetTopics); - } - - public override string ToString() - { - return "GetTopics<>"; - } - } - - [Serializable] - public sealed class CurrentTopics : IEquatable - { - public readonly string[] Topics; - - public CurrentTopics(string[] topics) - { - Topics = topics ?? new string[0]; - } - - public bool Equals(CurrentTopics other) - { - if (ReferenceEquals(other, null)) return false; - if (ReferenceEquals(other, this)) return true; - - return Equals(Topics, other.Topics); - } - - public override bool Equals(object obj) - { - return Equals(obj as CurrentTopics); - } - - public override int GetHashCode() - { - return (Topics != null ? Topics.GetHashCode() : 0); - } - - public override string ToString() - { - return string.Format("CurrentTopics<{0}>", string.Join(",", Topics)); - } - } - - #endregion - - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Tools/PublishSubscribe/DistributedPubSub.cs b/src/contrib/cluster/Akka.Cluster.Tools/PublishSubscribe/DistributedPubSub.cs deleted file mode 100644 index 3bffc09310e..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools/PublishSubscribe/DistributedPubSub.cs +++ /dev/null @@ -1,93 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using Akka.Actor; -using Akka.Configuration; -using Akka.Dispatch; - -namespace Akka.Cluster.Tools.PublishSubscribe -{ - /// - /// Marker trait for remote messages with special serializer. - /// - public interface IDistributedPubSubMessage { } - - public class DistributedPubSubExtensionProvider : ExtensionIdProvider - { - public override DistributedPubSub CreateExtension(ExtendedActorSystem system) - { - return new DistributedPubSub(system); - } - } - - /// - /// Extension that starts a actor with settings - /// defined in config section `akka.cluster.pub-sub`. - /// - public class DistributedPubSub : IExtension - { - private readonly ExtendedActorSystem _system; - private readonly DistributedPubSubSettings _settings; - private readonly Cluster _cluster; - private readonly IActorRef _mediatorRef; - - public static DistributedPubSub Get(ActorSystem system) - { - return system.WithExtension(); - } - - public static Config DefaultConfig() - { - return ConfigurationFactory.FromResource("Akka.Cluster.Tools.PublishSubscribe.reference.conf"); - } - - public DistributedPubSub(ExtendedActorSystem system) - { - _system = system; - _system.Settings.InjectTopLevelFallback(DefaultConfig()); - _settings = DistributedPubSubSettings.Create(system); - _cluster = Cluster.Get(_system); - _mediatorRef = CreateMediator(); - } - - /// - /// Returns true if this member is not tagged with the role configured for the mediator. - /// - public bool IsTerminated - { - get - { - return _cluster.IsTerminated || !(string.IsNullOrEmpty(_settings.Role) || _cluster.SelfRoles.Contains(_settings.Role)); - } - } - - /// - /// The actor reference. - /// - public IActorRef Mediator - { - get - { - return IsTerminated ? _system.DeadLetters : _mediatorRef; - } - } - - private IActorRef CreateMediator() - { - var name = _system.Settings.Config.GetString("akka.cluster.pub-sub.name"); - var dispatcher = _system.Settings.Config.GetString("akka.cluster.pub-sub.use-dispatcher"); - if (string.IsNullOrEmpty(dispatcher)) - dispatcher = Dispatchers.DefaultDispatcherId; - - return _system.SystemActorOf( - Props.Create(() => new DistributedPubSubMediator(_settings)) - .WithDeploy(Deploy.Local) - .WithDispatcher(dispatcher), - name); - } - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Tools/PublishSubscribe/DistributedPubSubMediator.cs b/src/contrib/cluster/Akka.Cluster.Tools/PublishSubscribe/DistributedPubSubMediator.cs deleted file mode 100644 index cabc2647e25..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools/PublishSubscribe/DistributedPubSubMediator.cs +++ /dev/null @@ -1,544 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Linq; -using Akka.Actor; -using Akka.Cluster.Tools.PublishSubscribe.Internal; -using Akka.Event; -using Akka.Pattern; -using Akka.Routing; -using Akka.Util; -using Status = Akka.Cluster.Tools.PublishSubscribe.Internal.Status; - -namespace Akka.Cluster.Tools.PublishSubscribe -{ - - /// - /// - /// This actor manages a registry of actor references and replicates - /// the entries to peer actors among all cluster nodes or a group of nodes - /// tagged with a specific role. - /// - /// - /// The is supposed to be started on all nodes, - /// or all nodes with specified role, in the cluster. The mediator can be - /// started with the extension or as an ordinary actor. - /// - /// - /// Changes are only performed in the own part of the registry and those changes - /// are versioned. Deltas are disseminated in a scalable way to other nodes with - /// a gossip protocol. The registry is eventually consistent, i.e. changes are not - /// immediately visible at other nodes, but typically they will be fully replicated - /// to all other nodes after a few seconds. - /// - /// - /// You can send messages via the mediator on any node to registered actors on - /// any other node. There is three modes of message delivery. - /// - /// - /// 1. - - /// The message will be delivered to one recipient with a matching path, if any such - /// exists in the registry. If several entries match the path the message will be sent - /// via the supplied `routingLogic` (default random) to one destination. The sender of the - /// message can specify that local affinity is preferred, i.e. the message is sent to an actor - /// in the same local actor system as the used mediator actor, if any such exists, otherwise - /// route to any other matching entry. A typical usage of this mode is private chat to one - /// other user in an instant messaging application. It can also be used for distributing - /// tasks to registered workers, like a cluster aware router where the routees dynamically - /// can register themselves. - /// - /// - /// 2. - - /// The message will be delivered to all recipients with a matching path. Actors with - /// the same path, without address information, can be registered on different nodes. - /// On each node there can only be one such actor, since the path is unique within one - /// local actor system. Typical usage of this mode is to broadcast messages to all replicas - /// with the same path, e.g. 3 actors on different nodes that all perform the same actions, - /// for redundancy. - /// - /// - /// 3. - - /// Actors may be registered to a named topic instead of path. This enables many subscribers - /// on each node. The message will be delivered to all subscribers of the topic. For - /// efficiency the message is sent over the wire only once per node (that has a matching topic), - /// and then delivered to all subscribers of the local topic representation. This is the - /// true pub/sub mode. A typical usage of this mode is a chat room in an instant messaging - /// application. - /// - /// - /// 4. with sendOneMessageToEachGroup - - /// Actors may be subscribed to a named topic with an optional property `group`. - /// If subscribing with a group name, each message published to a topic with the - /// `sendOneMessageToEachGroup` flag is delivered via the supplied `routingLogic` - /// (default random) to one actor within each subscribing group. - /// If all the subscribed actors have the same group name, then this works just like - /// and all messages are delivered to one subscribe. - /// If all the subscribed actors have different group names, then this works like normal - /// and all messages are broadcast to all subscribers. - /// - /// - /// You register actors to the local mediator with or - /// . `Put` is used together with `Send` and - /// `SendToAll` message delivery modes. The `ActorRef` in `Put` must belong to the same - /// local actor system as the mediator. `Subscribe` is used together with `Publish`. - /// Actors are automatically removed from the registry when they are terminated, or you - /// can explicitly remove entries with or - /// . - /// - /// - /// Successful `Subscribe` and `Unsubscribe` is acknowledged with - /// and - /// replies. - /// - /// - public class DistributedPubSubMediator : ReceiveActor - { - public static Props Props(DistributedPubSubSettings settings) - { - return Actor.Props.Create(() => new DistributedPubSubMediator(settings)).WithDeploy(Deploy.Local); - } - - private readonly Cluster _cluster = Cluster.Get(Context.System); - private readonly DistributedPubSubSettings _settings; - private readonly ICancelable _gossipCancelable; - private readonly ICancelable _pruneCancelable; - private readonly TimeSpan _pruneInterval; - - private ISet
_nodes = new HashSet
(); - private ILoggingAdapter _log; - private IDictionary _registry = new Dictionary(); - - public ILoggingAdapter Log { get { return _log ?? (_log = Context.GetLogger()); } } - - public IDictionary OwnVersions - { - get - { - return _registry - .Select(entry => new KeyValuePair(entry.Key, entry.Value.Version)) - .ToDictionary(kv => kv.Key, kv => kv.Value); - } - } - - public DistributedPubSubMediator(DistributedPubSubSettings settings) - { - if (settings.RoutingLogic is ConsistentHashingRoutingLogic) - throw new ArgumentException("Consistent hashing routing logic cannot be used by the pub-sub mediator"); - - _settings = settings; - - if (!string.IsNullOrEmpty(_settings.Role) && !_cluster.SelfRoles.Contains(_settings.Role)) - throw new ArgumentException(string.Format("The cluster member [{0}] doesn't have the role [{1}]", _cluster.SelfAddress, _settings.Role)); - - //Start periodic gossip to random nodes in cluster - _gossipCancelable = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(_settings.GossipInterval, _settings.GossipInterval, Self, GossipTick.Instance, Self); - _pruneInterval = new TimeSpan(_settings.RemovedTimeToLive.Ticks / 2); - _pruneCancelable = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(_pruneInterval, _pruneInterval, Self, Prune.Instance, Self); - - Receive(send => - { - var routees = new List(); - - Bucket bucket; - if (_registry.TryGetValue(_cluster.SelfAddress, out bucket)) - { - ValueHolder valueHolder; - if (bucket.Content.TryGetValue(send.Path, out valueHolder) && send.LocalAffinity) - { - var routee = valueHolder.Routee; - if (routee != null) routees.Add(routee); - } - else - { - foreach (var entry in _registry) - { - if (entry.Value.Content.TryGetValue(send.Path, out valueHolder)) - { - var routee = valueHolder.Routee; - if (routee != null) routees.Add(routee); - } - } - } - } - - if (routees.Count != 0) - { - new Router(_settings.RoutingLogic, routees.ToArray()).Route(Utils.WrapIfNeeded(send.Message), Sender); - } - }); - Receive(sendToAll => - { - PublishMessage(sendToAll.Path, sendToAll.Message, sendToAll.ExcludeSelf); - }); - Receive(publish => - { - var topic = Uri.EscapeDataString(publish.Topic); - var path = Self.Path / topic; - if (publish.SendOneMessageToEachGroup) - PublishToEachGroup(path.ToStringWithoutAddress(), publish.Message); - else - PublishMessage(path.ToStringWithoutAddress(), publish.Message); - }); - Receive(put => - { - if (!string.IsNullOrEmpty(put.Ref.Path.Address.Host)) - Log.Warning("Registered actor must be local: [{0}]", put.Ref); - else - { - PutToRegistry(put.Ref.Path.ToStringWithoutAddress(), put.Ref); - Context.Watch(put.Ref); - } - }); - Receive(remove => - { - Bucket bucket; - if (_registry.TryGetValue(_cluster.SelfAddress, out bucket)) - { - ValueHolder valueHolder; - if (bucket.Content.TryGetValue(remove.Path, out valueHolder) && valueHolder.Ref != null) - { - Context.Unwatch(valueHolder.Ref); - PutToRegistry(remove.Path, null); - } - } - }); - Receive(subscribe => - { - // each topic is managed by a child actor with the same name as the topic - var topic = Uri.EscapeDataString(subscribe.Topic); - var child = Context.Child(topic); - if (!ActorRefs.Nobody.Equals(child)) - { - child.Forward(subscribe); - } - else - { - var t = Context.ActorOf(Actor.Props.Create(() => - new Topic(_settings.RemovedTimeToLive, _settings.RoutingLogic)), topic); - t.Forward(subscribe); - HandleRegisterTopic(t); - } - }); - Receive(register => - { - HandleRegisterTopic(register.TopicRef); - }); - Receive(getTopics => - { - Sender.Tell(new Distributed.CurrentTopics(GetCurrentTopics().ToArray())); - }); - Receive(subscribed => - { - subscribed.Subscriber.Tell(subscribed.Ack); - }); - Receive(unsubscribe => - { - var topic = Uri.EscapeDataString(unsubscribe.Topic); - var child = Context.Child(topic); - if (!ActorRefs.Nobody.Equals(child)) - child.Forward(unsubscribe); - }); - Receive(unsubscribed => - { - unsubscribed.Subscriber.Tell(unsubscribed.Ack); - }); - Receive(status => - { - // gossip chat starts with a Status message, containing the bucket versions of the other node - var delta = CollectDelta(status.Versions).ToArray(); - if (delta.Length != 0) - Sender.Tell(new Delta(delta)); - - if (OtherHasNewerVersions(status.Versions)) - Sender.Tell(new Status(OwnVersions)); - }); - Receive(delta => - { - // reply from Status message in the gossip chat - // the Delta contains potential updates (newer versions) from the other node - // only accept deltas/buckets from known nodes, otherwise there is a risk of - // adding back entries when nodes are removed - if (_nodes.Contains(Sender.Path.Address)) - { - foreach (var bucket in delta.Buckets) - { - if (_nodes.Contains(bucket.Owner)) - { - Bucket myBucket; - if (!_registry.TryGetValue(bucket.Owner, out myBucket)) - myBucket = new Bucket(bucket.Owner); - - if (bucket.Version > myBucket.Version) - { - _registry.Add(bucket.Owner, new Bucket(myBucket.Owner, bucket.Version, myBucket.Content.AddRange(bucket.Content))); - } - } - } - } - }); - Receive(_ => HandleGossip()); - Receive(_ => HandlePrune()); - Receive(terminated => - { - var key = terminated.ActorRef.Path.ToStringWithoutAddress(); - - Bucket bucket; - if (_registry.TryGetValue(_cluster.SelfAddress, out bucket)) - { - ValueHolder holder; - if (bucket.Content.TryGetValue(key, out holder) && terminated.ActorRef.Equals(holder.Ref)) - { - PutToRegistry(key, null); // remove - } - } - }); - Receive(state => - { - var nodes = state.Members - .Where(m => m.Status != MemberStatus.Joining && IsMatchingRole(m)) - .Select(m => m.Address); - - _nodes = new HashSet
(nodes); - }); - Receive(up => - { - if (IsMatchingRole(up.Member)) _nodes.Add(up.Member.Address); - }); - Receive(removed => - { - var member = removed.Member; - if (member.Address == _cluster.SelfAddress) - { - Context.Stop(Self); - } - else if (IsMatchingRole(member)) - { - _nodes.Remove(member.Address); - _registry.Remove(member.Address); - } - }); - Receive(_ => { /* ignore */ }); - Receive(_ => - { - var count = _registry.Sum(entry => entry.Value.Content.Count(kv => kv.Value.Ref != null)); - Sender.Tell(count); - }); - } - - private bool OtherHasNewerVersions(IDictionary versions) - { - return versions.Any(entry => - { - Bucket bucket; - return (!_registry.TryGetValue(entry.Key, out bucket) && entry.Value > bucket.Version) - || entry.Value > 0L; - }); - } - - private IEnumerable CollectDelta(IDictionary versions) - { - // missing entries are represented by version 0 - var filledOtherVersions = new Dictionary(versions); - foreach (var entry in OwnVersions) - if (filledOtherVersions.ContainsKey(entry.Key)) - filledOtherVersions[entry.Key] = 0L; - else - filledOtherVersions.Add(entry.Key, 0L); - - var count = 0; - foreach (var entry in filledOtherVersions) - { - var owner = entry.Key; - var v = entry.Value; - - Bucket bucket; - if (!_registry.TryGetValue(owner, out bucket)) - bucket = new Bucket(owner); - - if (bucket.Version > v && count < _settings.MaxDeltaElements) - { - var deltaContent = bucket.Content - .Where(kv => kv.Value.Version > v) - .Aggregate(ImmutableDictionary.Empty, - (current, kv) => current.SetItem(kv.Key, kv.Value)); - - count += deltaContent.Count; - - if (count <= _settings.MaxDeltaElements) - yield return new Bucket(bucket.Owner, bucket.Version, deltaContent); - else - { - // exceeded the maxDeltaElements, pick the elements with lowest versions - var sortedContent = deltaContent.OrderBy(x => x.Value.Version).ToArray(); - var chunk = sortedContent.Take(_settings.MaxDeltaElements - (count - sortedContent.Length)).ToList(); - var content = chunk.Aggregate(ImmutableDictionary.Empty, - (current, kv) => current.SetItem(kv.Key, kv.Value)); - - yield return new Bucket(bucket.Owner, chunk.Last().Value.Version, content); - } - } - } - } - - private IEnumerable GetCurrentTopics() - { - var topicPrefix = Self.Path.ToStringWithoutAddress(); - foreach (var entry in _registry) - { - var bucket = entry.Value; - foreach (var kv in bucket.Content) - { - var key = kv.Key; - var value = kv.Value; - if (key.StartsWith(topicPrefix)) - { - var topic = key.Substring(topicPrefix.Length + 1); - if (!topic.Contains("/")) - { - yield return Uri.EscapeDataString(topic); - } - } - } - } - } - - private void HandleRegisterTopic(IActorRef actorRef) - { - PutToRegistry(actorRef.Path.ToStringWithoutAddress(), actorRef); - Context.Watch(actorRef); - } - - private void PutToRegistry(string key, IActorRef value) - { - var v = NextVersion(); - Bucket bucket; - if (!_registry.TryGetValue(_cluster.SelfAddress, out bucket)) - { - _registry.Add(_cluster.SelfAddress, - new Bucket(_cluster.SelfAddress, v, ImmutableDictionary.Empty.Add(key, new ValueHolder(v, value)))); - } - else - { - _registry[_cluster.SelfAddress] = new Bucket(bucket.Owner, v, bucket.Content.Add(key, new ValueHolder(v, value))); - } - } - - private void PublishMessage(string path, object message, bool excludeSelf = false) - { - foreach (var entry in _registry) - { - var address = entry.Key; - var bucket = entry.Value; - - if (!(excludeSelf && address == _cluster.SelfAddress)) - { - var valueHolder = bucket.Content[path]; - if (valueHolder != null && !valueHolder.Ref.Equals(ActorRefs.Nobody)) - { - valueHolder.Ref.Forward(message); - } - } - } - } - - private void PublishToEachGroup(string path, object message) - { - var prefix = path + "/"; - var lastKey = path + "0"; // '0' is the next char of '/' - - var groups = ExtractGroups(prefix, lastKey).GroupBy(kv => kv.Key); - var wrappedMessage = new SendToOneSubscriber(message); - - foreach (var g in groups) - { - var routees = g.Select(r => r.Value).ToArray(); - if (routees.Length != 0) - new Router(_settings.RoutingLogic, routees).Route(wrappedMessage, Sender); - } - } - - private IEnumerable> ExtractGroups(string prefix, string lastKey) - { - foreach (var bucket in _registry.Values) - { - //TODO: optimize into tree-aware key range [prefix, lastKey] - foreach (var keyVal in bucket.Content.Where(kv => kv.Key.CompareTo(prefix) != -1 && kv.Key.CompareTo(lastKey) != 1)) - { - yield return new KeyValuePair(keyVal.Key, keyVal.Value.Routee); - } - } - } - - private void HandlePrune() - { - foreach (var entry in _registry) - { - var owner = entry.Key; - var bucket = entry.Value; - - var oldRemoved = bucket.Content - .Where(kv => (bucket.Version - kv.Value.Version) > _settings.RemovedTimeToLive.TotalMilliseconds) - .Select(kv => kv.Key); - - if (oldRemoved.Any()) - { - _registry.Add(owner, new Bucket(bucket.Owner, bucket.Version, bucket.Content.RemoveRange(oldRemoved))); - } - } - } - - private void HandleGossip() - { - var node = SelectRandomNode(_nodes.Except(new[] { _cluster.SelfAddress }).ToArray()); - if (node != null) - GossipTo(node); - } - - private void GossipTo(Address address) - { - Context.ActorSelection(Self.Path.ToStringWithAddress(address)).Tell(new Status(OwnVersions)); - } - - private Address SelectRandomNode(IList
addresses) - { - if (addresses == null || addresses.Count == 0) return null; - return addresses[ThreadLocalRandom.Current.Next(addresses.Count)]; - } - - protected override void PreStart() - { - base.PreStart(); - if (_cluster.IsTerminated) throw new IllegalStateException("Cluster node must not be terminated"); - _cluster.Subscribe(Self, new[] { typeof(ClusterEvent.IMemberEvent) }); - } - - protected override void PostStop() - { - base.PostStop(); - _cluster.Unsubscribe(Self); - _gossipCancelable.Cancel(); - _pruneCancelable.Cancel(); - } - - private bool IsMatchingRole(Member member) - { - return string.IsNullOrEmpty(_settings.Role) || member.HasRole(_settings.Role); - } - - // the version is a timestamp because it is also used when pruning removed entries - private long _version = 0L; - private long NextVersion() - { - var current = DateTime.UtcNow.TimeOfDay.Ticks; - _version = current > _version ? current : _version + 1; - return _version; - } - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Tools/PublishSubscribe/DistributedPubSubSettings.cs b/src/contrib/cluster/Akka.Cluster.Tools/PublishSubscribe/DistributedPubSubSettings.cs deleted file mode 100644 index 7ab551f7b26..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools/PublishSubscribe/DistributedPubSubSettings.cs +++ /dev/null @@ -1,124 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using Akka.Actor; -using Akka.Configuration; -using Akka.Routing; - -namespace Akka.Cluster.Tools.PublishSubscribe -{ - public class DistributedPubSubSettings - { - /// - /// Creates cluster publish/subscribe settings from the default configuration `akka.cluster.pub-sub`. - /// - public static DistributedPubSubSettings Create(ActorSystem system) - { - var config = system.Settings.Config.GetConfig("akka.cluster.pub-sub"); - if (config == null) throw new ArgumentException("Actor system settings has no configuration for akka.cluster.pub-sub defined"); - - return Create(config); - } - - /// - /// Creates cluster publish subscribe settings from provided configuration with the same layout as `akka.cluster.pub-sub`. - /// - public static DistributedPubSubSettings Create(Config config) - { - RoutingLogic routingLogic = null; - var routingLogicName = config.GetString("routing-logic"); - switch (routingLogicName) - { - case "random": - routingLogic = new RandomLogic(); - break; - case "round-robin": - routingLogic = new RoundRobinRoutingLogic(); - break; - case "broadcast": - routingLogic = new BroadcastRoutingLogic(); - break; - case "consistent-hashing": - throw new ArgumentException("Consistent hashing routing logic cannot be used by the pub-sub mediator"); - default: - throw new ArgumentException("Unknown routing logic is tried to be applied to the pub-sub mediator: " + - routingLogicName); - } - - return new DistributedPubSubSettings( - config.GetString("role"), - routingLogic, - config.GetTimeSpan("gossip-interval"), - config.GetTimeSpan("removed-time-to-live"), - config.GetInt("max-delta-elements")); - } - - /// - /// The mediator starts on members tagged with this role. Uses all if undefined. - /// - public readonly string Role; - - /// - /// The routing logic to use for . - /// - public readonly RoutingLogic RoutingLogic; - - /// - /// How often the should send out gossip information - /// - public readonly TimeSpan GossipInterval; - - /// - /// Removed entries are pruned after this duration. - /// - public readonly TimeSpan RemovedTimeToLive; - - /// - /// Maximum number of elements to transfer in one message when synchronizing the registries. - /// Next chunk will be transferred in next round of gossip. - /// - public readonly int MaxDeltaElements; - - /// - /// Creates a new instance of the . - /// - public DistributedPubSubSettings(string role, RoutingLogic routingLogic, TimeSpan gossipInterval, TimeSpan removedTimeToLive, int maxDeltaElements) - { - Role = !string.IsNullOrEmpty(role) ? role : null; - RoutingLogic = routingLogic; - GossipInterval = gossipInterval; - RemovedTimeToLive = removedTimeToLive; - MaxDeltaElements = maxDeltaElements; - } - - public DistributedPubSubSettings WithRole(string role) - { - return new DistributedPubSubSettings(role, RoutingLogic, GossipInterval, RemovedTimeToLive, MaxDeltaElements); - } - - public DistributedPubSubSettings WithRoutingLogic(RoutingLogic routingLogic) - { - return new DistributedPubSubSettings(Role, routingLogic, GossipInterval, RemovedTimeToLive, MaxDeltaElements); - } - - public DistributedPubSubSettings WithGossipInterval(TimeSpan gossipInterval) - { - return new DistributedPubSubSettings(Role, RoutingLogic, gossipInterval, RemovedTimeToLive, MaxDeltaElements); - } - - public DistributedPubSubSettings WithRemovedTimeToLive(TimeSpan removedTtl) - { - return new DistributedPubSubSettings(Role, RoutingLogic, GossipInterval, removedTtl, MaxDeltaElements); - } - - public DistributedPubSubSettings WithMaxDeltaElements(int maxDeltaElements) - { - return new DistributedPubSubSettings(Role, RoutingLogic, GossipInterval, RemovedTimeToLive, maxDeltaElements); - } - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Tools/PublishSubscribe/Internal/TopicMessages.cs b/src/contrib/cluster/Akka.Cluster.Tools/PublishSubscribe/Internal/TopicMessages.cs deleted file mode 100644 index 84bef4f2f53..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools/PublishSubscribe/Internal/TopicMessages.cs +++ /dev/null @@ -1,150 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using Akka.Actor; -using Akka.Routing; - -namespace Akka.Cluster.Tools.PublishSubscribe.Internal -{ - [Serializable] - public sealed class Prune - { - public static readonly Prune Instance = new Prune(); - private Prune() { } - } - - // Only for testing purposes, to poll/await replication - public sealed class Count - { - public static readonly Count Instance = new Count(); - private Count() { } - } - - [Serializable] - public struct Bucket - { - public readonly Address Owner; - public readonly long Version; - public readonly IImmutableDictionary Content; - - public Bucket(Address owner) : this(owner, 0L, ImmutableDictionary.Empty) - { - } - - public Bucket(Address owner, long version, IImmutableDictionary content) : this() - { - Owner = owner; - Version = version; - Content = content; - } - } - - [Serializable] - public sealed class ValueHolder - { - public readonly long Version; - public readonly IActorRef Ref; - - [NonSerialized] - private Routee _routee; - - public ValueHolder(long version, IActorRef @ref) - { - Version = version; - Ref = @ref; - } - - public Routee Routee { get { return _routee ?? (_routee = Ref != null ? new ActorRefRoutee(Ref) : null); } } - } - - [Serializable] - public sealed class Status : IDistributedPubSubMessage - { - public readonly IDictionary Versions; - - public Status(IDictionary versions) - { - Versions = versions ?? new Dictionary(0); - } - } - - [Serializable] - public sealed class Delta : IDistributedPubSubMessage - { - public readonly Bucket[] Buckets; - - public Delta(Bucket[] buckets) - { - Buckets = buckets ?? new Bucket[0]; - } - } - - [Serializable] - public sealed class GossipTick - { - public static readonly GossipTick Instance = new GossipTick(); - - private GossipTick() { } - } - - [Serializable] - public sealed class RegisterTopic - { - public readonly IActorRef TopicRef; - - public RegisterTopic(IActorRef topicRef) - { - TopicRef = topicRef; - } - } - - [Serializable] - public sealed class Subscribed - { - public readonly Distributed.SubscribeAck Ack; - public readonly IActorRef Subscriber; - - public Subscribed(Distributed.SubscribeAck ack, IActorRef subscriber) - { - Ack = ack; - Subscriber = subscriber; - } - } - - [Serializable] - public sealed class Unsubscribed - { - public readonly Distributed.UnsubscribeAck Ack; - public readonly IActorRef Subscriber; - - public Unsubscribed(Distributed.UnsubscribeAck ack, IActorRef subscriber) - { - Ack = ack; - Subscriber = subscriber; - } - } - - [Serializable] - public sealed class SendToOneSubscriber - { - public readonly object Message; - - public SendToOneSubscriber(object message) - { - Message = message; - } - } - - [Serializable] - public sealed class MediatorRouterEnvelope : RouterEnvelope - { - public MediatorRouterEnvelope(object message) : base(message) { } - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Tools/PublishSubscribe/Internal/Topics.cs b/src/contrib/cluster/Akka.Cluster.Tools/PublishSubscribe/Internal/Topics.cs deleted file mode 100644 index 3af46f25646..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools/PublishSubscribe/Internal/Topics.cs +++ /dev/null @@ -1,199 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using System.Collections.Generic; -using System.Linq; -using Akka.Actor; -using Akka.Remote; -using Akka.Routing; - -namespace Akka.Cluster.Tools.PublishSubscribe.Internal -{ - public abstract class TopicLike : ActorBase - { - protected readonly TimeSpan PruneInterval; - protected readonly ICancelable PruneCancelable; - protected readonly ISet Subscribers; - protected readonly TimeSpan EmptyTimeToLive; - - protected Deadline PruneDeadline = null; - - protected TopicLike(TimeSpan emptyTimeToLive) - { - Subscribers = new HashSet(); - EmptyTimeToLive = emptyTimeToLive; - PruneInterval = new TimeSpan(emptyTimeToLive.Ticks / 2); - PruneCancelable = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(PruneInterval, PruneInterval, Self, Prune.Instance, Self); - } - - protected override void PostStop() - { - base.PostStop(); - PruneCancelable.Cancel(); - } - - protected bool DefaultReceive(object message) - { - if (message is Distributed.Subscribe) - { - var subscribe = (Distributed.Subscribe)message; - - Context.Watch(subscribe.Ref); - Subscribers.Add(subscribe.Ref); - PruneDeadline = null; - Context.Parent.Tell(new Subscribed(new Distributed.SubscribeAck(subscribe), Sender)); - } - else if (message is Distributed.Unsubscribe) - { - var unsubscribe = (Distributed.Unsubscribe)message; - - Context.Unwatch(unsubscribe.Ref); - Remove(unsubscribe.Ref); - Context.Parent.Tell(new Unsubscribed(new Distributed.UnsubscribeAck(unsubscribe), Sender)); - } - else if (message is Terminated) - { - var terminated = (Terminated)message; - Remove(terminated.ActorRef); - } - else if (message is Prune) - { - if (PruneDeadline != null && PruneDeadline.IsOverdue) Context.Stop(Self); - } - else - { - foreach (var subscriber in Subscribers) - subscriber.Forward(message); - } - - return true; - } - - protected abstract bool Business(object message); - - protected override bool Receive(object message) - { - return Business(message) || DefaultReceive(message); - } - - private void Remove(IActorRef actorRef) - { - Subscribers.Remove(actorRef); - - if (Subscribers.Count == 0 && !Context.GetChildren().Any()) - { - PruneDeadline = Deadline.Now + EmptyTimeToLive; - } - } - } - - public class Topic : TopicLike - { - private readonly RoutingLogic _routingLogic; - - public Topic(TimeSpan emptyTimeToLive, RoutingLogic routingLogic) : base(emptyTimeToLive) - { - _routingLogic = routingLogic; - } - - protected override bool Business(object message) - { - Distributed.Subscribe subscribe; - Distributed.Unsubscribe unsubscribe; - if ((subscribe = message as Distributed.Subscribe) != null && subscribe.Group != null) - { - var encodedGroup = Encode(subscribe.Group); - var child = encodedGroup == null ? ActorRefs.Nobody : Context.Child(encodedGroup); - - if (!ActorRefs.Nobody.Equals(child)) - { - child.Forward(message); - } - else - { - var group = Context.ActorOf(Props.Create(() => new Group(EmptyTimeToLive, _routingLogic)), encodedGroup); - group.Forward(message); - Context.Watch(group); - Context.Parent.Tell(new RegisterTopic(group)); - } - - PruneDeadline = null; - } - else if ((unsubscribe = message as Distributed.Unsubscribe) != null && unsubscribe.Group != null) - { - var encodedGroup = Encode(unsubscribe.Group); - var child = encodedGroup == null ? ActorRefs.Nobody : Context.Child(encodedGroup); - - if (!child.Equals(ActorRefs.Nobody)) - { - child.Forward(message); - } - } - else if (message is Subscribed) - { - Context.Parent.Forward(message); - } - else if (message is Unsubscribed) - { - Context.Parent.Forward(message); - } - else return false; - return true; - } - - private static string Encode(string name) - { - return name == null ? null : Uri.EscapeDataString(name); - } - } - - public class Group : TopicLike - { - private readonly RoutingLogic _routingLogic; - - public Group(TimeSpan emptyTimeToLive, RoutingLogic routingLogic) : base(emptyTimeToLive) - { - _routingLogic = routingLogic; - } - - protected override bool Business(object message) - { - if (message is SendToOneSubscriber) - { - if (Subscribers.Count != 0) - { - var send = (SendToOneSubscriber)message; - var routees = Subscribers.Select(sub => (Routee)new ActorRefRoutee(sub)).ToArray(); - new Router(_routingLogic, routees).Route(Utils.WrapIfNeeded(send.Message), Sender); - } - } - else return false; - return true; - } - } - - public static class Utils - { - /// - /// - /// Mediator uses to send messages to multiple destinations, Router in general - /// unwraps messages from and sends the contents to s. - /// - /// - /// Using mediator services should not have an undesired effect of unwrapping messages - /// out of . For this reason user messages are wrapped in - /// which will be unwrapped by the leaving original - /// user message. - /// - /// - public static object WrapIfNeeded(object message) - { - return message is RouterEnvelope ? new MediatorRouterEnvelope(message) : message; - } - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Tools/PublishSubscribe/Serialization/DistributedPubSubMessageSerializer.cs b/src/contrib/cluster/Akka.Cluster.Tools/PublishSubscribe/Serialization/DistributedPubSubMessageSerializer.cs deleted file mode 100644 index 72d251039d9..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools/PublishSubscribe/Serialization/DistributedPubSubMessageSerializer.cs +++ /dev/null @@ -1,288 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.IO; -using System.IO.Compression; -using System.Linq; -using Akka.Actor; -using Akka.Cluster.PubSub.Serializers.Proto; -using Akka.Cluster.Tools.PublishSubscribe.Internal; -using Akka.Serialization; -using Google.ProtocolBuffers; -using Address = Akka.Cluster.PubSub.Serializers.Proto.Address; -using Delta = Akka.Cluster.Tools.PublishSubscribe.Internal.Delta; -using Status = Akka.Cluster.PubSub.Serializers.Proto.Status; - -namespace Akka.Cluster.Tools.PublishSubscribe.Serialization -{ - /** - * Protobuf serializer of DistributedPubSubMediator messages. - */ - public class DistributedPubSubMessageSerializer : SerializerWithStringManifest - { - public const int BufferSize = 1024 * 4; - - public const string StatusManifest = "A"; - public const string DeltaManifest = "B"; - public const string SendManifest = "C"; - public const string SendToAllManifest = "D"; - public const string PublishManifest = "E"; - - private readonly IDictionary> _fromBinaryMap; - - private readonly int _identifier; - - public DistributedPubSubMessageSerializer(ExtendedActorSystem system) : base(system) - { - _identifier = SerializerIdentifierHelper.GetSerializerIdentifierFromConfig(this.GetType(), system); - _fromBinaryMap = new Dictionary> - { - {StatusManifest, StatusFromBinary}, - {DeltaManifest, DeltaFromBinary}, - {SendManifest, SendFromBinary}, - {SendToAllManifest, SendToAllFromBinary}, - {PublishManifest, PublishFromBinary} - }; - } - - public override int Identifier { get { return _identifier; } } - - public override byte[] ToBinary(object obj) - { - if (obj is Internal.Status) return Compress(StatusToProto(obj as Internal.Status)); - else if (obj is Internal.Delta) return Compress(DeltaToProto(obj as Internal.Delta)); - else if (obj is Distributed.Send) return SendToProto(obj as Distributed.Send).ToByteArray(); - else if (obj is Distributed.SendToAll) return SendToAllToProto(obj as Distributed.SendToAll).ToByteArray(); - else if (obj is Distributed.Publish) return PublishToProto(obj as Distributed.Publish).ToByteArray(); - else throw new ArgumentException(string.Format("Can't serialize object of type {0} with {1}", obj.GetType(), GetType())); - } - - public override object FromBinary(byte[] bytes, string manifestString) - { - Func deserializer; - if (_fromBinaryMap.TryGetValue(manifestString, out deserializer)) - { - return deserializer(bytes); - } - else - throw new ArgumentException(string.Format("Unimplemented deserialization of message with manifest [{0}] in serializer {1}", manifestString, GetType())); - } - - public override string Manifest(object o) - { - if (o is Internal.Status) return StatusManifest; - if (o is Internal.Delta) return DeltaManifest; - if (o is Distributed.Send) return SendManifest; - if (o is Distributed.SendToAll) return SendToAllManifest; - if (o is Distributed.Publish) return PublishManifest; - - throw new ArgumentException(string.Format("Serializer {0} cannot serialize message of type {1}", this.GetType(), o.GetType())); - } - - private byte[] Compress(IMessageLite proto) - { - using (var memStream = new MemoryStream(BufferSize)) - using (var gzip = new GZipStream(memStream, CompressionLevel.Fastest)) - { - proto.WriteTo(gzip); - gzip.Flush(); - memStream.Position = 0; - return memStream.ToArray(); - } - } - - private byte[] Decompress(byte[] binary) - { - using (var memStream = new MemoryStream(binary)) - using (var gzip = new GZipStream(memStream, CompressionLevel.Fastest)) - using (var outStream = new MemoryStream(BufferSize)) - { - gzip.CopyTo(outStream); - return outStream.ToArray(); - } - } - - private Address.Builder AddressToProto(Actor.Address address) - { - if (string.IsNullOrEmpty(address.Host) || !address.Port.HasValue) - throw new ArgumentException(string.Format("Address [{0}] could not be serialized: host or port missing", address)); - - return Address.CreateBuilder() - .SetSystem(address.System) - .SetHostname(address.Host) - .SetPort((uint)address.Port.Value) - .SetProtocol(address.Protocol); - } - - private Actor.Address AddressFromProto(Address address) - { - return new Actor.Address(address.Protocol, address.System, address.Hostname, (int)address.Port); - } - - private Akka.Cluster.PubSub.Serializers.Proto.Delta DeltaToProto(Delta delta) - { - var buckets = delta.Buckets.Select(b => - { - var entries = b.Content.Select(c => - { - var bb = Akka.Cluster.PubSub.Serializers.Proto.Delta.Types.Entry.CreateBuilder() - .SetKey(c.Key).SetVersion(c.Value.Version); - if (c.Value.Ref != null) - { - bb.SetRef(Akka.Serialization.Serialization.SerializedActorPath(c.Value.Ref)); - } - return bb.Build(); - }); - return Akka.Cluster.PubSub.Serializers.Proto.Delta.Types.Bucket.CreateBuilder() - .SetOwner(AddressToProto(b.Owner)) - .SetVersion(b.Version) - .AddRangeContent(entries) - .Build(); - }).ToArray(); - - return Akka.Cluster.PubSub.Serializers.Proto.Delta.CreateBuilder() - .AddRangeBuckets(buckets) - .Build(); - } - - private Delta DeltaFromBinary(byte[] binary) - { - return DeltaFromProto(Akka.Cluster.PubSub.Serializers.Proto.Delta.ParseFrom(Decompress(binary))); - } - - private Delta DeltaFromProto(Akka.Cluster.PubSub.Serializers.Proto.Delta delta) - { - return new Delta(delta.BucketsList.Select(b => - { - var content = b.ContentList.Aggregate(ImmutableDictionary.Empty, (map, entry) => - map.Add(entry.Key, new ValueHolder(entry.Version, entry.HasRef ? ResolveActorRef(entry.Ref) : null))); - return new Bucket(AddressFromProto(b.Owner), b.Version, content); - }).ToArray()); - } - - private IActorRef ResolveActorRef(string path) - { - return system.Provider.ResolveActorRef(path); - } - - private Status StatusToProto(Internal.Status status) - { - var versions = status.Versions.Select(v => - Status.Types.Version.CreateBuilder() - .SetAddress(AddressToProto(v.Key)) - .SetTimestamp(v.Value) - .Build()) - .ToArray(); - - return Status.CreateBuilder().AddRangeVersions(versions).Build(); - } - - private Internal.Status StatusFromBinary(byte[] binary) - { - return StatusFromProto(Status.ParseFrom(Decompress(binary))); - } - - private Internal.Status StatusFromProto(Status status) - { - return new Internal.Status(status.VersionsList - .ToDictionary( - v => AddressFromProto(v.Address), - v => v.Timestamp)); - } - - private Send SendToProto(Distributed.Send send) - { - return Send.CreateBuilder() - .SetPath(send.Path) - .SetLocalAffinity(send.LocalAffinity) - .SetPayload(PayloadToProto(send.Message)) - .Build(); - } - - private Distributed.Send SendFromBinary(byte[] binary) - { - return SendFromProto(Send.ParseFrom(binary)); - } - - private Distributed.Send SendFromProto(Send send) - { - return new Distributed.Send(send.Path, PayloadFromProto(send.Payload), send.LocalAffinity); - } - - private SendToAll SendToAllToProto(Distributed.SendToAll sendToAll) - { - return SendToAll.CreateBuilder() - .SetPath(sendToAll.Path) - .SetAllButSelf(sendToAll.ExcludeSelf) - .SetPayload(PayloadToProto(sendToAll.Message)) - .Build(); - } - - private Distributed.SendToAll SendToAllFromBinary(byte[] binary) - { - return SendToAllFromProto(SendToAll.ParseFrom(binary)); - } - - private Distributed.SendToAll SendToAllFromProto(SendToAll send) - { - return new Distributed.SendToAll(send.Path, PayloadFromProto(send.Payload), send.AllButSelf); - } - - private Publish PublishToProto(Distributed.Publish publish) - { - return Publish.CreateBuilder() - .SetTopic(publish.Topic) - .SetPayload(PayloadToProto(publish.Message)) - .Build(); - } - - private Distributed.Publish PublishFromBinary(byte[] binary) - { - return PublishFromProto(Publish.ParseFrom(binary)); - } - - private Distributed.Publish PublishFromProto(Publish publish) - { - return new Distributed.Publish(publish.Topic, PayloadFromProto(publish.Payload)); - } - - private Payload PayloadToProto(object message) - { - var serializer = system.Serialization.FindSerializerFor(message); - var builder = Payload.CreateBuilder() - .SetEnclosedMessage(ByteString.CopyFrom(serializer.ToBinary(message))) - .SetSerializerId(serializer.Identifier); - - SerializerWithStringManifest serializerWithManifest; - if ((serializerWithManifest = serializer as SerializerWithStringManifest) != null) - { - var manifest = serializerWithManifest.Manifest(message); - if (!string.IsNullOrEmpty(manifest)) - builder.SetMessageManifest(ByteString.CopyFromUtf8(manifest)); - } - else - { - if (serializer.IncludeManifest) - builder.SetMessageManifest(ByteString.CopyFromUtf8(message.GetType().FullName)); - } - - return builder.Build(); - } - - private object PayloadFromProto(Payload payload) - { - var type = payload.HasMessageManifest ? Type.GetType(payload.MessageManifest.ToStringUtf8()) : null; - return system.Serialization.Deserialize( - payload.EnclosedMessage.ToByteArray(), - payload.SerializerId, - type); - } - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Tools/PublishSubscribe/Serialization/Proto/DistributedPubSubMessages.cs b/src/contrib/cluster/Akka.Cluster.Tools/PublishSubscribe/Serialization/Proto/DistributedPubSubMessages.cs deleted file mode 100644 index 5a0df5e5446..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools/PublishSubscribe/Serialization/Proto/DistributedPubSubMessages.cs +++ /dev/null @@ -1,4626 +0,0 @@ -// Generated by ProtoGen, Version=2.4.1.521, Culture=neutral, PublicKeyToken=55f7125234beb589. DO NOT EDIT! -#pragma warning disable 1591, 0612, 3021 -#region Designer generated code - -using pb = global::Google.ProtocolBuffers; -using pbc = global::Google.ProtocolBuffers.Collections; -using pbd = global::Google.ProtocolBuffers.Descriptors; -using scg = global::System.Collections.Generic; -namespace Akka.Cluster.PubSub.Serializers.Proto -{ - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public static partial class DistributedPubSubMessages - { - - #region Extension registration - public static void RegisterAllExtensions(pb::ExtensionRegistry registry) - { - } - #endregion - #region Static variables - internal static pbd::MessageDescriptor internal__static_Status__Descriptor; - internal static pb::FieldAccess.FieldAccessorTable internal__static_Status__FieldAccessorTable; - internal static pbd::MessageDescriptor internal__static_Status_Version__Descriptor; - internal static pb::FieldAccess.FieldAccessorTable internal__static_Status_Version__FieldAccessorTable; - internal static pbd::MessageDescriptor internal__static_Delta__Descriptor; - internal static pb::FieldAccess.FieldAccessorTable internal__static_Delta__FieldAccessorTable; - internal static pbd::MessageDescriptor internal__static_Delta_Entry__Descriptor; - internal static pb::FieldAccess.FieldAccessorTable internal__static_Delta_Entry__FieldAccessorTable; - internal static pbd::MessageDescriptor internal__static_Delta_Bucket__Descriptor; - internal static pb::FieldAccess.FieldAccessorTable internal__static_Delta_Bucket__FieldAccessorTable; - internal static pbd::MessageDescriptor internal__static_Address__Descriptor; - internal static pb::FieldAccess.FieldAccessorTable internal__static_Address__FieldAccessorTable; - internal static pbd::MessageDescriptor internal__static_Send__Descriptor; - internal static pb::FieldAccess.FieldAccessorTable internal__static_Send__FieldAccessorTable; - internal static pbd::MessageDescriptor internal__static_SendToAll__Descriptor; - internal static pb::FieldAccess.FieldAccessorTable internal__static_SendToAll__FieldAccessorTable; - internal static pbd::MessageDescriptor internal__static_Publish__Descriptor; - internal static pb::FieldAccess.FieldAccessorTable internal__static_Publish__FieldAccessorTable; - internal static pbd::MessageDescriptor internal__static_Payload__Descriptor; - internal static pb::FieldAccess.FieldAccessorTable internal__static_Payload__FieldAccessorTable; - #endregion - #region Descriptor - public static pbd::FileDescriptor Descriptor - { - get { return descriptor; } - } - private static pbd::FileDescriptor descriptor; - - static DistributedPubSubMessages() - { - byte[] descriptorData = global::System.Convert.FromBase64String( - "Ch9EaXN0cmlidXRlZFB1YlN1Yk1lc3NhZ2VzLnByb3RvImQKBlN0YXR1cxIh" + - "Cgh2ZXJzaW9ucxgBIAMoCzIPLlN0YXR1cy5WZXJzaW9uGjcKB1ZlcnNpb24S" + - "GQoHYWRkcmVzcxgBIAIoCzIILkFkZHJlc3MSEQoJdGltZXN0YW1wGAIgAigD" + - "Iq4BCgVEZWx0YRIeCgdidWNrZXRzGAEgAygLMg0uRGVsdGEuQnVja2V0GjIK" + - "BUVudHJ5EgsKA2tleRgBIAIoCRIPCgd2ZXJzaW9uGAIgAigDEgsKA3JlZhgD" + - "IAEoCRpRCgZCdWNrZXQSFwoFb3duZXIYASACKAsyCC5BZGRyZXNzEg8KB3Zl" + - "cnNpb24YAiACKAMSHQoHY29udGVudBgDIAMoCzIMLkRlbHRhLkVudHJ5IksK" + - "B0FkZHJlc3MSDgoGc3lzdGVtGAEgAigJEhAKCGhvc3RuYW1lGAIgAigJEgwK" + - "BHBvcnQYAyACKA0SEAoIcHJvdG9jb2wYBCABKAkiRgoEU2VuZBIMCgRwYXRo" + - "GAEgAigJEhUKDWxvY2FsQWZmaW5pdHkYAiACKAgSGQoHcGF5bG9hZBgDIAIo" + - "CzIILlBheWxvYWQiSAoJU2VuZFRvQWxsEgwKBHBhdGgYASACKAkSEgoKYWxs" + - "QnV0U2VsZhgCIAIoCBIZCgdwYXlsb2FkGAMgAigLMgguUGF5bG9hZCIzCgdQ" + - "dWJsaXNoEg0KBXRvcGljGAEgAigJEhkKB3BheWxvYWQYAyACKAsyCC5QYXls" + - "b2FkIlEKB1BheWxvYWQSFwoPZW5jbG9zZWRNZXNzYWdlGAEgAigMEhQKDHNl" + - "cmlhbGl6ZXJJZBgCIAIoBRIXCg9tZXNzYWdlTWFuaWZlc3QYBCABKAxCAkgB"); - pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate (pbd::FileDescriptor root) { - descriptor = root; - internal__static_Status__Descriptor = Descriptor.MessageTypes[0]; - internal__static_Status__FieldAccessorTable = - new pb::FieldAccess.FieldAccessorTable(internal__static_Status__Descriptor, - new string[] { "Versions", }); - internal__static_Status_Version__Descriptor = internal__static_Status__Descriptor.NestedTypes[0]; - internal__static_Status_Version__FieldAccessorTable = - new pb::FieldAccess.FieldAccessorTable(internal__static_Status_Version__Descriptor, - new string[] { "Address", "Timestamp", }); - internal__static_Delta__Descriptor = Descriptor.MessageTypes[1]; - internal__static_Delta__FieldAccessorTable = - new pb::FieldAccess.FieldAccessorTable(internal__static_Delta__Descriptor, - new string[] { "Buckets", }); - internal__static_Delta_Entry__Descriptor = internal__static_Delta__Descriptor.NestedTypes[0]; - internal__static_Delta_Entry__FieldAccessorTable = - new pb::FieldAccess.FieldAccessorTable(internal__static_Delta_Entry__Descriptor, - new string[] { "Key", "Version", "Ref", }); - internal__static_Delta_Bucket__Descriptor = internal__static_Delta__Descriptor.NestedTypes[1]; - internal__static_Delta_Bucket__FieldAccessorTable = - new pb::FieldAccess.FieldAccessorTable(internal__static_Delta_Bucket__Descriptor, - new string[] { "Owner", "Version", "Content", }); - internal__static_Address__Descriptor = Descriptor.MessageTypes[2]; - internal__static_Address__FieldAccessorTable = - new pb::FieldAccess.FieldAccessorTable(internal__static_Address__Descriptor, - new string[] { "System", "Hostname", "Port", "Protocol", }); - internal__static_Send__Descriptor = Descriptor.MessageTypes[3]; - internal__static_Send__FieldAccessorTable = - new pb::FieldAccess.FieldAccessorTable(internal__static_Send__Descriptor, - new string[] { "Path", "LocalAffinity", "Payload", }); - internal__static_SendToAll__Descriptor = Descriptor.MessageTypes[4]; - internal__static_SendToAll__FieldAccessorTable = - new pb::FieldAccess.FieldAccessorTable(internal__static_SendToAll__Descriptor, - new string[] { "Path", "AllButSelf", "Payload", }); - internal__static_Publish__Descriptor = Descriptor.MessageTypes[5]; - internal__static_Publish__FieldAccessorTable = - new pb::FieldAccess.FieldAccessorTable(internal__static_Publish__Descriptor, - new string[] { "Topic", "Payload", }); - internal__static_Payload__Descriptor = Descriptor.MessageTypes[6]; - internal__static_Payload__FieldAccessorTable = - new pb::FieldAccess.FieldAccessorTable(internal__static_Payload__Descriptor, - new string[] { "EnclosedMessage", "SerializerId", "MessageManifest", }); - return null; - }; - pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, - new pbd::FileDescriptor[] { - }, assigner); - } - #endregion - - } - #region Messages - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class Status : pb::GeneratedMessage - { - private Status() { } - private static readonly Status defaultInstance = new Status().MakeReadOnly(); - private static readonly string[] _statusFieldNames = new string[] { "versions" }; - private static readonly uint[] _statusFieldTags = new uint[] { 10 }; - public static Status DefaultInstance - { - get { return defaultInstance; } - } - - public override Status DefaultInstanceForType - { - get { return DefaultInstance; } - } - - protected override Status ThisMessage - { - get { return this; } - } - - public static pbd::MessageDescriptor Descriptor - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.DistributedPubSubMessages.internal__static_Status__Descriptor; } - } - - protected override pb::FieldAccess.FieldAccessorTable InternalFieldAccessors - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.DistributedPubSubMessages.internal__static_Status__FieldAccessorTable; } - } - - #region Nested types - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public static partial class Types - { - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class Version : pb::GeneratedMessage - { - private Version() { } - private static readonly Version defaultInstance = new Version().MakeReadOnly(); - private static readonly string[] _versionFieldNames = new string[] { "address", "timestamp" }; - private static readonly uint[] _versionFieldTags = new uint[] { 10, 16 }; - public static Version DefaultInstance - { - get { return defaultInstance; } - } - - public override Version DefaultInstanceForType - { - get { return DefaultInstance; } - } - - protected override Version ThisMessage - { - get { return this; } - } - - public static pbd::MessageDescriptor Descriptor - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.DistributedPubSubMessages.internal__static_Status_Version__Descriptor; } - } - - protected override pb::FieldAccess.FieldAccessorTable InternalFieldAccessors - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.DistributedPubSubMessages.internal__static_Status_Version__FieldAccessorTable; } - } - - public const int AddressFieldNumber = 1; - private bool hasAddress; - private global::Akka.Cluster.PubSub.Serializers.Proto.Address address_; - public bool HasAddress - { - get { return hasAddress; } - } - public global::Akka.Cluster.PubSub.Serializers.Proto.Address Address - { - get { return address_ ?? global::Akka.Cluster.PubSub.Serializers.Proto.Address.DefaultInstance; } - } - - public const int TimestampFieldNumber = 2; - private bool hasTimestamp; - private long timestamp_; - public bool HasTimestamp - { - get { return hasTimestamp; } - } - public long Timestamp - { - get { return timestamp_; } - } - - public override bool IsInitialized - { - get - { - if (!hasAddress) return false; - if (!hasTimestamp) return false; - if (!Address.IsInitialized) return false; - return true; - } - } - - public override void WriteTo(pb::ICodedOutputStream output) - { - int size = SerializedSize; - string[] field_names = _versionFieldNames; - if (hasAddress) - { - output.WriteMessage(1, field_names[0], Address); - } - if (hasTimestamp) - { - output.WriteInt64(2, field_names[1], Timestamp); - } - UnknownFields.WriteTo(output); - } - - private int memoizedSerializedSize = -1; - public override int SerializedSize - { - get - { - int size = memoizedSerializedSize; - if (size != -1) return size; - - size = 0; - if (hasAddress) - { - size += pb::CodedOutputStream.ComputeMessageSize(1, Address); - } - if (hasTimestamp) - { - size += pb::CodedOutputStream.ComputeInt64Size(2, Timestamp); - } - size += UnknownFields.SerializedSize; - memoizedSerializedSize = size; - return size; - } - } - - public static Version ParseFrom(pb::ByteString data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static Version ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static Version ParseFrom(byte[] data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static Version ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static Version ParseFrom(global::System.IO.Stream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static Version ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - public static Version ParseDelimitedFrom(global::System.IO.Stream input) - { - return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); - } - public static Version ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); - } - public static Version ParseFrom(pb::ICodedInputStream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static Version ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - private Version MakeReadOnly() - { - return this; - } - - public static Builder CreateBuilder() { return new Builder(); } - public override Builder ToBuilder() { return CreateBuilder(this); } - public override Builder CreateBuilderForType() { return new Builder(); } - public static Builder CreateBuilder(Version prototype) - { - return new Builder(prototype); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class Builder : pb::GeneratedBuilder - { - protected override Builder ThisBuilder - { - get { return this; } - } - public Builder() - { - result = DefaultInstance; - resultIsReadOnly = true; - } - internal Builder(Version cloneFrom) - { - result = cloneFrom; - resultIsReadOnly = true; - } - - private bool resultIsReadOnly; - private Version result; - - private Version PrepareBuilder() - { - if (resultIsReadOnly) - { - Version original = result; - result = new Version(); - resultIsReadOnly = false; - MergeFrom(original); - } - return result; - } - - public override bool IsInitialized - { - get { return result.IsInitialized; } - } - - protected override Version MessageBeingBuilt - { - get { return PrepareBuilder(); } - } - - public override Builder Clear() - { - result = DefaultInstance; - resultIsReadOnly = true; - return this; - } - - public override Builder Clone() - { - if (resultIsReadOnly) - { - return new Builder(result); - } - else - { - return new Builder().MergeFrom(result); - } - } - - public override pbd::MessageDescriptor DescriptorForType - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.Status.Types.Version.Descriptor; } - } - - public override Version DefaultInstanceForType - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.Status.Types.Version.DefaultInstance; } - } - - public override Version BuildPartial() - { - if (resultIsReadOnly) - { - return result; - } - resultIsReadOnly = true; - return result.MakeReadOnly(); - } - - public override Builder MergeFrom(pb::IMessage other) - { - if (other is Version) - { - return MergeFrom((Version)other); - } - else - { - base.MergeFrom(other); - return this; - } - } - - public override Builder MergeFrom(Version other) - { - if (other == global::Akka.Cluster.PubSub.Serializers.Proto.Status.Types.Version.DefaultInstance) return this; - PrepareBuilder(); - if (other.HasAddress) - { - MergeAddress(other.Address); - } - if (other.HasTimestamp) - { - Timestamp = other.Timestamp; - } - this.MergeUnknownFields(other.UnknownFields); - return this; - } - - public override Builder MergeFrom(pb::ICodedInputStream input) - { - return MergeFrom(input, pb::ExtensionRegistry.Empty); - } - - public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - PrepareBuilder(); - pb::UnknownFieldSet.Builder unknownFields = null; - uint tag; - string field_name; - while (input.ReadTag(out tag, out field_name)) - { - if (tag == 0 && field_name != null) - { - int field_ordinal = global::System.Array.BinarySearch(_versionFieldNames, field_name, global::System.StringComparer.Ordinal); - if (field_ordinal >= 0) - tag = _versionFieldTags[field_ordinal]; - else - { - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - continue; - } - } - switch (tag) - { - case 0: - { - throw pb::InvalidProtocolBufferException.InvalidTag(); - } - default: - { - if (pb::WireFormat.IsEndGroupTag(tag)) - { - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - break; - } - case 10: - { - global::Akka.Cluster.PubSub.Serializers.Proto.Address.Builder subBuilder = global::Akka.Cluster.PubSub.Serializers.Proto.Address.CreateBuilder(); - if (result.hasAddress) - { - subBuilder.MergeFrom(Address); - } - input.ReadMessage(subBuilder, extensionRegistry); - Address = subBuilder.BuildPartial(); - break; - } - case 16: - { - result.hasTimestamp = input.ReadInt64(ref result.timestamp_); - break; - } - } - } - - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - - - public bool HasAddress - { - get { return result.hasAddress; } - } - public global::Akka.Cluster.PubSub.Serializers.Proto.Address Address - { - get { return result.Address; } - set { SetAddress(value); } - } - public Builder SetAddress(global::Akka.Cluster.PubSub.Serializers.Proto.Address value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.hasAddress = true; - result.address_ = value; - return this; - } - public Builder SetAddress(global::Akka.Cluster.PubSub.Serializers.Proto.Address.Builder builderForValue) - { - pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); - PrepareBuilder(); - result.hasAddress = true; - result.address_ = builderForValue.Build(); - return this; - } - public Builder MergeAddress(global::Akka.Cluster.PubSub.Serializers.Proto.Address value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - if (result.hasAddress && - result.address_ != global::Akka.Cluster.PubSub.Serializers.Proto.Address.DefaultInstance) - { - result.address_ = global::Akka.Cluster.PubSub.Serializers.Proto.Address.CreateBuilder(result.address_).MergeFrom(value).BuildPartial(); - } - else - { - result.address_ = value; - } - result.hasAddress = true; - return this; - } - public Builder ClearAddress() - { - PrepareBuilder(); - result.hasAddress = false; - result.address_ = null; - return this; - } - - public bool HasTimestamp - { - get { return result.hasTimestamp; } - } - public long Timestamp - { - get { return result.Timestamp; } - set { SetTimestamp(value); } - } - public Builder SetTimestamp(long value) - { - PrepareBuilder(); - result.hasTimestamp = true; - result.timestamp_ = value; - return this; - } - public Builder ClearTimestamp() - { - PrepareBuilder(); - result.hasTimestamp = false; - result.timestamp_ = 0L; - return this; - } - } - static Version() - { - object.ReferenceEquals(global::Akka.Cluster.PubSub.Serializers.Proto.DistributedPubSubMessages.Descriptor, null); - } - } - - } - #endregion - - public const int VersionsFieldNumber = 1; - private pbc::PopsicleList versions_ = new pbc::PopsicleList(); - public scg::IList VersionsList - { - get { return versions_; } - } - public int VersionsCount - { - get { return versions_.Count; } - } - public global::Akka.Cluster.PubSub.Serializers.Proto.Status.Types.Version GetVersions(int index) - { - return versions_[index]; - } - - public override bool IsInitialized - { - get - { - foreach (global::Akka.Cluster.PubSub.Serializers.Proto.Status.Types.Version element in VersionsList) - { - if (!element.IsInitialized) return false; - } - return true; - } - } - - public override void WriteTo(pb::ICodedOutputStream output) - { - int size = SerializedSize; - string[] field_names = _statusFieldNames; - if (versions_.Count > 0) - { - output.WriteMessageArray(1, field_names[0], versions_); - } - UnknownFields.WriteTo(output); - } - - private int memoizedSerializedSize = -1; - public override int SerializedSize - { - get - { - int size = memoizedSerializedSize; - if (size != -1) return size; - - size = 0; - foreach (global::Akka.Cluster.PubSub.Serializers.Proto.Status.Types.Version element in VersionsList) - { - size += pb::CodedOutputStream.ComputeMessageSize(1, element); - } - size += UnknownFields.SerializedSize; - memoizedSerializedSize = size; - return size; - } - } - - public static Status ParseFrom(pb::ByteString data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static Status ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static Status ParseFrom(byte[] data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static Status ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static Status ParseFrom(global::System.IO.Stream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static Status ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - public static Status ParseDelimitedFrom(global::System.IO.Stream input) - { - return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); - } - public static Status ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); - } - public static Status ParseFrom(pb::ICodedInputStream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static Status ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - private Status MakeReadOnly() - { - versions_.MakeReadOnly(); - return this; - } - - public static Builder CreateBuilder() { return new Builder(); } - public override Builder ToBuilder() { return CreateBuilder(this); } - public override Builder CreateBuilderForType() { return new Builder(); } - public static Builder CreateBuilder(Status prototype) - { - return new Builder(prototype); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class Builder : pb::GeneratedBuilder - { - protected override Builder ThisBuilder - { - get { return this; } - } - public Builder() - { - result = DefaultInstance; - resultIsReadOnly = true; - } - internal Builder(Status cloneFrom) - { - result = cloneFrom; - resultIsReadOnly = true; - } - - private bool resultIsReadOnly; - private Status result; - - private Status PrepareBuilder() - { - if (resultIsReadOnly) - { - Status original = result; - result = new Status(); - resultIsReadOnly = false; - MergeFrom(original); - } - return result; - } - - public override bool IsInitialized - { - get { return result.IsInitialized; } - } - - protected override Status MessageBeingBuilt - { - get { return PrepareBuilder(); } - } - - public override Builder Clear() - { - result = DefaultInstance; - resultIsReadOnly = true; - return this; - } - - public override Builder Clone() - { - if (resultIsReadOnly) - { - return new Builder(result); - } - else - { - return new Builder().MergeFrom(result); - } - } - - public override pbd::MessageDescriptor DescriptorForType - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.Status.Descriptor; } - } - - public override Status DefaultInstanceForType - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.Status.DefaultInstance; } - } - - public override Status BuildPartial() - { - if (resultIsReadOnly) - { - return result; - } - resultIsReadOnly = true; - return result.MakeReadOnly(); - } - - public override Builder MergeFrom(pb::IMessage other) - { - if (other is Status) - { - return MergeFrom((Status)other); - } - else - { - base.MergeFrom(other); - return this; - } - } - - public override Builder MergeFrom(Status other) - { - if (other == global::Akka.Cluster.PubSub.Serializers.Proto.Status.DefaultInstance) return this; - PrepareBuilder(); - if (other.versions_.Count != 0) - { - result.versions_.Add(other.versions_); - } - this.MergeUnknownFields(other.UnknownFields); - return this; - } - - public override Builder MergeFrom(pb::ICodedInputStream input) - { - return MergeFrom(input, pb::ExtensionRegistry.Empty); - } - - public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - PrepareBuilder(); - pb::UnknownFieldSet.Builder unknownFields = null; - uint tag; - string field_name; - while (input.ReadTag(out tag, out field_name)) - { - if (tag == 0 && field_name != null) - { - int field_ordinal = global::System.Array.BinarySearch(_statusFieldNames, field_name, global::System.StringComparer.Ordinal); - if (field_ordinal >= 0) - tag = _statusFieldTags[field_ordinal]; - else - { - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - continue; - } - } - switch (tag) - { - case 0: - { - throw pb::InvalidProtocolBufferException.InvalidTag(); - } - default: - { - if (pb::WireFormat.IsEndGroupTag(tag)) - { - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - break; - } - case 10: - { - input.ReadMessageArray(tag, field_name, result.versions_, global::Akka.Cluster.PubSub.Serializers.Proto.Status.Types.Version.DefaultInstance, extensionRegistry); - break; - } - } - } - - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - - - public pbc::IPopsicleList VersionsList - { - get { return PrepareBuilder().versions_; } - } - public int VersionsCount - { - get { return result.VersionsCount; } - } - public global::Akka.Cluster.PubSub.Serializers.Proto.Status.Types.Version GetVersions(int index) - { - return result.GetVersions(index); - } - public Builder SetVersions(int index, global::Akka.Cluster.PubSub.Serializers.Proto.Status.Types.Version value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.versions_[index] = value; - return this; - } - public Builder SetVersions(int index, global::Akka.Cluster.PubSub.Serializers.Proto.Status.Types.Version.Builder builderForValue) - { - pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); - PrepareBuilder(); - result.versions_[index] = builderForValue.Build(); - return this; - } - public Builder AddVersions(global::Akka.Cluster.PubSub.Serializers.Proto.Status.Types.Version value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.versions_.Add(value); - return this; - } - public Builder AddVersions(global::Akka.Cluster.PubSub.Serializers.Proto.Status.Types.Version.Builder builderForValue) - { - pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); - PrepareBuilder(); - result.versions_.Add(builderForValue.Build()); - return this; - } - public Builder AddRangeVersions(scg::IEnumerable values) - { - PrepareBuilder(); - result.versions_.Add(values); - return this; - } - public Builder ClearVersions() - { - PrepareBuilder(); - result.versions_.Clear(); - return this; - } - } - static Status() - { - object.ReferenceEquals(global::Akka.Cluster.PubSub.Serializers.Proto.DistributedPubSubMessages.Descriptor, null); - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class Delta : pb::GeneratedMessage - { - private Delta() { } - private static readonly Delta defaultInstance = new Delta().MakeReadOnly(); - private static readonly string[] _deltaFieldNames = new string[] { "buckets" }; - private static readonly uint[] _deltaFieldTags = new uint[] { 10 }; - public static Delta DefaultInstance - { - get { return defaultInstance; } - } - - public override Delta DefaultInstanceForType - { - get { return DefaultInstance; } - } - - protected override Delta ThisMessage - { - get { return this; } - } - - public static pbd::MessageDescriptor Descriptor - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.DistributedPubSubMessages.internal__static_Delta__Descriptor; } - } - - protected override pb::FieldAccess.FieldAccessorTable InternalFieldAccessors - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.DistributedPubSubMessages.internal__static_Delta__FieldAccessorTable; } - } - - #region Nested types - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public static partial class Types - { - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class Entry : pb::GeneratedMessage - { - private Entry() { } - private static readonly Entry defaultInstance = new Entry().MakeReadOnly(); - private static readonly string[] _entryFieldNames = new string[] { "key", "ref", "version" }; - private static readonly uint[] _entryFieldTags = new uint[] { 10, 26, 16 }; - public static Entry DefaultInstance - { - get { return defaultInstance; } - } - - public override Entry DefaultInstanceForType - { - get { return DefaultInstance; } - } - - protected override Entry ThisMessage - { - get { return this; } - } - - public static pbd::MessageDescriptor Descriptor - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.DistributedPubSubMessages.internal__static_Delta_Entry__Descriptor; } - } - - protected override pb::FieldAccess.FieldAccessorTable InternalFieldAccessors - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.DistributedPubSubMessages.internal__static_Delta_Entry__FieldAccessorTable; } - } - - public const int KeyFieldNumber = 1; - private bool hasKey; - private string key_ = ""; - public bool HasKey - { - get { return hasKey; } - } - public string Key - { - get { return key_; } - } - - public const int VersionFieldNumber = 2; - private bool hasVersion; - private long version_; - public bool HasVersion - { - get { return hasVersion; } - } - public long Version - { - get { return version_; } - } - - public const int RefFieldNumber = 3; - private bool hasRef; - private string ref_ = ""; - public bool HasRef - { - get { return hasRef; } - } - public string Ref - { - get { return ref_; } - } - - public override bool IsInitialized - { - get - { - if (!hasKey) return false; - if (!hasVersion) return false; - return true; - } - } - - public override void WriteTo(pb::ICodedOutputStream output) - { - int size = SerializedSize; - string[] field_names = _entryFieldNames; - if (hasKey) - { - output.WriteString(1, field_names[0], Key); - } - if (hasVersion) - { - output.WriteInt64(2, field_names[2], Version); - } - if (hasRef) - { - output.WriteString(3, field_names[1], Ref); - } - UnknownFields.WriteTo(output); - } - - private int memoizedSerializedSize = -1; - public override int SerializedSize - { - get - { - int size = memoizedSerializedSize; - if (size != -1) return size; - - size = 0; - if (hasKey) - { - size += pb::CodedOutputStream.ComputeStringSize(1, Key); - } - if (hasVersion) - { - size += pb::CodedOutputStream.ComputeInt64Size(2, Version); - } - if (hasRef) - { - size += pb::CodedOutputStream.ComputeStringSize(3, Ref); - } - size += UnknownFields.SerializedSize; - memoizedSerializedSize = size; - return size; - } - } - - public static Entry ParseFrom(pb::ByteString data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static Entry ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static Entry ParseFrom(byte[] data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static Entry ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static Entry ParseFrom(global::System.IO.Stream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static Entry ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - public static Entry ParseDelimitedFrom(global::System.IO.Stream input) - { - return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); - } - public static Entry ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); - } - public static Entry ParseFrom(pb::ICodedInputStream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static Entry ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - private Entry MakeReadOnly() - { - return this; - } - - public static Builder CreateBuilder() { return new Builder(); } - public override Builder ToBuilder() { return CreateBuilder(this); } - public override Builder CreateBuilderForType() { return new Builder(); } - public static Builder CreateBuilder(Entry prototype) - { - return new Builder(prototype); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class Builder : pb::GeneratedBuilder - { - protected override Builder ThisBuilder - { - get { return this; } - } - public Builder() - { - result = DefaultInstance; - resultIsReadOnly = true; - } - internal Builder(Entry cloneFrom) - { - result = cloneFrom; - resultIsReadOnly = true; - } - - private bool resultIsReadOnly; - private Entry result; - - private Entry PrepareBuilder() - { - if (resultIsReadOnly) - { - Entry original = result; - result = new Entry(); - resultIsReadOnly = false; - MergeFrom(original); - } - return result; - } - - public override bool IsInitialized - { - get { return result.IsInitialized; } - } - - protected override Entry MessageBeingBuilt - { - get { return PrepareBuilder(); } - } - - public override Builder Clear() - { - result = DefaultInstance; - resultIsReadOnly = true; - return this; - } - - public override Builder Clone() - { - if (resultIsReadOnly) - { - return new Builder(result); - } - else - { - return new Builder().MergeFrom(result); - } - } - - public override pbd::MessageDescriptor DescriptorForType - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.Delta.Types.Entry.Descriptor; } - } - - public override Entry DefaultInstanceForType - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.Delta.Types.Entry.DefaultInstance; } - } - - public override Entry BuildPartial() - { - if (resultIsReadOnly) - { - return result; - } - resultIsReadOnly = true; - return result.MakeReadOnly(); - } - - public override Builder MergeFrom(pb::IMessage other) - { - if (other is Entry) - { - return MergeFrom((Entry)other); - } - else - { - base.MergeFrom(other); - return this; - } - } - - public override Builder MergeFrom(Entry other) - { - if (other == global::Akka.Cluster.PubSub.Serializers.Proto.Delta.Types.Entry.DefaultInstance) return this; - PrepareBuilder(); - if (other.HasKey) - { - Key = other.Key; - } - if (other.HasVersion) - { - Version = other.Version; - } - if (other.HasRef) - { - Ref = other.Ref; - } - this.MergeUnknownFields(other.UnknownFields); - return this; - } - - public override Builder MergeFrom(pb::ICodedInputStream input) - { - return MergeFrom(input, pb::ExtensionRegistry.Empty); - } - - public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - PrepareBuilder(); - pb::UnknownFieldSet.Builder unknownFields = null; - uint tag; - string field_name; - while (input.ReadTag(out tag, out field_name)) - { - if (tag == 0 && field_name != null) - { - int field_ordinal = global::System.Array.BinarySearch(_entryFieldNames, field_name, global::System.StringComparer.Ordinal); - if (field_ordinal >= 0) - tag = _entryFieldTags[field_ordinal]; - else - { - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - continue; - } - } - switch (tag) - { - case 0: - { - throw pb::InvalidProtocolBufferException.InvalidTag(); - } - default: - { - if (pb::WireFormat.IsEndGroupTag(tag)) - { - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - break; - } - case 10: - { - result.hasKey = input.ReadString(ref result.key_); - break; - } - case 16: - { - result.hasVersion = input.ReadInt64(ref result.version_); - break; - } - case 26: - { - result.hasRef = input.ReadString(ref result.ref_); - break; - } - } - } - - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - - - public bool HasKey - { - get { return result.hasKey; } - } - public string Key - { - get { return result.Key; } - set { SetKey(value); } - } - public Builder SetKey(string value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.hasKey = true; - result.key_ = value; - return this; - } - public Builder ClearKey() - { - PrepareBuilder(); - result.hasKey = false; - result.key_ = ""; - return this; - } - - public bool HasVersion - { - get { return result.hasVersion; } - } - public long Version - { - get { return result.Version; } - set { SetVersion(value); } - } - public Builder SetVersion(long value) - { - PrepareBuilder(); - result.hasVersion = true; - result.version_ = value; - return this; - } - public Builder ClearVersion() - { - PrepareBuilder(); - result.hasVersion = false; - result.version_ = 0L; - return this; - } - - public bool HasRef - { - get { return result.hasRef; } - } - public string Ref - { - get { return result.Ref; } - set { SetRef(value); } - } - public Builder SetRef(string value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.hasRef = true; - result.ref_ = value; - return this; - } - public Builder ClearRef() - { - PrepareBuilder(); - result.hasRef = false; - result.ref_ = ""; - return this; - } - } - static Entry() - { - object.ReferenceEquals(global::Akka.Cluster.PubSub.Serializers.Proto.DistributedPubSubMessages.Descriptor, null); - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class Bucket : pb::GeneratedMessage - { - private Bucket() { } - private static readonly Bucket defaultInstance = new Bucket().MakeReadOnly(); - private static readonly string[] _bucketFieldNames = new string[] { "content", "owner", "version" }; - private static readonly uint[] _bucketFieldTags = new uint[] { 26, 10, 16 }; - public static Bucket DefaultInstance - { - get { return defaultInstance; } - } - - public override Bucket DefaultInstanceForType - { - get { return DefaultInstance; } - } - - protected override Bucket ThisMessage - { - get { return this; } - } - - public static pbd::MessageDescriptor Descriptor - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.DistributedPubSubMessages.internal__static_Delta_Bucket__Descriptor; } - } - - protected override pb::FieldAccess.FieldAccessorTable InternalFieldAccessors - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.DistributedPubSubMessages.internal__static_Delta_Bucket__FieldAccessorTable; } - } - - public const int OwnerFieldNumber = 1; - private bool hasOwner; - private global::Akka.Cluster.PubSub.Serializers.Proto.Address owner_; - public bool HasOwner - { - get { return hasOwner; } - } - public global::Akka.Cluster.PubSub.Serializers.Proto.Address Owner - { - get { return owner_ ?? global::Akka.Cluster.PubSub.Serializers.Proto.Address.DefaultInstance; } - } - - public const int VersionFieldNumber = 2; - private bool hasVersion; - private long version_; - public bool HasVersion - { - get { return hasVersion; } - } - public long Version - { - get { return version_; } - } - - public const int ContentFieldNumber = 3; - private pbc::PopsicleList content_ = new pbc::PopsicleList(); - public scg::IList ContentList - { - get { return content_; } - } - public int ContentCount - { - get { return content_.Count; } - } - public global::Akka.Cluster.PubSub.Serializers.Proto.Delta.Types.Entry GetContent(int index) - { - return content_[index]; - } - - public override bool IsInitialized - { - get - { - if (!hasOwner) return false; - if (!hasVersion) return false; - if (!Owner.IsInitialized) return false; - foreach (global::Akka.Cluster.PubSub.Serializers.Proto.Delta.Types.Entry element in ContentList) - { - if (!element.IsInitialized) return false; - } - return true; - } - } - - public override void WriteTo(pb::ICodedOutputStream output) - { - int size = SerializedSize; - string[] field_names = _bucketFieldNames; - if (hasOwner) - { - output.WriteMessage(1, field_names[1], Owner); - } - if (hasVersion) - { - output.WriteInt64(2, field_names[2], Version); - } - if (content_.Count > 0) - { - output.WriteMessageArray(3, field_names[0], content_); - } - UnknownFields.WriteTo(output); - } - - private int memoizedSerializedSize = -1; - public override int SerializedSize - { - get - { - int size = memoizedSerializedSize; - if (size != -1) return size; - - size = 0; - if (hasOwner) - { - size += pb::CodedOutputStream.ComputeMessageSize(1, Owner); - } - if (hasVersion) - { - size += pb::CodedOutputStream.ComputeInt64Size(2, Version); - } - foreach (global::Akka.Cluster.PubSub.Serializers.Proto.Delta.Types.Entry element in ContentList) - { - size += pb::CodedOutputStream.ComputeMessageSize(3, element); - } - size += UnknownFields.SerializedSize; - memoizedSerializedSize = size; - return size; - } - } - - public static Bucket ParseFrom(pb::ByteString data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static Bucket ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static Bucket ParseFrom(byte[] data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static Bucket ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static Bucket ParseFrom(global::System.IO.Stream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static Bucket ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - public static Bucket ParseDelimitedFrom(global::System.IO.Stream input) - { - return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); - } - public static Bucket ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); - } - public static Bucket ParseFrom(pb::ICodedInputStream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static Bucket ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - private Bucket MakeReadOnly() - { - content_.MakeReadOnly(); - return this; - } - - public static Builder CreateBuilder() { return new Builder(); } - public override Builder ToBuilder() { return CreateBuilder(this); } - public override Builder CreateBuilderForType() { return new Builder(); } - public static Builder CreateBuilder(Bucket prototype) - { - return new Builder(prototype); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class Builder : pb::GeneratedBuilder - { - protected override Builder ThisBuilder - { - get { return this; } - } - public Builder() - { - result = DefaultInstance; - resultIsReadOnly = true; - } - internal Builder(Bucket cloneFrom) - { - result = cloneFrom; - resultIsReadOnly = true; - } - - private bool resultIsReadOnly; - private Bucket result; - - private Bucket PrepareBuilder() - { - if (resultIsReadOnly) - { - Bucket original = result; - result = new Bucket(); - resultIsReadOnly = false; - MergeFrom(original); - } - return result; - } - - public override bool IsInitialized - { - get { return result.IsInitialized; } - } - - protected override Bucket MessageBeingBuilt - { - get { return PrepareBuilder(); } - } - - public override Builder Clear() - { - result = DefaultInstance; - resultIsReadOnly = true; - return this; - } - - public override Builder Clone() - { - if (resultIsReadOnly) - { - return new Builder(result); - } - else - { - return new Builder().MergeFrom(result); - } - } - - public override pbd::MessageDescriptor DescriptorForType - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.Delta.Types.Bucket.Descriptor; } - } - - public override Bucket DefaultInstanceForType - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.Delta.Types.Bucket.DefaultInstance; } - } - - public override Bucket BuildPartial() - { - if (resultIsReadOnly) - { - return result; - } - resultIsReadOnly = true; - return result.MakeReadOnly(); - } - - public override Builder MergeFrom(pb::IMessage other) - { - if (other is Bucket) - { - return MergeFrom((Bucket)other); - } - else - { - base.MergeFrom(other); - return this; - } - } - - public override Builder MergeFrom(Bucket other) - { - if (other == global::Akka.Cluster.PubSub.Serializers.Proto.Delta.Types.Bucket.DefaultInstance) return this; - PrepareBuilder(); - if (other.HasOwner) - { - MergeOwner(other.Owner); - } - if (other.HasVersion) - { - Version = other.Version; - } - if (other.content_.Count != 0) - { - result.content_.Add(other.content_); - } - this.MergeUnknownFields(other.UnknownFields); - return this; - } - - public override Builder MergeFrom(pb::ICodedInputStream input) - { - return MergeFrom(input, pb::ExtensionRegistry.Empty); - } - - public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - PrepareBuilder(); - pb::UnknownFieldSet.Builder unknownFields = null; - uint tag; - string field_name; - while (input.ReadTag(out tag, out field_name)) - { - if (tag == 0 && field_name != null) - { - int field_ordinal = global::System.Array.BinarySearch(_bucketFieldNames, field_name, global::System.StringComparer.Ordinal); - if (field_ordinal >= 0) - tag = _bucketFieldTags[field_ordinal]; - else - { - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - continue; - } - } - switch (tag) - { - case 0: - { - throw pb::InvalidProtocolBufferException.InvalidTag(); - } - default: - { - if (pb::WireFormat.IsEndGroupTag(tag)) - { - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - break; - } - case 10: - { - global::Akka.Cluster.PubSub.Serializers.Proto.Address.Builder subBuilder = global::Akka.Cluster.PubSub.Serializers.Proto.Address.CreateBuilder(); - if (result.hasOwner) - { - subBuilder.MergeFrom(Owner); - } - input.ReadMessage(subBuilder, extensionRegistry); - Owner = subBuilder.BuildPartial(); - break; - } - case 16: - { - result.hasVersion = input.ReadInt64(ref result.version_); - break; - } - case 26: - { - input.ReadMessageArray(tag, field_name, result.content_, global::Akka.Cluster.PubSub.Serializers.Proto.Delta.Types.Entry.DefaultInstance, extensionRegistry); - break; - } - } - } - - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - - - public bool HasOwner - { - get { return result.hasOwner; } - } - public global::Akka.Cluster.PubSub.Serializers.Proto.Address Owner - { - get { return result.Owner; } - set { SetOwner(value); } - } - public Builder SetOwner(global::Akka.Cluster.PubSub.Serializers.Proto.Address value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.hasOwner = true; - result.owner_ = value; - return this; - } - public Builder SetOwner(global::Akka.Cluster.PubSub.Serializers.Proto.Address.Builder builderForValue) - { - pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); - PrepareBuilder(); - result.hasOwner = true; - result.owner_ = builderForValue.Build(); - return this; - } - public Builder MergeOwner(global::Akka.Cluster.PubSub.Serializers.Proto.Address value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - if (result.hasOwner && - result.owner_ != global::Akka.Cluster.PubSub.Serializers.Proto.Address.DefaultInstance) - { - result.owner_ = global::Akka.Cluster.PubSub.Serializers.Proto.Address.CreateBuilder(result.owner_).MergeFrom(value).BuildPartial(); - } - else - { - result.owner_ = value; - } - result.hasOwner = true; - return this; - } - public Builder ClearOwner() - { - PrepareBuilder(); - result.hasOwner = false; - result.owner_ = null; - return this; - } - - public bool HasVersion - { - get { return result.hasVersion; } - } - public long Version - { - get { return result.Version; } - set { SetVersion(value); } - } - public Builder SetVersion(long value) - { - PrepareBuilder(); - result.hasVersion = true; - result.version_ = value; - return this; - } - public Builder ClearVersion() - { - PrepareBuilder(); - result.hasVersion = false; - result.version_ = 0L; - return this; - } - - public pbc::IPopsicleList ContentList - { - get { return PrepareBuilder().content_; } - } - public int ContentCount - { - get { return result.ContentCount; } - } - public global::Akka.Cluster.PubSub.Serializers.Proto.Delta.Types.Entry GetContent(int index) - { - return result.GetContent(index); - } - public Builder SetContent(int index, global::Akka.Cluster.PubSub.Serializers.Proto.Delta.Types.Entry value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.content_[index] = value; - return this; - } - public Builder SetContent(int index, global::Akka.Cluster.PubSub.Serializers.Proto.Delta.Types.Entry.Builder builderForValue) - { - pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); - PrepareBuilder(); - result.content_[index] = builderForValue.Build(); - return this; - } - public Builder AddContent(global::Akka.Cluster.PubSub.Serializers.Proto.Delta.Types.Entry value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.content_.Add(value); - return this; - } - public Builder AddContent(global::Akka.Cluster.PubSub.Serializers.Proto.Delta.Types.Entry.Builder builderForValue) - { - pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); - PrepareBuilder(); - result.content_.Add(builderForValue.Build()); - return this; - } - public Builder AddRangeContent(scg::IEnumerable values) - { - PrepareBuilder(); - result.content_.Add(values); - return this; - } - public Builder ClearContent() - { - PrepareBuilder(); - result.content_.Clear(); - return this; - } - } - static Bucket() - { - object.ReferenceEquals(global::Akka.Cluster.PubSub.Serializers.Proto.DistributedPubSubMessages.Descriptor, null); - } - } - - } - #endregion - - public const int BucketsFieldNumber = 1; - private pbc::PopsicleList buckets_ = new pbc::PopsicleList(); - public scg::IList BucketsList - { - get { return buckets_; } - } - public int BucketsCount - { - get { return buckets_.Count; } - } - public global::Akka.Cluster.PubSub.Serializers.Proto.Delta.Types.Bucket GetBuckets(int index) - { - return buckets_[index]; - } - - public override bool IsInitialized - { - get - { - foreach (global::Akka.Cluster.PubSub.Serializers.Proto.Delta.Types.Bucket element in BucketsList) - { - if (!element.IsInitialized) return false; - } - return true; - } - } - - public override void WriteTo(pb::ICodedOutputStream output) - { - int size = SerializedSize; - string[] field_names = _deltaFieldNames; - if (buckets_.Count > 0) - { - output.WriteMessageArray(1, field_names[0], buckets_); - } - UnknownFields.WriteTo(output); - } - - private int memoizedSerializedSize = -1; - public override int SerializedSize - { - get - { - int size = memoizedSerializedSize; - if (size != -1) return size; - - size = 0; - foreach (global::Akka.Cluster.PubSub.Serializers.Proto.Delta.Types.Bucket element in BucketsList) - { - size += pb::CodedOutputStream.ComputeMessageSize(1, element); - } - size += UnknownFields.SerializedSize; - memoizedSerializedSize = size; - return size; - } - } - - public static Delta ParseFrom(pb::ByteString data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static Delta ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static Delta ParseFrom(byte[] data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static Delta ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static Delta ParseFrom(global::System.IO.Stream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static Delta ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - public static Delta ParseDelimitedFrom(global::System.IO.Stream input) - { - return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); - } - public static Delta ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); - } - public static Delta ParseFrom(pb::ICodedInputStream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static Delta ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - private Delta MakeReadOnly() - { - buckets_.MakeReadOnly(); - return this; - } - - public static Builder CreateBuilder() { return new Builder(); } - public override Builder ToBuilder() { return CreateBuilder(this); } - public override Builder CreateBuilderForType() { return new Builder(); } - public static Builder CreateBuilder(Delta prototype) - { - return new Builder(prototype); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class Builder : pb::GeneratedBuilder - { - protected override Builder ThisBuilder - { - get { return this; } - } - public Builder() - { - result = DefaultInstance; - resultIsReadOnly = true; - } - internal Builder(Delta cloneFrom) - { - result = cloneFrom; - resultIsReadOnly = true; - } - - private bool resultIsReadOnly; - private Delta result; - - private Delta PrepareBuilder() - { - if (resultIsReadOnly) - { - Delta original = result; - result = new Delta(); - resultIsReadOnly = false; - MergeFrom(original); - } - return result; - } - - public override bool IsInitialized - { - get { return result.IsInitialized; } - } - - protected override Delta MessageBeingBuilt - { - get { return PrepareBuilder(); } - } - - public override Builder Clear() - { - result = DefaultInstance; - resultIsReadOnly = true; - return this; - } - - public override Builder Clone() - { - if (resultIsReadOnly) - { - return new Builder(result); - } - else - { - return new Builder().MergeFrom(result); - } - } - - public override pbd::MessageDescriptor DescriptorForType - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.Delta.Descriptor; } - } - - public override Delta DefaultInstanceForType - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.Delta.DefaultInstance; } - } - - public override Delta BuildPartial() - { - if (resultIsReadOnly) - { - return result; - } - resultIsReadOnly = true; - return result.MakeReadOnly(); - } - - public override Builder MergeFrom(pb::IMessage other) - { - if (other is Delta) - { - return MergeFrom((Delta)other); - } - else - { - base.MergeFrom(other); - return this; - } - } - - public override Builder MergeFrom(Delta other) - { - if (other == global::Akka.Cluster.PubSub.Serializers.Proto.Delta.DefaultInstance) return this; - PrepareBuilder(); - if (other.buckets_.Count != 0) - { - result.buckets_.Add(other.buckets_); - } - this.MergeUnknownFields(other.UnknownFields); - return this; - } - - public override Builder MergeFrom(pb::ICodedInputStream input) - { - return MergeFrom(input, pb::ExtensionRegistry.Empty); - } - - public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - PrepareBuilder(); - pb::UnknownFieldSet.Builder unknownFields = null; - uint tag; - string field_name; - while (input.ReadTag(out tag, out field_name)) - { - if (tag == 0 && field_name != null) - { - int field_ordinal = global::System.Array.BinarySearch(_deltaFieldNames, field_name, global::System.StringComparer.Ordinal); - if (field_ordinal >= 0) - tag = _deltaFieldTags[field_ordinal]; - else - { - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - continue; - } - } - switch (tag) - { - case 0: - { - throw pb::InvalidProtocolBufferException.InvalidTag(); - } - default: - { - if (pb::WireFormat.IsEndGroupTag(tag)) - { - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - break; - } - case 10: - { - input.ReadMessageArray(tag, field_name, result.buckets_, global::Akka.Cluster.PubSub.Serializers.Proto.Delta.Types.Bucket.DefaultInstance, extensionRegistry); - break; - } - } - } - - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - - - public pbc::IPopsicleList BucketsList - { - get { return PrepareBuilder().buckets_; } - } - public int BucketsCount - { - get { return result.BucketsCount; } - } - public global::Akka.Cluster.PubSub.Serializers.Proto.Delta.Types.Bucket GetBuckets(int index) - { - return result.GetBuckets(index); - } - public Builder SetBuckets(int index, global::Akka.Cluster.PubSub.Serializers.Proto.Delta.Types.Bucket value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.buckets_[index] = value; - return this; - } - public Builder SetBuckets(int index, global::Akka.Cluster.PubSub.Serializers.Proto.Delta.Types.Bucket.Builder builderForValue) - { - pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); - PrepareBuilder(); - result.buckets_[index] = builderForValue.Build(); - return this; - } - public Builder AddBuckets(global::Akka.Cluster.PubSub.Serializers.Proto.Delta.Types.Bucket value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.buckets_.Add(value); - return this; - } - public Builder AddBuckets(global::Akka.Cluster.PubSub.Serializers.Proto.Delta.Types.Bucket.Builder builderForValue) - { - pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); - PrepareBuilder(); - result.buckets_.Add(builderForValue.Build()); - return this; - } - public Builder AddRangeBuckets(scg::IEnumerable values) - { - PrepareBuilder(); - result.buckets_.Add(values); - return this; - } - public Builder ClearBuckets() - { - PrepareBuilder(); - result.buckets_.Clear(); - return this; - } - } - static Delta() - { - object.ReferenceEquals(global::Akka.Cluster.PubSub.Serializers.Proto.DistributedPubSubMessages.Descriptor, null); - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class Address : pb::GeneratedMessage - { - private Address() { } - private static readonly Address defaultInstance = new Address().MakeReadOnly(); - private static readonly string[] _addressFieldNames = new string[] { "hostname", "port", "protocol", "system" }; - private static readonly uint[] _addressFieldTags = new uint[] { 18, 24, 34, 10 }; - public static Address DefaultInstance - { - get { return defaultInstance; } - } - - public override Address DefaultInstanceForType - { - get { return DefaultInstance; } - } - - protected override Address ThisMessage - { - get { return this; } - } - - public static pbd::MessageDescriptor Descriptor - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.DistributedPubSubMessages.internal__static_Address__Descriptor; } - } - - protected override pb::FieldAccess.FieldAccessorTable InternalFieldAccessors - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.DistributedPubSubMessages.internal__static_Address__FieldAccessorTable; } - } - - public const int SystemFieldNumber = 1; - private bool hasSystem; - private string system_ = ""; - public bool HasSystem - { - get { return hasSystem; } - } - public string System - { - get { return system_; } - } - - public const int HostnameFieldNumber = 2; - private bool hasHostname; - private string hostname_ = ""; - public bool HasHostname - { - get { return hasHostname; } - } - public string Hostname - { - get { return hostname_; } - } - - public const int PortFieldNumber = 3; - private bool hasPort; - private uint port_; - public bool HasPort - { - get { return hasPort; } - } - [global::System.CLSCompliant(false)] - public uint Port - { - get { return port_; } - } - - public const int ProtocolFieldNumber = 4; - private bool hasProtocol; - private string protocol_ = ""; - public bool HasProtocol - { - get { return hasProtocol; } - } - public string Protocol - { - get { return protocol_; } - } - - public override bool IsInitialized - { - get - { - if (!hasSystem) return false; - if (!hasHostname) return false; - if (!hasPort) return false; - return true; - } - } - - public override void WriteTo(pb::ICodedOutputStream output) - { - int size = SerializedSize; - string[] field_names = _addressFieldNames; - if (hasSystem) - { - output.WriteString(1, field_names[3], System); - } - if (hasHostname) - { - output.WriteString(2, field_names[0], Hostname); - } - if (hasPort) - { - output.WriteUInt32(3, field_names[1], Port); - } - if (hasProtocol) - { - output.WriteString(4, field_names[2], Protocol); - } - UnknownFields.WriteTo(output); - } - - private int memoizedSerializedSize = -1; - public override int SerializedSize - { - get - { - int size = memoizedSerializedSize; - if (size != -1) return size; - - size = 0; - if (hasSystem) - { - size += pb::CodedOutputStream.ComputeStringSize(1, System); - } - if (hasHostname) - { - size += pb::CodedOutputStream.ComputeStringSize(2, Hostname); - } - if (hasPort) - { - size += pb::CodedOutputStream.ComputeUInt32Size(3, Port); - } - if (hasProtocol) - { - size += pb::CodedOutputStream.ComputeStringSize(4, Protocol); - } - size += UnknownFields.SerializedSize; - memoizedSerializedSize = size; - return size; - } - } - - public static Address ParseFrom(pb::ByteString data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static Address ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static Address ParseFrom(byte[] data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static Address ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static Address ParseFrom(global::System.IO.Stream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static Address ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - public static Address ParseDelimitedFrom(global::System.IO.Stream input) - { - return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); - } - public static Address ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); - } - public static Address ParseFrom(pb::ICodedInputStream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static Address ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - private Address MakeReadOnly() - { - return this; - } - - public static Builder CreateBuilder() { return new Builder(); } - public override Builder ToBuilder() { return CreateBuilder(this); } - public override Builder CreateBuilderForType() { return new Builder(); } - public static Builder CreateBuilder(Address prototype) - { - return new Builder(prototype); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class Builder : pb::GeneratedBuilder - { - protected override Builder ThisBuilder - { - get { return this; } - } - public Builder() - { - result = DefaultInstance; - resultIsReadOnly = true; - } - internal Builder(Address cloneFrom) - { - result = cloneFrom; - resultIsReadOnly = true; - } - - private bool resultIsReadOnly; - private Address result; - - private Address PrepareBuilder() - { - if (resultIsReadOnly) - { - Address original = result; - result = new Address(); - resultIsReadOnly = false; - MergeFrom(original); - } - return result; - } - - public override bool IsInitialized - { - get { return result.IsInitialized; } - } - - protected override Address MessageBeingBuilt - { - get { return PrepareBuilder(); } - } - - public override Builder Clear() - { - result = DefaultInstance; - resultIsReadOnly = true; - return this; - } - - public override Builder Clone() - { - if (resultIsReadOnly) - { - return new Builder(result); - } - else - { - return new Builder().MergeFrom(result); - } - } - - public override pbd::MessageDescriptor DescriptorForType - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.Address.Descriptor; } - } - - public override Address DefaultInstanceForType - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.Address.DefaultInstance; } - } - - public override Address BuildPartial() - { - if (resultIsReadOnly) - { - return result; - } - resultIsReadOnly = true; - return result.MakeReadOnly(); - } - - public override Builder MergeFrom(pb::IMessage other) - { - if (other is Address) - { - return MergeFrom((Address)other); - } - else - { - base.MergeFrom(other); - return this; - } - } - - public override Builder MergeFrom(Address other) - { - if (other == global::Akka.Cluster.PubSub.Serializers.Proto.Address.DefaultInstance) return this; - PrepareBuilder(); - if (other.HasSystem) - { - System = other.System; - } - if (other.HasHostname) - { - Hostname = other.Hostname; - } - if (other.HasPort) - { - Port = other.Port; - } - if (other.HasProtocol) - { - Protocol = other.Protocol; - } - this.MergeUnknownFields(other.UnknownFields); - return this; - } - - public override Builder MergeFrom(pb::ICodedInputStream input) - { - return MergeFrom(input, pb::ExtensionRegistry.Empty); - } - - public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - PrepareBuilder(); - pb::UnknownFieldSet.Builder unknownFields = null; - uint tag; - string field_name; - while (input.ReadTag(out tag, out field_name)) - { - if (tag == 0 && field_name != null) - { - int field_ordinal = global::System.Array.BinarySearch(_addressFieldNames, field_name, global::System.StringComparer.Ordinal); - if (field_ordinal >= 0) - tag = _addressFieldTags[field_ordinal]; - else - { - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - continue; - } - } - switch (tag) - { - case 0: - { - throw pb::InvalidProtocolBufferException.InvalidTag(); - } - default: - { - if (pb::WireFormat.IsEndGroupTag(tag)) - { - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - break; - } - case 10: - { - result.hasSystem = input.ReadString(ref result.system_); - break; - } - case 18: - { - result.hasHostname = input.ReadString(ref result.hostname_); - break; - } - case 24: - { - result.hasPort = input.ReadUInt32(ref result.port_); - break; - } - case 34: - { - result.hasProtocol = input.ReadString(ref result.protocol_); - break; - } - } - } - - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - - - public bool HasSystem - { - get { return result.hasSystem; } - } - public string System - { - get { return result.System; } - set { SetSystem(value); } - } - public Builder SetSystem(string value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.hasSystem = true; - result.system_ = value; - return this; - } - public Builder ClearSystem() - { - PrepareBuilder(); - result.hasSystem = false; - result.system_ = ""; - return this; - } - - public bool HasHostname - { - get { return result.hasHostname; } - } - public string Hostname - { - get { return result.Hostname; } - set { SetHostname(value); } - } - public Builder SetHostname(string value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.hasHostname = true; - result.hostname_ = value; - return this; - } - public Builder ClearHostname() - { - PrepareBuilder(); - result.hasHostname = false; - result.hostname_ = ""; - return this; - } - - public bool HasPort - { - get { return result.hasPort; } - } - [global::System.CLSCompliant(false)] - public uint Port - { - get { return result.Port; } - set { SetPort(value); } - } - [global::System.CLSCompliant(false)] - public Builder SetPort(uint value) - { - PrepareBuilder(); - result.hasPort = true; - result.port_ = value; - return this; - } - public Builder ClearPort() - { - PrepareBuilder(); - result.hasPort = false; - result.port_ = 0; - return this; - } - - public bool HasProtocol - { - get { return result.hasProtocol; } - } - public string Protocol - { - get { return result.Protocol; } - set { SetProtocol(value); } - } - public Builder SetProtocol(string value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.hasProtocol = true; - result.protocol_ = value; - return this; - } - public Builder ClearProtocol() - { - PrepareBuilder(); - result.hasProtocol = false; - result.protocol_ = ""; - return this; - } - } - static Address() - { - object.ReferenceEquals(global::Akka.Cluster.PubSub.Serializers.Proto.DistributedPubSubMessages.Descriptor, null); - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class Send : pb::GeneratedMessage - { - private Send() { } - private static readonly Send defaultInstance = new Send().MakeReadOnly(); - private static readonly string[] _sendFieldNames = new string[] { "localAffinity", "path", "payload" }; - private static readonly uint[] _sendFieldTags = new uint[] { 16, 10, 26 }; - public static Send DefaultInstance - { - get { return defaultInstance; } - } - - public override Send DefaultInstanceForType - { - get { return DefaultInstance; } - } - - protected override Send ThisMessage - { - get { return this; } - } - - public static pbd::MessageDescriptor Descriptor - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.DistributedPubSubMessages.internal__static_Send__Descriptor; } - } - - protected override pb::FieldAccess.FieldAccessorTable InternalFieldAccessors - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.DistributedPubSubMessages.internal__static_Send__FieldAccessorTable; } - } - - public const int PathFieldNumber = 1; - private bool hasPath; - private string path_ = ""; - public bool HasPath - { - get { return hasPath; } - } - public string Path - { - get { return path_; } - } - - public const int LocalAffinityFieldNumber = 2; - private bool hasLocalAffinity; - private bool localAffinity_; - public bool HasLocalAffinity - { - get { return hasLocalAffinity; } - } - public bool LocalAffinity - { - get { return localAffinity_; } - } - - public const int PayloadFieldNumber = 3; - private bool hasPayload; - private global::Akka.Cluster.PubSub.Serializers.Proto.Payload payload_; - public bool HasPayload - { - get { return hasPayload; } - } - public global::Akka.Cluster.PubSub.Serializers.Proto.Payload Payload - { - get { return payload_ ?? global::Akka.Cluster.PubSub.Serializers.Proto.Payload.DefaultInstance; } - } - - public override bool IsInitialized - { - get - { - if (!hasPath) return false; - if (!hasLocalAffinity) return false; - if (!hasPayload) return false; - if (!Payload.IsInitialized) return false; - return true; - } - } - - public override void WriteTo(pb::ICodedOutputStream output) - { - int size = SerializedSize; - string[] field_names = _sendFieldNames; - if (hasPath) - { - output.WriteString(1, field_names[1], Path); - } - if (hasLocalAffinity) - { - output.WriteBool(2, field_names[0], LocalAffinity); - } - if (hasPayload) - { - output.WriteMessage(3, field_names[2], Payload); - } - UnknownFields.WriteTo(output); - } - - private int memoizedSerializedSize = -1; - public override int SerializedSize - { - get - { - int size = memoizedSerializedSize; - if (size != -1) return size; - - size = 0; - if (hasPath) - { - size += pb::CodedOutputStream.ComputeStringSize(1, Path); - } - if (hasLocalAffinity) - { - size += pb::CodedOutputStream.ComputeBoolSize(2, LocalAffinity); - } - if (hasPayload) - { - size += pb::CodedOutputStream.ComputeMessageSize(3, Payload); - } - size += UnknownFields.SerializedSize; - memoizedSerializedSize = size; - return size; - } - } - - public static Send ParseFrom(pb::ByteString data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static Send ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static Send ParseFrom(byte[] data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static Send ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static Send ParseFrom(global::System.IO.Stream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static Send ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - public static Send ParseDelimitedFrom(global::System.IO.Stream input) - { - return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); - } - public static Send ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); - } - public static Send ParseFrom(pb::ICodedInputStream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static Send ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - private Send MakeReadOnly() - { - return this; - } - - public static Builder CreateBuilder() { return new Builder(); } - public override Builder ToBuilder() { return CreateBuilder(this); } - public override Builder CreateBuilderForType() { return new Builder(); } - public static Builder CreateBuilder(Send prototype) - { - return new Builder(prototype); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class Builder : pb::GeneratedBuilder - { - protected override Builder ThisBuilder - { - get { return this; } - } - public Builder() - { - result = DefaultInstance; - resultIsReadOnly = true; - } - internal Builder(Send cloneFrom) - { - result = cloneFrom; - resultIsReadOnly = true; - } - - private bool resultIsReadOnly; - private Send result; - - private Send PrepareBuilder() - { - if (resultIsReadOnly) - { - Send original = result; - result = new Send(); - resultIsReadOnly = false; - MergeFrom(original); - } - return result; - } - - public override bool IsInitialized - { - get { return result.IsInitialized; } - } - - protected override Send MessageBeingBuilt - { - get { return PrepareBuilder(); } - } - - public override Builder Clear() - { - result = DefaultInstance; - resultIsReadOnly = true; - return this; - } - - public override Builder Clone() - { - if (resultIsReadOnly) - { - return new Builder(result); - } - else - { - return new Builder().MergeFrom(result); - } - } - - public override pbd::MessageDescriptor DescriptorForType - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.Send.Descriptor; } - } - - public override Send DefaultInstanceForType - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.Send.DefaultInstance; } - } - - public override Send BuildPartial() - { - if (resultIsReadOnly) - { - return result; - } - resultIsReadOnly = true; - return result.MakeReadOnly(); - } - - public override Builder MergeFrom(pb::IMessage other) - { - if (other is Send) - { - return MergeFrom((Send)other); - } - else - { - base.MergeFrom(other); - return this; - } - } - - public override Builder MergeFrom(Send other) - { - if (other == global::Akka.Cluster.PubSub.Serializers.Proto.Send.DefaultInstance) return this; - PrepareBuilder(); - if (other.HasPath) - { - Path = other.Path; - } - if (other.HasLocalAffinity) - { - LocalAffinity = other.LocalAffinity; - } - if (other.HasPayload) - { - MergePayload(other.Payload); - } - this.MergeUnknownFields(other.UnknownFields); - return this; - } - - public override Builder MergeFrom(pb::ICodedInputStream input) - { - return MergeFrom(input, pb::ExtensionRegistry.Empty); - } - - public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - PrepareBuilder(); - pb::UnknownFieldSet.Builder unknownFields = null; - uint tag; - string field_name; - while (input.ReadTag(out tag, out field_name)) - { - if (tag == 0 && field_name != null) - { - int field_ordinal = global::System.Array.BinarySearch(_sendFieldNames, field_name, global::System.StringComparer.Ordinal); - if (field_ordinal >= 0) - tag = _sendFieldTags[field_ordinal]; - else - { - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - continue; - } - } - switch (tag) - { - case 0: - { - throw pb::InvalidProtocolBufferException.InvalidTag(); - } - default: - { - if (pb::WireFormat.IsEndGroupTag(tag)) - { - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - break; - } - case 10: - { - result.hasPath = input.ReadString(ref result.path_); - break; - } - case 16: - { - result.hasLocalAffinity = input.ReadBool(ref result.localAffinity_); - break; - } - case 26: - { - global::Akka.Cluster.PubSub.Serializers.Proto.Payload.Builder subBuilder = global::Akka.Cluster.PubSub.Serializers.Proto.Payload.CreateBuilder(); - if (result.hasPayload) - { - subBuilder.MergeFrom(Payload); - } - input.ReadMessage(subBuilder, extensionRegistry); - Payload = subBuilder.BuildPartial(); - break; - } - } - } - - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - - - public bool HasPath - { - get { return result.hasPath; } - } - public string Path - { - get { return result.Path; } - set { SetPath(value); } - } - public Builder SetPath(string value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.hasPath = true; - result.path_ = value; - return this; - } - public Builder ClearPath() - { - PrepareBuilder(); - result.hasPath = false; - result.path_ = ""; - return this; - } - - public bool HasLocalAffinity - { - get { return result.hasLocalAffinity; } - } - public bool LocalAffinity - { - get { return result.LocalAffinity; } - set { SetLocalAffinity(value); } - } - public Builder SetLocalAffinity(bool value) - { - PrepareBuilder(); - result.hasLocalAffinity = true; - result.localAffinity_ = value; - return this; - } - public Builder ClearLocalAffinity() - { - PrepareBuilder(); - result.hasLocalAffinity = false; - result.localAffinity_ = false; - return this; - } - - public bool HasPayload - { - get { return result.hasPayload; } - } - public global::Akka.Cluster.PubSub.Serializers.Proto.Payload Payload - { - get { return result.Payload; } - set { SetPayload(value); } - } - public Builder SetPayload(global::Akka.Cluster.PubSub.Serializers.Proto.Payload value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.hasPayload = true; - result.payload_ = value; - return this; - } - public Builder SetPayload(global::Akka.Cluster.PubSub.Serializers.Proto.Payload.Builder builderForValue) - { - pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); - PrepareBuilder(); - result.hasPayload = true; - result.payload_ = builderForValue.Build(); - return this; - } - public Builder MergePayload(global::Akka.Cluster.PubSub.Serializers.Proto.Payload value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - if (result.hasPayload && - result.payload_ != global::Akka.Cluster.PubSub.Serializers.Proto.Payload.DefaultInstance) - { - result.payload_ = global::Akka.Cluster.PubSub.Serializers.Proto.Payload.CreateBuilder(result.payload_).MergeFrom(value).BuildPartial(); - } - else - { - result.payload_ = value; - } - result.hasPayload = true; - return this; - } - public Builder ClearPayload() - { - PrepareBuilder(); - result.hasPayload = false; - result.payload_ = null; - return this; - } - } - static Send() - { - object.ReferenceEquals(global::Akka.Cluster.PubSub.Serializers.Proto.DistributedPubSubMessages.Descriptor, null); - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class SendToAll : pb::GeneratedMessage - { - private SendToAll() { } - private static readonly SendToAll defaultInstance = new SendToAll().MakeReadOnly(); - private static readonly string[] _sendToAllFieldNames = new string[] { "allButSelf", "path", "payload" }; - private static readonly uint[] _sendToAllFieldTags = new uint[] { 16, 10, 26 }; - public static SendToAll DefaultInstance - { - get { return defaultInstance; } - } - - public override SendToAll DefaultInstanceForType - { - get { return DefaultInstance; } - } - - protected override SendToAll ThisMessage - { - get { return this; } - } - - public static pbd::MessageDescriptor Descriptor - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.DistributedPubSubMessages.internal__static_SendToAll__Descriptor; } - } - - protected override pb::FieldAccess.FieldAccessorTable InternalFieldAccessors - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.DistributedPubSubMessages.internal__static_SendToAll__FieldAccessorTable; } - } - - public const int PathFieldNumber = 1; - private bool hasPath; - private string path_ = ""; - public bool HasPath - { - get { return hasPath; } - } - public string Path - { - get { return path_; } - } - - public const int AllButSelfFieldNumber = 2; - private bool hasAllButSelf; - private bool allButSelf_; - public bool HasAllButSelf - { - get { return hasAllButSelf; } - } - public bool AllButSelf - { - get { return allButSelf_; } - } - - public const int PayloadFieldNumber = 3; - private bool hasPayload; - private global::Akka.Cluster.PubSub.Serializers.Proto.Payload payload_; - public bool HasPayload - { - get { return hasPayload; } - } - public global::Akka.Cluster.PubSub.Serializers.Proto.Payload Payload - { - get { return payload_ ?? global::Akka.Cluster.PubSub.Serializers.Proto.Payload.DefaultInstance; } - } - - public override bool IsInitialized - { - get - { - if (!hasPath) return false; - if (!hasAllButSelf) return false; - if (!hasPayload) return false; - if (!Payload.IsInitialized) return false; - return true; - } - } - - public override void WriteTo(pb::ICodedOutputStream output) - { - int size = SerializedSize; - string[] field_names = _sendToAllFieldNames; - if (hasPath) - { - output.WriteString(1, field_names[1], Path); - } - if (hasAllButSelf) - { - output.WriteBool(2, field_names[0], AllButSelf); - } - if (hasPayload) - { - output.WriteMessage(3, field_names[2], Payload); - } - UnknownFields.WriteTo(output); - } - - private int memoizedSerializedSize = -1; - public override int SerializedSize - { - get - { - int size = memoizedSerializedSize; - if (size != -1) return size; - - size = 0; - if (hasPath) - { - size += pb::CodedOutputStream.ComputeStringSize(1, Path); - } - if (hasAllButSelf) - { - size += pb::CodedOutputStream.ComputeBoolSize(2, AllButSelf); - } - if (hasPayload) - { - size += pb::CodedOutputStream.ComputeMessageSize(3, Payload); - } - size += UnknownFields.SerializedSize; - memoizedSerializedSize = size; - return size; - } - } - - public static SendToAll ParseFrom(pb::ByteString data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static SendToAll ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static SendToAll ParseFrom(byte[] data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static SendToAll ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static SendToAll ParseFrom(global::System.IO.Stream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static SendToAll ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - public static SendToAll ParseDelimitedFrom(global::System.IO.Stream input) - { - return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); - } - public static SendToAll ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); - } - public static SendToAll ParseFrom(pb::ICodedInputStream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static SendToAll ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - private SendToAll MakeReadOnly() - { - return this; - } - - public static Builder CreateBuilder() { return new Builder(); } - public override Builder ToBuilder() { return CreateBuilder(this); } - public override Builder CreateBuilderForType() { return new Builder(); } - public static Builder CreateBuilder(SendToAll prototype) - { - return new Builder(prototype); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class Builder : pb::GeneratedBuilder - { - protected override Builder ThisBuilder - { - get { return this; } - } - public Builder() - { - result = DefaultInstance; - resultIsReadOnly = true; - } - internal Builder(SendToAll cloneFrom) - { - result = cloneFrom; - resultIsReadOnly = true; - } - - private bool resultIsReadOnly; - private SendToAll result; - - private SendToAll PrepareBuilder() - { - if (resultIsReadOnly) - { - SendToAll original = result; - result = new SendToAll(); - resultIsReadOnly = false; - MergeFrom(original); - } - return result; - } - - public override bool IsInitialized - { - get { return result.IsInitialized; } - } - - protected override SendToAll MessageBeingBuilt - { - get { return PrepareBuilder(); } - } - - public override Builder Clear() - { - result = DefaultInstance; - resultIsReadOnly = true; - return this; - } - - public override Builder Clone() - { - if (resultIsReadOnly) - { - return new Builder(result); - } - else - { - return new Builder().MergeFrom(result); - } - } - - public override pbd::MessageDescriptor DescriptorForType - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.SendToAll.Descriptor; } - } - - public override SendToAll DefaultInstanceForType - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.SendToAll.DefaultInstance; } - } - - public override SendToAll BuildPartial() - { - if (resultIsReadOnly) - { - return result; - } - resultIsReadOnly = true; - return result.MakeReadOnly(); - } - - public override Builder MergeFrom(pb::IMessage other) - { - if (other is SendToAll) - { - return MergeFrom((SendToAll)other); - } - else - { - base.MergeFrom(other); - return this; - } - } - - public override Builder MergeFrom(SendToAll other) - { - if (other == global::Akka.Cluster.PubSub.Serializers.Proto.SendToAll.DefaultInstance) return this; - PrepareBuilder(); - if (other.HasPath) - { - Path = other.Path; - } - if (other.HasAllButSelf) - { - AllButSelf = other.AllButSelf; - } - if (other.HasPayload) - { - MergePayload(other.Payload); - } - this.MergeUnknownFields(other.UnknownFields); - return this; - } - - public override Builder MergeFrom(pb::ICodedInputStream input) - { - return MergeFrom(input, pb::ExtensionRegistry.Empty); - } - - public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - PrepareBuilder(); - pb::UnknownFieldSet.Builder unknownFields = null; - uint tag; - string field_name; - while (input.ReadTag(out tag, out field_name)) - { - if (tag == 0 && field_name != null) - { - int field_ordinal = global::System.Array.BinarySearch(_sendToAllFieldNames, field_name, global::System.StringComparer.Ordinal); - if (field_ordinal >= 0) - tag = _sendToAllFieldTags[field_ordinal]; - else - { - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - continue; - } - } - switch (tag) - { - case 0: - { - throw pb::InvalidProtocolBufferException.InvalidTag(); - } - default: - { - if (pb::WireFormat.IsEndGroupTag(tag)) - { - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - break; - } - case 10: - { - result.hasPath = input.ReadString(ref result.path_); - break; - } - case 16: - { - result.hasAllButSelf = input.ReadBool(ref result.allButSelf_); - break; - } - case 26: - { - global::Akka.Cluster.PubSub.Serializers.Proto.Payload.Builder subBuilder = global::Akka.Cluster.PubSub.Serializers.Proto.Payload.CreateBuilder(); - if (result.hasPayload) - { - subBuilder.MergeFrom(Payload); - } - input.ReadMessage(subBuilder, extensionRegistry); - Payload = subBuilder.BuildPartial(); - break; - } - } - } - - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - - - public bool HasPath - { - get { return result.hasPath; } - } - public string Path - { - get { return result.Path; } - set { SetPath(value); } - } - public Builder SetPath(string value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.hasPath = true; - result.path_ = value; - return this; - } - public Builder ClearPath() - { - PrepareBuilder(); - result.hasPath = false; - result.path_ = ""; - return this; - } - - public bool HasAllButSelf - { - get { return result.hasAllButSelf; } - } - public bool AllButSelf - { - get { return result.AllButSelf; } - set { SetAllButSelf(value); } - } - public Builder SetAllButSelf(bool value) - { - PrepareBuilder(); - result.hasAllButSelf = true; - result.allButSelf_ = value; - return this; - } - public Builder ClearAllButSelf() - { - PrepareBuilder(); - result.hasAllButSelf = false; - result.allButSelf_ = false; - return this; - } - - public bool HasPayload - { - get { return result.hasPayload; } - } - public global::Akka.Cluster.PubSub.Serializers.Proto.Payload Payload - { - get { return result.Payload; } - set { SetPayload(value); } - } - public Builder SetPayload(global::Akka.Cluster.PubSub.Serializers.Proto.Payload value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.hasPayload = true; - result.payload_ = value; - return this; - } - public Builder SetPayload(global::Akka.Cluster.PubSub.Serializers.Proto.Payload.Builder builderForValue) - { - pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); - PrepareBuilder(); - result.hasPayload = true; - result.payload_ = builderForValue.Build(); - return this; - } - public Builder MergePayload(global::Akka.Cluster.PubSub.Serializers.Proto.Payload value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - if (result.hasPayload && - result.payload_ != global::Akka.Cluster.PubSub.Serializers.Proto.Payload.DefaultInstance) - { - result.payload_ = global::Akka.Cluster.PubSub.Serializers.Proto.Payload.CreateBuilder(result.payload_).MergeFrom(value).BuildPartial(); - } - else - { - result.payload_ = value; - } - result.hasPayload = true; - return this; - } - public Builder ClearPayload() - { - PrepareBuilder(); - result.hasPayload = false; - result.payload_ = null; - return this; - } - } - static SendToAll() - { - object.ReferenceEquals(global::Akka.Cluster.PubSub.Serializers.Proto.DistributedPubSubMessages.Descriptor, null); - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class Publish : pb::GeneratedMessage - { - private Publish() { } - private static readonly Publish defaultInstance = new Publish().MakeReadOnly(); - private static readonly string[] _publishFieldNames = new string[] { "payload", "topic" }; - private static readonly uint[] _publishFieldTags = new uint[] { 26, 10 }; - public static Publish DefaultInstance - { - get { return defaultInstance; } - } - - public override Publish DefaultInstanceForType - { - get { return DefaultInstance; } - } - - protected override Publish ThisMessage - { - get { return this; } - } - - public static pbd::MessageDescriptor Descriptor - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.DistributedPubSubMessages.internal__static_Publish__Descriptor; } - } - - protected override pb::FieldAccess.FieldAccessorTable InternalFieldAccessors - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.DistributedPubSubMessages.internal__static_Publish__FieldAccessorTable; } - } - - public const int TopicFieldNumber = 1; - private bool hasTopic; - private string topic_ = ""; - public bool HasTopic - { - get { return hasTopic; } - } - public string Topic - { - get { return topic_; } - } - - public const int PayloadFieldNumber = 3; - private bool hasPayload; - private global::Akka.Cluster.PubSub.Serializers.Proto.Payload payload_; - public bool HasPayload - { - get { return hasPayload; } - } - public global::Akka.Cluster.PubSub.Serializers.Proto.Payload Payload - { - get { return payload_ ?? global::Akka.Cluster.PubSub.Serializers.Proto.Payload.DefaultInstance; } - } - - public override bool IsInitialized - { - get - { - if (!hasTopic) return false; - if (!hasPayload) return false; - if (!Payload.IsInitialized) return false; - return true; - } - } - - public override void WriteTo(pb::ICodedOutputStream output) - { - int size = SerializedSize; - string[] field_names = _publishFieldNames; - if (hasTopic) - { - output.WriteString(1, field_names[1], Topic); - } - if (hasPayload) - { - output.WriteMessage(3, field_names[0], Payload); - } - UnknownFields.WriteTo(output); - } - - private int memoizedSerializedSize = -1; - public override int SerializedSize - { - get - { - int size = memoizedSerializedSize; - if (size != -1) return size; - - size = 0; - if (hasTopic) - { - size += pb::CodedOutputStream.ComputeStringSize(1, Topic); - } - if (hasPayload) - { - size += pb::CodedOutputStream.ComputeMessageSize(3, Payload); - } - size += UnknownFields.SerializedSize; - memoizedSerializedSize = size; - return size; - } - } - - public static Publish ParseFrom(pb::ByteString data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static Publish ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static Publish ParseFrom(byte[] data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static Publish ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static Publish ParseFrom(global::System.IO.Stream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static Publish ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - public static Publish ParseDelimitedFrom(global::System.IO.Stream input) - { - return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); - } - public static Publish ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); - } - public static Publish ParseFrom(pb::ICodedInputStream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static Publish ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - private Publish MakeReadOnly() - { - return this; - } - - public static Builder CreateBuilder() { return new Builder(); } - public override Builder ToBuilder() { return CreateBuilder(this); } - public override Builder CreateBuilderForType() { return new Builder(); } - public static Builder CreateBuilder(Publish prototype) - { - return new Builder(prototype); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class Builder : pb::GeneratedBuilder - { - protected override Builder ThisBuilder - { - get { return this; } - } - public Builder() - { - result = DefaultInstance; - resultIsReadOnly = true; - } - internal Builder(Publish cloneFrom) - { - result = cloneFrom; - resultIsReadOnly = true; - } - - private bool resultIsReadOnly; - private Publish result; - - private Publish PrepareBuilder() - { - if (resultIsReadOnly) - { - Publish original = result; - result = new Publish(); - resultIsReadOnly = false; - MergeFrom(original); - } - return result; - } - - public override bool IsInitialized - { - get { return result.IsInitialized; } - } - - protected override Publish MessageBeingBuilt - { - get { return PrepareBuilder(); } - } - - public override Builder Clear() - { - result = DefaultInstance; - resultIsReadOnly = true; - return this; - } - - public override Builder Clone() - { - if (resultIsReadOnly) - { - return new Builder(result); - } - else - { - return new Builder().MergeFrom(result); - } - } - - public override pbd::MessageDescriptor DescriptorForType - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.Publish.Descriptor; } - } - - public override Publish DefaultInstanceForType - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.Publish.DefaultInstance; } - } - - public override Publish BuildPartial() - { - if (resultIsReadOnly) - { - return result; - } - resultIsReadOnly = true; - return result.MakeReadOnly(); - } - - public override Builder MergeFrom(pb::IMessage other) - { - if (other is Publish) - { - return MergeFrom((Publish)other); - } - else - { - base.MergeFrom(other); - return this; - } - } - - public override Builder MergeFrom(Publish other) - { - if (other == global::Akka.Cluster.PubSub.Serializers.Proto.Publish.DefaultInstance) return this; - PrepareBuilder(); - if (other.HasTopic) - { - Topic = other.Topic; - } - if (other.HasPayload) - { - MergePayload(other.Payload); - } - this.MergeUnknownFields(other.UnknownFields); - return this; - } - - public override Builder MergeFrom(pb::ICodedInputStream input) - { - return MergeFrom(input, pb::ExtensionRegistry.Empty); - } - - public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - PrepareBuilder(); - pb::UnknownFieldSet.Builder unknownFields = null; - uint tag; - string field_name; - while (input.ReadTag(out tag, out field_name)) - { - if (tag == 0 && field_name != null) - { - int field_ordinal = global::System.Array.BinarySearch(_publishFieldNames, field_name, global::System.StringComparer.Ordinal); - if (field_ordinal >= 0) - tag = _publishFieldTags[field_ordinal]; - else - { - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - continue; - } - } - switch (tag) - { - case 0: - { - throw pb::InvalidProtocolBufferException.InvalidTag(); - } - default: - { - if (pb::WireFormat.IsEndGroupTag(tag)) - { - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - break; - } - case 10: - { - result.hasTopic = input.ReadString(ref result.topic_); - break; - } - case 26: - { - global::Akka.Cluster.PubSub.Serializers.Proto.Payload.Builder subBuilder = global::Akka.Cluster.PubSub.Serializers.Proto.Payload.CreateBuilder(); - if (result.hasPayload) - { - subBuilder.MergeFrom(Payload); - } - input.ReadMessage(subBuilder, extensionRegistry); - Payload = subBuilder.BuildPartial(); - break; - } - } - } - - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - - - public bool HasTopic - { - get { return result.hasTopic; } - } - public string Topic - { - get { return result.Topic; } - set { SetTopic(value); } - } - public Builder SetTopic(string value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.hasTopic = true; - result.topic_ = value; - return this; - } - public Builder ClearTopic() - { - PrepareBuilder(); - result.hasTopic = false; - result.topic_ = ""; - return this; - } - - public bool HasPayload - { - get { return result.hasPayload; } - } - public global::Akka.Cluster.PubSub.Serializers.Proto.Payload Payload - { - get { return result.Payload; } - set { SetPayload(value); } - } - public Builder SetPayload(global::Akka.Cluster.PubSub.Serializers.Proto.Payload value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.hasPayload = true; - result.payload_ = value; - return this; - } - public Builder SetPayload(global::Akka.Cluster.PubSub.Serializers.Proto.Payload.Builder builderForValue) - { - pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); - PrepareBuilder(); - result.hasPayload = true; - result.payload_ = builderForValue.Build(); - return this; - } - public Builder MergePayload(global::Akka.Cluster.PubSub.Serializers.Proto.Payload value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - if (result.hasPayload && - result.payload_ != global::Akka.Cluster.PubSub.Serializers.Proto.Payload.DefaultInstance) - { - result.payload_ = global::Akka.Cluster.PubSub.Serializers.Proto.Payload.CreateBuilder(result.payload_).MergeFrom(value).BuildPartial(); - } - else - { - result.payload_ = value; - } - result.hasPayload = true; - return this; - } - public Builder ClearPayload() - { - PrepareBuilder(); - result.hasPayload = false; - result.payload_ = null; - return this; - } - } - static Publish() - { - object.ReferenceEquals(global::Akka.Cluster.PubSub.Serializers.Proto.DistributedPubSubMessages.Descriptor, null); - } - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class Payload : pb::GeneratedMessage - { - private Payload() { } - private static readonly Payload defaultInstance = new Payload().MakeReadOnly(); - private static readonly string[] _payloadFieldNames = new string[] { "enclosedMessage", "messageManifest", "serializerId" }; - private static readonly uint[] _payloadFieldTags = new uint[] { 10, 34, 16 }; - public static Payload DefaultInstance - { - get { return defaultInstance; } - } - - public override Payload DefaultInstanceForType - { - get { return DefaultInstance; } - } - - protected override Payload ThisMessage - { - get { return this; } - } - - public static pbd::MessageDescriptor Descriptor - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.DistributedPubSubMessages.internal__static_Payload__Descriptor; } - } - - protected override pb::FieldAccess.FieldAccessorTable InternalFieldAccessors - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.DistributedPubSubMessages.internal__static_Payload__FieldAccessorTable; } - } - - public const int EnclosedMessageFieldNumber = 1; - private bool hasEnclosedMessage; - private pb::ByteString enclosedMessage_ = pb::ByteString.Empty; - public bool HasEnclosedMessage - { - get { return hasEnclosedMessage; } - } - public pb::ByteString EnclosedMessage - { - get { return enclosedMessage_; } - } - - public const int SerializerIdFieldNumber = 2; - private bool hasSerializerId; - private int serializerId_; - public bool HasSerializerId - { - get { return hasSerializerId; } - } - public int SerializerId - { - get { return serializerId_; } - } - - public const int MessageManifestFieldNumber = 4; - private bool hasMessageManifest; - private pb::ByteString messageManifest_ = pb::ByteString.Empty; - public bool HasMessageManifest - { - get { return hasMessageManifest; } - } - public pb::ByteString MessageManifest - { - get { return messageManifest_; } - } - - public override bool IsInitialized - { - get - { - if (!hasEnclosedMessage) return false; - if (!hasSerializerId) return false; - return true; - } - } - - public override void WriteTo(pb::ICodedOutputStream output) - { - int size = SerializedSize; - string[] field_names = _payloadFieldNames; - if (hasEnclosedMessage) - { - output.WriteBytes(1, field_names[0], EnclosedMessage); - } - if (hasSerializerId) - { - output.WriteInt32(2, field_names[2], SerializerId); - } - if (hasMessageManifest) - { - output.WriteBytes(4, field_names[1], MessageManifest); - } - UnknownFields.WriteTo(output); - } - - private int memoizedSerializedSize = -1; - public override int SerializedSize - { - get - { - int size = memoizedSerializedSize; - if (size != -1) return size; - - size = 0; - if (hasEnclosedMessage) - { - size += pb::CodedOutputStream.ComputeBytesSize(1, EnclosedMessage); - } - if (hasSerializerId) - { - size += pb::CodedOutputStream.ComputeInt32Size(2, SerializerId); - } - if (hasMessageManifest) - { - size += pb::CodedOutputStream.ComputeBytesSize(4, MessageManifest); - } - size += UnknownFields.SerializedSize; - memoizedSerializedSize = size; - return size; - } - } - - public static Payload ParseFrom(pb::ByteString data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static Payload ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static Payload ParseFrom(byte[] data) - { - return ((Builder)CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static Payload ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static Payload ParseFrom(global::System.IO.Stream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static Payload ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - public static Payload ParseDelimitedFrom(global::System.IO.Stream input) - { - return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); - } - public static Payload ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) - { - return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); - } - public static Payload ParseFrom(pb::ICodedInputStream input) - { - return ((Builder)CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static Payload ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - return ((Builder)CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - private Payload MakeReadOnly() - { - return this; - } - - public static Builder CreateBuilder() { return new Builder(); } - public override Builder ToBuilder() { return CreateBuilder(this); } - public override Builder CreateBuilderForType() { return new Builder(); } - public static Builder CreateBuilder(Payload prototype) - { - return new Builder(prototype); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class Builder : pb::GeneratedBuilder - { - protected override Builder ThisBuilder - { - get { return this; } - } - public Builder() - { - result = DefaultInstance; - resultIsReadOnly = true; - } - internal Builder(Payload cloneFrom) - { - result = cloneFrom; - resultIsReadOnly = true; - } - - private bool resultIsReadOnly; - private Payload result; - - private Payload PrepareBuilder() - { - if (resultIsReadOnly) - { - Payload original = result; - result = new Payload(); - resultIsReadOnly = false; - MergeFrom(original); - } - return result; - } - - public override bool IsInitialized - { - get { return result.IsInitialized; } - } - - protected override Payload MessageBeingBuilt - { - get { return PrepareBuilder(); } - } - - public override Builder Clear() - { - result = DefaultInstance; - resultIsReadOnly = true; - return this; - } - - public override Builder Clone() - { - if (resultIsReadOnly) - { - return new Builder(result); - } - else - { - return new Builder().MergeFrom(result); - } - } - - public override pbd::MessageDescriptor DescriptorForType - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.Payload.Descriptor; } - } - - public override Payload DefaultInstanceForType - { - get { return global::Akka.Cluster.PubSub.Serializers.Proto.Payload.DefaultInstance; } - } - - public override Payload BuildPartial() - { - if (resultIsReadOnly) - { - return result; - } - resultIsReadOnly = true; - return result.MakeReadOnly(); - } - - public override Builder MergeFrom(pb::IMessage other) - { - if (other is Payload) - { - return MergeFrom((Payload)other); - } - else - { - base.MergeFrom(other); - return this; - } - } - - public override Builder MergeFrom(Payload other) - { - if (other == global::Akka.Cluster.PubSub.Serializers.Proto.Payload.DefaultInstance) return this; - PrepareBuilder(); - if (other.HasEnclosedMessage) - { - EnclosedMessage = other.EnclosedMessage; - } - if (other.HasSerializerId) - { - SerializerId = other.SerializerId; - } - if (other.HasMessageManifest) - { - MessageManifest = other.MessageManifest; - } - this.MergeUnknownFields(other.UnknownFields); - return this; - } - - public override Builder MergeFrom(pb::ICodedInputStream input) - { - return MergeFrom(input, pb::ExtensionRegistry.Empty); - } - - public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) - { - PrepareBuilder(); - pb::UnknownFieldSet.Builder unknownFields = null; - uint tag; - string field_name; - while (input.ReadTag(out tag, out field_name)) - { - if (tag == 0 && field_name != null) - { - int field_ordinal = global::System.Array.BinarySearch(_payloadFieldNames, field_name, global::System.StringComparer.Ordinal); - if (field_ordinal >= 0) - tag = _payloadFieldTags[field_ordinal]; - else - { - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - continue; - } - } - switch (tag) - { - case 0: - { - throw pb::InvalidProtocolBufferException.InvalidTag(); - } - default: - { - if (pb::WireFormat.IsEndGroupTag(tag)) - { - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - if (unknownFields == null) - { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - break; - } - case 10: - { - result.hasEnclosedMessage = input.ReadBytes(ref result.enclosedMessage_); - break; - } - case 16: - { - result.hasSerializerId = input.ReadInt32(ref result.serializerId_); - break; - } - case 34: - { - result.hasMessageManifest = input.ReadBytes(ref result.messageManifest_); - break; - } - } - } - - if (unknownFields != null) - { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - - - public bool HasEnclosedMessage - { - get { return result.hasEnclosedMessage; } - } - public pb::ByteString EnclosedMessage - { - get { return result.EnclosedMessage; } - set { SetEnclosedMessage(value); } - } - public Builder SetEnclosedMessage(pb::ByteString value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.hasEnclosedMessage = true; - result.enclosedMessage_ = value; - return this; - } - public Builder ClearEnclosedMessage() - { - PrepareBuilder(); - result.hasEnclosedMessage = false; - result.enclosedMessage_ = pb::ByteString.Empty; - return this; - } - - public bool HasSerializerId - { - get { return result.hasSerializerId; } - } - public int SerializerId - { - get { return result.SerializerId; } - set { SetSerializerId(value); } - } - public Builder SetSerializerId(int value) - { - PrepareBuilder(); - result.hasSerializerId = true; - result.serializerId_ = value; - return this; - } - public Builder ClearSerializerId() - { - PrepareBuilder(); - result.hasSerializerId = false; - result.serializerId_ = 0; - return this; - } - - public bool HasMessageManifest - { - get { return result.hasMessageManifest; } - } - public pb::ByteString MessageManifest - { - get { return result.MessageManifest; } - set { SetMessageManifest(value); } - } - public Builder SetMessageManifest(pb::ByteString value) - { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.hasMessageManifest = true; - result.messageManifest_ = value; - return this; - } - public Builder ClearMessageManifest() - { - PrepareBuilder(); - result.hasMessageManifest = false; - result.messageManifest_ = pb::ByteString.Empty; - return this; - } - } - static Payload() - { - object.ReferenceEquals(global::Akka.Cluster.PubSub.Serializers.Proto.DistributedPubSubMessages.Descriptor, null); - } - } - - #endregion - -} - -#endregion Designer generated code diff --git a/src/contrib/cluster/Akka.Cluster.Tools/PublishSubscribe/reference.conf b/src/contrib/cluster/Akka.Cluster.Tools/PublishSubscribe/reference.conf deleted file mode 100644 index 2dd6a5ddcec..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools/PublishSubscribe/reference.conf +++ /dev/null @@ -1,51 +0,0 @@ -############################################ -# Akka Cluster Tools Reference Config File # -############################################ - -# This is the reference config file that contains all the default settings. -# Make your edits/overrides in your application.conf. - -# //#pub-sub-ext-config -# Settings for the DistributedPubSub extension -akka.cluster.pub-sub { - # Actor name of the mediator actor, /system/distributedPubSubMediator - name = distributedPubSubMediator - - # Start the mediator on members tagged with this role. - # All members are used if undefined or empty. - role = "" - - # The routing logic to use for 'Send' - # Possible values: random, round-robin, broadcast - routing-logic = random - - # How often the DistributedPubSubMediator should send out gossip information - gossip-interval = 1s - - # Removed entries are pruned after this duration - removed-time-to-live = 120s - - # Maximum number of elements to transfer in one message when synchronizing the registries. - # Next chunk will be transferred in next round of gossip. - max-delta-elements = 3000 - - # The id of the dispatcher to use for DistributedPubSubMediator actors. - # If not specified default dispatcher is used. - # If specified you need to define the settings of the actual dispatcher. - use-dispatcher = "" - -} -# //#pub-sub-ext-config - -# Protobuf serializer for cluster DistributedPubSubMeditor messages -akka.actor { - serializers { - akka-pubsub = "Akka.Cluster.Tools.PublishSubscribe.Serializers.DistributedPubSubMessageSerializer, Akka.Cluster.Tools" - } - serialization-bindings { - "Akka.Cluster.Tools.PublishSubscribe.IDistributedPubSubMessage, Akka.Cluster.Tools" = akka-pubsub - } - serialization-identifiers { - "Akka.Cluster.Tools.PublishSubscribe.Serializers.DistributedPubSubMessageSerializer, Akka.Cluster.Tools" = 9 - } -} diff --git a/src/contrib/cluster/Akka.Cluster.Tools/Singleton/ClusterSingletonManager.cs b/src/contrib/cluster/Akka.Cluster.Tools/Singleton/ClusterSingletonManager.cs deleted file mode 100644 index 7eb564b3979..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools/Singleton/ClusterSingletonManager.cs +++ /dev/null @@ -1,760 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using System.Collections.Immutable; -using System.Linq; -using System.Runtime.Serialization; -using Akka.Actor; -using Akka.Configuration; -using Akka.Event; -using Akka.Remote; - -namespace Akka.Cluster.Tools.Singleton -{ - [Serializable] - internal enum ClusterSingletonMessage - { - HandOverToMe, - HandOverInProgress, - HandOverDone, - TakeOverFromMe, - Cleanup - } - - [Serializable] - internal sealed class StartOldestChangedBuffer - { - public static readonly StartOldestChangedBuffer Instance = new StartOldestChangedBuffer(); - private StartOldestChangedBuffer() { } - } - - [Serializable] - internal sealed class HandOverRetry - { - public readonly int Count; - - public HandOverRetry(int count) - { - Count = count; - } - } - - [Serializable] - internal sealed class TakeOverRetry - { - public readonly int Count; - - public TakeOverRetry(int count) - { - Count = count; - } - } - - public interface IClusterSingletonData { } - - [Serializable] - internal sealed class Uninitialized : IClusterSingletonData - { - public static readonly Uninitialized Instance = new Uninitialized(); - private Uninitialized() { } - } - - [Serializable] - internal sealed class YoungerData : IClusterSingletonData - { - public readonly Address Oldest; - - public YoungerData(Address oldest) - { - Oldest = oldest; - } - } - - [Serializable] - internal sealed class BecomingOldestData : IClusterSingletonData - { - public readonly Address PreviousOldest; - - public BecomingOldestData(Address previousOldest) - { - PreviousOldest = previousOldest; - } - } - - [Serializable] - internal sealed class OldestData : IClusterSingletonData - { - public readonly IActorRef Singleton; - public readonly bool SingletonTerminated; - - public OldestData(IActorRef singleton, bool singletonTerminated) - { - Singleton = singleton; - SingletonTerminated = singletonTerminated; - } - } - - [Serializable] - internal sealed class WasOldestData : IClusterSingletonData - { - public readonly IActorRef Singleton; - public readonly bool SingletonTerminated; - public readonly Address NewOldest; - - public WasOldestData(IActorRef singleton, bool singletonTerminated, Address newOldest) - { - Singleton = singleton; - SingletonTerminated = singletonTerminated; - NewOldest = newOldest; - } - } - - [Serializable] - internal sealed class HandingOverData : IClusterSingletonData - { - public readonly IActorRef Singleton; - public readonly IActorRef HandOverTo; - - public HandingOverData(IActorRef singleton, IActorRef handOverTo) - { - Singleton = singleton; - HandOverTo = handOverTo; - } - } - - [Serializable] - internal sealed class EndData : IClusterSingletonData - { - public static readonly EndData Instance = new EndData(); - - public EndData() - { - } - } - - [Serializable] - internal sealed class DelayedMemberRemoved - { - public readonly Member Member; - - public DelayedMemberRemoved(Member member) - { - Member = member; - } - } - - [Serializable] - public enum ClusterSingletonState - { - Start, - Oldest, - Younger, - BecomingOldest, - WasOldest, - HandingOver, - TakeOver, - End - } - - /// - /// Thrown when a consistent state can't be determined within the defined retry limits. - /// Eventually it will reach a stable state and can continue, and that is simplified - /// by starting over with a clean state. Parent supervisor should typically restart the actor, i.e. default decision. - /// - public sealed class ClusterSingletonManagerIsStuck : AkkaException - { - public ClusterSingletonManagerIsStuck(string message) : base(message) { } - - public ClusterSingletonManagerIsStuck(SerializationInfo info, StreamingContext context) : base(info, context) - { - } - } - - /// - /// - /// Manages singleton actor instance among all cluster nodes or a group of nodes tagged with a specific role. - /// At most one singleton instance is running at any point in time. - /// - /// - /// The ClusterSingletonManager is supposed to be started on all nodes, or all nodes with specified role, - /// in the cluster with . The actual singleton is started on the oldest node - /// by creating a child actor from the supplied `singletonProps`. - /// - /// - /// The singleton actor is always running on the oldest member with specified role. The oldest member is determined - /// by . This can change when removing members. A graceful hand over can normally - /// be performed when current oldest node is leaving the cluster. Be aware that there is a short time period when - /// there is no active singleton during the hand-over process. - /// - /// - /// The cluster failure detector will notice when oldest node becomes unreachable due to things like CLR crash, - /// hard shut down, or network failure. When the crashed node has been removed (via down) from the cluster then - /// a new oldest node will take over and a new singleton actor is created.For these failure scenarios there - /// will not be a graceful hand-over, but more than one active singletons is prevented by all reasonable means. - /// Some corner cases are eventually resolved by configurable timeouts. - /// - /// - /// You access the singleton actor with . Alternatively the singleton actor may - /// broadcast its existence when it is started. - /// - /// - /// Use factory method to create the for the actor. - /// - /// - public sealed class ClusterSingletonManager : FSM - { - /// - /// Returns default HOCON configuration for the cluster singleton. - /// - public static Config DefaultConfig() - { - return ConfigurationFactory.FromResource("Akka.Cluster.Tools.Singleton.reference.conf"); - } - - /// - /// Creates props for the current cluster singleton manager using - /// as the default termination message. - /// - /// of the singleton actor instance. - /// Cluster singleton manager settings. - /// - public static Props Props(Props singletonProps, ClusterSingletonManagerSettings settings) - { - return Props(singletonProps, PoisonPill.Instance, settings); - } - - /// - /// Creates props for the current cluster singleton manager. - /// - /// of the singleton actor instance. - /// - /// When handing over to a new oldest node this is sent to the singleton actor - /// to tell it to finish its work, close resources, and stop. The hand-over to the new oldest node - /// is completed when the singleton actor is terminated. Note that is a - /// perfectly fine if you only need to stop the actor. - /// - /// Cluster singleton manager settings. - public static Props Props(Props singletonProps, object terminationMessage, ClusterSingletonManagerSettings settings) - { - return Actor.Props.Create(() => new ClusterSingletonManager(singletonProps, terminationMessage, settings)).WithDeploy(Deploy.Local); - } - - private readonly Props _singletonProps; - private readonly object _terminationMessage; - private readonly ClusterSingletonManagerSettings _settings; - - private const string HandOverRetryTimer = "hand-over-retry"; - private const string TakeOverRetryTimer = "take-over-retry"; - private const string CleanupTimer = "cleanup"; - - // Previous GetNext request delivered event and new GetNext is to be sent - private bool _oldestChangedReceived = true; - private bool _selfExited; - - // started when when self member is Up - private IActorRef _oldestChangedBuffer; - // keep track of previously removed members - private ImmutableDictionary _removed = ImmutableDictionary.Empty; - private readonly int _maxHandOverRetries; - private readonly int _maxTakeOverRetries; - private readonly Cluster _cluster = Cluster.Get(Context.System); - private ILoggingAdapter _log; - - public ClusterSingletonManager(Props singletonProps, object terminationMessage, ClusterSingletonManagerSettings settings) - { - var role = settings.Role; - if (!string.IsNullOrEmpty(role) && !_cluster.SelfRoles.Contains(role)) - throw new ArgumentException(string.Format("This cluster member [{0}] doesn't have the role [{1}]", _cluster.SelfAddress, role)); - - _singletonProps = singletonProps; - _terminationMessage = terminationMessage; - _settings = settings; - - var n = (int)(_settings.RemovalMargin.TotalMilliseconds / _settings.HandOverRetryInterval.TotalMilliseconds); - _maxHandOverRetries = n + 3; - _maxTakeOverRetries = Math.Max(1, n - 3); - - InitializeFSM(); - } - - private ILoggingAdapter Log { get { return _log ?? (_log = Context.GetLogger()); } } - - protected override void PreStart() - { - base.PreStart(); - - // subscribe to cluster changes, re-subscribe when restart - _cluster.Subscribe(Self, new[] { typeof(ClusterEvent.MemberExited), typeof(ClusterEvent.MemberRemoved) }); - - SetTimer(CleanupTimer, ClusterSingletonMessage.Cleanup, TimeSpan.FromMinutes(1.0), repeat: true); - - // defer subscription to avoid some jitter when - // starting/joining several nodes at the same time - var self = Self; - _cluster.RegisterOnMemberUp(() => self.Tell(StartOldestChangedBuffer.Instance)); - } - - protected override void PostStop() - { - CancelTimer(CleanupTimer); - _cluster.Unsubscribe(Self); - base.PostStop(); - } - - private void AddRemoved(Address address) - { - _removed = _removed.Add(address, Deadline.Now + TimeSpan.FromMinutes(15.0)); - } - - private void CleanupOverdueNotMemberAnyMore() - { - _removed = _removed.Where(kv => kv.Value.IsOverdue).ToImmutableDictionary(); - } - - private ActorSelection Peer(Address at) - { - return Context.ActorSelection(Self.Path.ToStringWithAddress(at)); - } - - private void GetNextOldestChange() - { - if (_oldestChangedReceived) - { - _oldestChangedReceived = false; - _oldestChangedBuffer.Tell(OldestChangedBuffer.GetNext.Instance); - } - } - - private State GoToOldest() - { - Log.Info("Singleton manager [{0}] starting singleton actor", _cluster.SelfAddress); - var singleton = Context.Watch(Context.ActorOf(_singletonProps, _settings.SingletonName)); - return - GoTo(ClusterSingletonState.Oldest).Using(new OldestData(singleton, false)); - } - - private State HandleHandOverDone(IActorRef handOverTo) - { - Address newOldest = null; - - if (handOverTo != null) - { - newOldest = handOverTo.Path.Address; - handOverTo.Tell(ClusterSingletonMessage.HandOverDone); - } - - Log.Info("Singleton terminated, hand-over done [{0} -> {1}]", _cluster.SelfAddress, newOldest); - - if (_removed.ContainsKey(_cluster.SelfAddress)) - { - Log.Info("Self removed, stopping ClusterSingletonManager"); - return Stop(); - } - else if (_selfExited) - { - return GoTo(ClusterSingletonState.End).Using(new EndData()); - } - - return GoTo(ClusterSingletonState.Younger).Using(new YoungerData(newOldest)); - } - - private State GoToHandingOver(IActorRef singleton, bool singletonTerminated, IActorRef handOverTo) - { - if (singletonTerminated) return HandleHandOverDone(handOverTo); - - if (handOverTo != null) handOverTo.Tell(ClusterSingletonMessage.HandOverInProgress); - - singleton.Tell(_terminationMessage); - - return GoTo(ClusterSingletonState.HandingOver).Using(new HandingOverData(singleton, handOverTo)); - } - - - private void InitializeFSM() - { - When(ClusterSingletonState.Start, e => - { - if (e.FsmEvent is StartOldestChangedBuffer) - { - _oldestChangedBuffer = Context.ActorOf(Actor.Props.Create(_settings.Role).WithDispatcher(Context.Props.Dispatcher)); - GetNextOldestChange(); - return Stay(); - } - else if (e.FsmEvent is OldestChangedBuffer.InitialOldestState) - { - var initialOldestState = (OldestChangedBuffer.InitialOldestState)e.FsmEvent; - _oldestChangedReceived = true; - var isSelfOldest = _cluster.SelfAddress.Equals(initialOldestState.Oldest); - - if (isSelfOldest && initialOldestState.SafeToBeOldest) - return GoToOldest(); - else if (isSelfOldest) - return GoTo(ClusterSingletonState.BecomingOldest).Using(new BecomingOldestData(null)); - else - return GoTo(ClusterSingletonState.Younger).Using(new YoungerData(initialOldestState.Oldest)); - } - else return null; - }); - - When(ClusterSingletonState.Younger, e => - { - DelayedMemberRemoved removed; - YoungerData youngerData; - if (e.FsmEvent is OldestChangedBuffer.OldestChanged && (youngerData = e.StateData as YoungerData) != null) - { - var oldestChanged = (OldestChangedBuffer.OldestChanged)e.FsmEvent; - - Log.Info("Younger observed OldestChanged: [{0} -> myself]", youngerData.Oldest); - - _oldestChangedReceived = true; - if (oldestChanged.Oldest.Equals(_cluster.SelfAddress)) - { - if (youngerData.Oldest == null) return GoToOldest(); - else if (_removed.ContainsKey(youngerData.Oldest)) return GoToOldest(); - else - { - Peer(youngerData.Oldest).Tell(ClusterSingletonMessage.HandOverToMe); - return GoTo(ClusterSingletonState.BecomingOldest).Using(new BecomingOldestData(youngerData.Oldest)); - } - } - else - { - GetNextOldestChange(); - return Stay().Using(new YoungerData(oldestChanged.Oldest)); - } - } - else if (e.FsmEvent is ClusterEvent.MemberRemoved) - { - var m = ((ClusterEvent.MemberRemoved)e.FsmEvent).Member; - if (m.Address.Equals(_cluster.SelfAddress)) - { - Log.Info("Self removed, stopping ClusterSingletonManager"); - return Stop(); - } - else - { - ScheduleDelayedMemberRemoved(m); - return Stay(); - } - } - else if ((removed = e.FsmEvent as DelayedMemberRemoved) != null - && (youngerData = e.StateData as YoungerData) != null - && removed.Member.Address.Equals(youngerData.Oldest)) - { - Log.Info("Previous oldest removed [{0}]", removed.Member.Address); - AddRemoved(removed.Member.Address); - // transition when OldestChanged - return Stay().Using(new YoungerData(null)); - } - else return null; - }); - - When(ClusterSingletonState.BecomingOldest, e => - { - DelayedMemberRemoved removed; - var becomingOldest = e.StateData as BecomingOldestData; - if (e.FsmEvent is ClusterSingletonMessage) - { - var m = (ClusterSingletonMessage)e.FsmEvent; - switch (m) - { - case ClusterSingletonMessage.HandOverInProgress: - // confirmation that the hand-over process has started - Log.Info("Hand-over in progress at [{0}]", Sender.Path.Address); - CancelTimer(HandOverRetryTimer); - return Stay(); - case ClusterSingletonMessage.HandOverDone: - if (becomingOldest == null || becomingOldest.PreviousOldest == null) return null; - else - { - if (Sender.Path.Address.Equals(becomingOldest.PreviousOldest)) - return GoToOldest(); - else - { - Log.Info("Ignoring HandOverDone in BecomingOldest from [{0}]. Expected previous oldest [{1}]", Sender.Path.Address, becomingOldest.PreviousOldest); - return Stay(); - } - } - case ClusterSingletonMessage.TakeOverFromMe: - if (becomingOldest == null) return null; - else - { - if (becomingOldest.PreviousOldest == null) - { - Sender.Tell(ClusterSingletonMessage.HandOverToMe); - return Stay().Using(new BecomingOldestData(Sender.Path.Address)); - } - else - { - if (becomingOldest.PreviousOldest.Equals(Sender.Path.Address)) - Sender.Tell(ClusterSingletonMessage.HandOverToMe); - else - Log.Info("Ignoring TakeOver request in BecomingOldest from [{0}]. Expected previous oldest [{1}]", Sender.Path.Address, becomingOldest.PreviousOldest); - - return Stay(); - } - } - default: - return null; - } - } - else if (e.FsmEvent is ClusterEvent.MemberRemoved) - { - var member = ((ClusterEvent.MemberRemoved)e.FsmEvent).Member; - if (member.Address.Equals(_cluster.SelfAddress)) - { - Log.Info("Self removed, stopping ClusterSingletonManager"); - return Stop(); - } - else - { - ScheduleDelayedMemberRemoved(member); - return Stay(); - } - } - else if ((removed = e.FsmEvent as DelayedMemberRemoved) != null - && becomingOldest != null - && removed.Member.Address.Equals(becomingOldest.PreviousOldest)) - { - Log.Info("Previous oldest [{0}] removed", becomingOldest.PreviousOldest); - AddRemoved(removed.Member.Address); - return GoToOldest(); - } - else if (e.FsmEvent is HandOverRetry && becomingOldest != null) - { - var handOverRetry = (HandOverRetry)e.FsmEvent; - if (handOverRetry.Count <= _maxHandOverRetries) - { - Log.Info("Retry [{0}], sending HandOverToMe to [{1}]", handOverRetry.Count, becomingOldest.PreviousOldest); - if (becomingOldest.PreviousOldest != null) - Peer(becomingOldest.PreviousOldest).Tell(ClusterSingletonMessage.HandOverToMe); - - SetTimer(HandOverRetryTimer, new HandOverRetry(handOverRetry.Count + 1), _settings.HandOverRetryInterval, repeat: false); - return Stay(); - } - else if (becomingOldest.PreviousOldest != null && _removed.ContainsKey(becomingOldest.PreviousOldest)) - { - // can't send HandOverToMe, previousOldest unknown for new node (or restart) - // previous oldest might be down or removed, so no TakeOverFromMe message is received - Log.Info("Timeout in BecomingOldest. Previous oldest unknown, removed and no TakeOver request."); - return GoToOldest(); - } - else - { - throw new ClusterSingletonManagerIsStuck(string.Format("Becoming singleton oldest was stuck because previous oldest [{0}] is unresponsive", becomingOldest.PreviousOldest)); - } - } - else return null; - }); - - When(ClusterSingletonState.Oldest, e => - { - Terminated terminated; - var oldestData = e.StateData as OldestData; - if (e.FsmEvent is OldestChangedBuffer.OldestChanged && oldestData != null) - { - var oldestChanged = (OldestChangedBuffer.OldestChanged)e.FsmEvent; - Log.Info("Oldest observed OldestChanged: [{0} -> {1}]", _cluster.SelfAddress, oldestChanged.Oldest); - - _oldestChangedReceived = true; - if (oldestChanged.Oldest != null) - { - if (oldestChanged.Oldest.Equals(_cluster.SelfAddress)) - return Stay(); - else if (!_selfExited && _removed.ContainsKey(oldestChanged.Oldest)) - return GoToHandingOver(oldestData.Singleton, oldestData.SingletonTerminated, null); - else - { - // send TakeOver request in case the new oldest doesn't know previous oldest - Peer(oldestChanged.Oldest).Tell(ClusterSingletonMessage.TakeOverFromMe); - SetTimer(TakeOverRetryTimer, new TakeOverRetry(1), _settings.HandOverRetryInterval); - return GoTo(ClusterSingletonState.WasOldest) - .Using(new WasOldestData(oldestData.Singleton, oldestData.SingletonTerminated, oldestChanged.Oldest)); - } - } - else - { - // new oldest will initiate the hand-over - SetTimer(TakeOverRetryTimer, new TakeOverRetry(1), _settings.HandOverRetryInterval); - return GoTo(ClusterSingletonState.WasOldest).Using(new WasOldestData(oldestData.Singleton, oldestData.SingletonTerminated, null)); - } - } - else if (e.FsmEvent.Equals(ClusterSingletonMessage.HandOverToMe) && oldestData != null) - { - return GoToHandingOver(oldestData.Singleton, oldestData.SingletonTerminated, Sender); - } - else if ((terminated = e.FsmEvent as Terminated) != null - && oldestData != null - && terminated.ActorRef.Equals(oldestData.Singleton)) - { - return Stay().Using(new OldestData(oldestData.Singleton, true)); - } - else return null; - }); - - When(ClusterSingletonState.WasOldest, e => - { - ClusterEvent.MemberRemoved removed; - Terminated terminated; - var wasOldestData = e.StateData as WasOldestData; - if (e.FsmEvent is TakeOverRetry && wasOldestData != null) - { - var takeOverRetry = (TakeOverRetry)e.FsmEvent; - if (takeOverRetry.Count <= _maxTakeOverRetries) - { - Log.Info("Retry [{0}], sending TakeOverFromMe to [{1}]", takeOverRetry.Count, wasOldestData.NewOldest); - - if (wasOldestData.NewOldest != null) - Peer(wasOldestData.NewOldest).Tell(ClusterSingletonMessage.TakeOverFromMe); - - SetTimer(TakeOverRetryTimer, new TakeOverRetry(takeOverRetry.Count), _settings.HandOverRetryInterval); - return Stay(); - } - else - throw new ClusterSingletonManagerIsStuck(string.Format("Expected hand-over to [{0}] never occured", wasOldestData.NewOldest)); - } - else if (e.FsmEvent.Equals(ClusterSingletonMessage.HandOverToMe) && wasOldestData != null) - { - return GoToHandingOver(wasOldestData.Singleton, wasOldestData.SingletonTerminated, Sender); - } - else if ((removed = e.FsmEvent as ClusterEvent.MemberRemoved) != null - && !_selfExited && removed.Member.Address.Equals(_cluster.SelfAddress)) - { - Log.Info("Self removed, stopping ClusterSingletonManager"); - return Stop(); - } - else if ((removed = e.FsmEvent as ClusterEvent.MemberRemoved) != null - && wasOldestData != null && wasOldestData.NewOldest != null && !_selfExited - && removed.Member.Address.Equals(wasOldestData.NewOldest)) - { - AddRemoved(removed.Member.Address); - return GoToHandingOver(wasOldestData.Singleton, wasOldestData.SingletonTerminated, null); - } - else if ((terminated = e.FsmEvent as Terminated) != null && wasOldestData != null - && terminated.ActorRef.Equals(wasOldestData.Singleton)) - { - return Stay().Using(new WasOldestData(wasOldestData.Singleton, true, wasOldestData.NewOldest)); - } - return null; - }); - - When(ClusterSingletonState.HandingOver, e => - { - var handingOverData = e.StateData as HandingOverData; - if (handingOverData != null) - { - Terminated terminated; - if ((terminated = e.FsmEvent as Terminated) != null && - terminated.ActorRef.Equals(handingOverData.Singleton)) - { - return HandleHandOverDone(handingOverData.HandOverTo); - } - if (e.FsmEvent.Equals(ClusterSingletonMessage.HandOverToMe) - && handingOverData.HandOverTo.Equals(Sender)) - { - Sender.Tell(ClusterSingletonMessage.HandOverInProgress); - return Stay(); - } - } - return null; - }); - - When(ClusterSingletonState.End, e => - { - var removed = e.FsmEvent as ClusterEvent.MemberRemoved; - if (removed != null && removed.Member.Address.Equals(_cluster.SelfAddress)) - { - Log.Info("Self removed, stopping ClusterSingletonManager"); - return Stop(); - } - return null; - }); - - WhenUnhandled(e => - { - var removed = e.FsmEvent as ClusterEvent.MemberRemoved; - if (e.FsmEvent is ClusterEvent.CurrentClusterState) return Stay(); - if (e.FsmEvent is ClusterEvent.MemberExited) - { - var m = ((ClusterEvent.MemberExited)e.FsmEvent).Member; - if (m.Address.Equals(_cluster.SelfAddress)) - { - _selfExited = true; - Log.Info("Exited [{0}]", m.Address); - } - - return Stay(); - } - if (removed != null && removed.Member.Address.Equals(_cluster.SelfAddress) && !_selfExited) - { - Log.Info("Self removed, stopping ClusterSingletonManager"); - return Stop(); - } - if (removed != null) - { - if (!_selfExited) - Log.Info("Member removed [{0}]", removed.Member.Address); - - AddRemoved(removed.Member.Address); - return Stay(); - } - if (e.FsmEvent is DelayedMemberRemoved) - { - var m = ((DelayedMemberRemoved)e.FsmEvent).Member; - if (!_selfExited) - Log.Info("Member removed [{0}]", m.Address); - - AddRemoved(m.Address); - return Stay(); - } - if (e.FsmEvent.Equals(ClusterSingletonMessage.TakeOverFromMe)) - { - Log.Info("Ignoring TakeOver request in [{0}] from [{1}].", StateName, Sender.Path.Address); - return Stay(); - } - if (e.FsmEvent.Equals(ClusterSingletonMessage.Cleanup)) - { - CleanupOverdueNotMemberAnyMore(); - return Stay(); - } - - return null; - }); - - OnTransition((from, to) => - { - Log.Info("ClusterSingletonManager state change [{0} -> {1}] {2}", from, to, StateData.ToString()); - - if (to == ClusterSingletonState.BecomingOldest) SetTimer(HandOverRetryTimer, new HandOverRetry(1), _settings.HandOverRetryInterval); - if (from == ClusterSingletonState.BecomingOldest) CancelTimer(HandOverRetryTimer); - if (from == ClusterSingletonState.WasOldest) CancelTimer(TakeOverRetryTimer); - if (to == ClusterSingletonState.Younger || to == ClusterSingletonState.Oldest) GetNextOldestChange(); - if (to == ClusterSingletonState.Younger || to == ClusterSingletonState.End) - { - if (_removed.ContainsKey(_cluster.SelfAddress)) - { - Log.Info("Self removed, stopping ClusterSingletonManager"); - Context.Stop(Self); - } - } - }); - - StartWith(ClusterSingletonState.Start, Uninitialized.Instance); - } - - private void ScheduleDelayedMemberRemoved(Member member) - { - if (_settings.RemovalMargin > TimeSpan.Zero) - { - Log.Debug("Schedule DelayedMemberRemoved for {0}", member.Address); - Context.System.Scheduler.ScheduleTellOnce(_settings.RemovalMargin, Self, new DelayedMemberRemoved(member), Self); - } - else Self.Tell(new DelayedMemberRemoved(member)); - } - } -} diff --git a/src/contrib/cluster/Akka.Cluster.Tools/Singleton/ClusterSingletonManagerSettings.cs b/src/contrib/cluster/Akka.Cluster.Tools/Singleton/ClusterSingletonManagerSettings.cs deleted file mode 100644 index a3f2cded07d..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools/Singleton/ClusterSingletonManagerSettings.cs +++ /dev/null @@ -1,113 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using Akka.Actor; -using Akka.Configuration; - -namespace Akka.Cluster.Tools.Singleton -{ - [Serializable] - public sealed class ClusterSingletonManagerSettings : INoSerializationVerificationNeeded - { - public static ClusterSingletonManagerSettings Create(ActorSystem system) - { - var config = system.Settings.Config.GetConfig("akka.cluster.singleton"); - if (config == null) - throw new ConfigurationException(string.Format("Cannot initialize {0}: akka.cluster.singleton configuration node was not provided", typeof(ClusterSingletonManagerSettings))); - - return Create(config).WithRemovalMargin(Cluster.Get(system).Settings.DownRemovalMargin); - } - - public static ClusterSingletonManagerSettings Create(Config config) - { - var role = config.GetString("role"); - if (role == string.Empty) role = null; - return new ClusterSingletonManagerSettings( - singletonName: config.GetString("singleton-name"), - role: role, - removalMargin: TimeSpan.MinValue, - handOverRetryInterval: config.GetTimeSpan("hand-over-retry-interval")); - } - - public readonly string SingletonName; - public readonly string Role; - public readonly TimeSpan RemovalMargin; - public readonly TimeSpan HandOverRetryInterval; - - /// - /// Creates a new instance of the . - /// - /// The actor name of the child singleton actor. - /// - /// Singleton among the nodes tagged with specified role. If the role is not specified - /// it's a singleton among all nodes in the cluster. - /// - /// - /// Margin until the singleton instance that belonged to a downed/removed partition is - /// created in surviving partition. The purpose of this margin is that in case of - /// a network partition the singleton actors in the non-surviving partitions must - /// be stopped before corresponding actors are started somewhere else. - /// This is especially important for persistent actors. - /// - /// - /// When a node is becoming oldest it sends hand-over - /// request to previous oldest, that might be leaving the cluster. This is - /// retried with this interval until the previous oldest confirms that the hand - /// over has started or the previous oldest member is removed from the cluster - /// (+ ). - /// - public ClusterSingletonManagerSettings(string singletonName, string role, TimeSpan removalMargin, TimeSpan handOverRetryInterval) - { - if (string.IsNullOrWhiteSpace(singletonName)) - throw new ArgumentNullException("singletonName"); - if (removalMargin == TimeSpan.Zero) - throw new ArgumentException("ClusterSingletonManagerSettings.RemovalMargin must be positive", "removalMargin"); - if (handOverRetryInterval == TimeSpan.Zero) - throw new ArgumentException("ClusterSingletonManagerSettings.HandOverRetryInterval must be positive", "handOverRetryInterval"); - - SingletonName = singletonName; - Role = role; - RemovalMargin = removalMargin; - HandOverRetryInterval = handOverRetryInterval; - } - - public ClusterSingletonManagerSettings WithSingletonName(string singletonName) - { - return Copy(singletonName: singletonName); - } - - public ClusterSingletonManagerSettings WithRole(string role) - { - return new ClusterSingletonManagerSettings( - singletonName: SingletonName, - role: role, - removalMargin: RemovalMargin, - handOverRetryInterval: HandOverRetryInterval); - } - - public ClusterSingletonManagerSettings WithRemovalMargin(TimeSpan removalMargin) - { - return Copy(removalMargin: removalMargin); - } - - public ClusterSingletonManagerSettings WithHandOverRetryInterval(TimeSpan handOverRetryInterval) - { - return Copy(handOverRetryInterval: handOverRetryInterval); - } - - private ClusterSingletonManagerSettings Copy(string singletonName = null, string role = null, TimeSpan? removalMargin = null, - TimeSpan? handOverRetryInterval = null) - { - return new ClusterSingletonManagerSettings( - singletonName: singletonName ?? SingletonName, - role: role ?? Role, - removalMargin: removalMargin ?? RemovalMargin, - handOverRetryInterval: handOverRetryInterval ?? HandOverRetryInterval); - } - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Tools/Singleton/ClusterSingletonProxy.cs b/src/contrib/cluster/Akka.Cluster.Tools/Singleton/ClusterSingletonProxy.cs deleted file mode 100644 index d42e7e72b34..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools/Singleton/ClusterSingletonProxy.cs +++ /dev/null @@ -1,241 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Linq; -using Akka.Actor; -using Akka.Configuration; -using Akka.Event; - -namespace Akka.Cluster.Tools.Singleton -{ - /// - /// - /// The works together with the to provide a - /// distributed proxy to the singleton actor. - /// - /// - /// The proxy can be started on every node where the singleton needs to be reached and used as if it were the singleton - /// itself. It will then act as a router to the currently running singleton instance. If the singleton is not currently - /// available, e.g., during hand off or startup, the proxy will buffer the messages sent to the singleton and then deliver - /// them when the singleton is finally available. The size of the buffer is configurable and it can be disabled by using - /// a buffer size of 0. When the buffer is full old messages will be dropped when new messages are sent via the proxy. - /// - /// - /// The proxy works by keeping track of the oldest cluster member. When a new oldest member is identified, e.g. because - /// the older one left the cluster, or at startup, the proxy will try to identify the singleton on the oldest member by - /// periodically sending an message until the singleton responds with its . - /// - /// - /// Note that this is a best effort implementation: messages can always be lost due to the distributed nature of the actors involved. - /// - /// - public sealed class ClusterSingletonProxy : UntypedActor - { - internal sealed class TryToIdentifySingleton - { - public static readonly TryToIdentifySingleton Instance = new TryToIdentifySingleton(); - private TryToIdentifySingleton() { } - } - /// - /// Returns default HOCON configuration for the cluster singleton. - /// - public static Config DefaultConfig() - { - return ConfigurationFactory.FromResource("Akka.Cluster.Tools.Singleton.reference.conf"); - } - - - /// - /// Faactory method for . - /// - /// - /// The logical path of the singleton manager, e.g. `/user/singletonManager`, - /// which ends with the name you defined in `actorOf` when creating the . - /// - /// Cluster singleton proxy settings. - public static Props Props(string singletonManagerPath, ClusterSingletonProxySettings settings) - { - return Actor.Props.Create(() => new ClusterSingletonProxy(singletonManagerPath, settings)).WithDeploy(Deploy.Local); - } - - private readonly ClusterSingletonProxySettings _settings; - private readonly Cluster _cluster = Cluster.Get(Context.System); - private readonly Queue> _buffer = new Queue>(); // queue seems to fit better - private readonly string[] _singletonPath; - private int _identityCounter = 0; - private string _identityId; - private IActorRef _singleton = null; - private ICancelable _identityTimer = null; - private ImmutableSortedSet _membersByAge = ImmutableSortedSet.Empty.WithComparer(MemberAgeOrdering.Descending); - private ILoggingAdapter _log; - - public ClusterSingletonProxy(string singletonManagerPath, ClusterSingletonProxySettings settings) - { - _settings = settings; - _singletonPath = (singletonManagerPath + "/" + settings.SingletonName).Split('/'); - _identityId = CreateIdentifyId(_identityCounter); - } - - private ILoggingAdapter Log { get { return _log ?? (_log = Context.GetLogger()); } } - - protected override void OnReceive(object message) - { - message.Match() - .With(HandleInitial) - .With(m => Add(m.Member)) - .With(m => Remove(m.Member)) - .With(m => Remove(m.Member)) - .With(identity => - { - if (identity.Subject != null) - { - // if the new singleton is defined, deliver all buffered messages - var subject = identity.Subject; - Log.Info("Singleton identified at [{0}]", subject.Path); - _singleton = subject; - Context.Watch(subject); - CancelTimer(); - SendBuffered(); - } - }) - .With(() => - { - var oldest = _membersByAge.FirstOrDefault(); - if (oldest != null && _identityTimer != null) - { - var singletonAddress = new RootActorPath(oldest.Address) / _singletonPath; - Log.Debug("Trying to identify singleton at [{0}]", singletonAddress); - Context.ActorSelection(singletonAddress).Tell(new Identify(_identityId)); - } - }) - .With(terminated => - { - if (Equals(_singleton, terminated.ActorRef)) - { - // buffering mode, identification of new will start when old node is removed - _singleton = null; - } - }) - .Default(msg => - { - if (_singleton != null) - { - if (Log.IsDebugEnabled) - Log.Debug("Forwarding message of type [{0}] to current singleton instance at [{1}]", msg.GetType(), _singleton.Path); - _singleton.Forward(msg); - } - else - Buffer(msg); - }); - } - - protected override void PreStart() - { - CancelTimer(); - _cluster.Subscribe(Self, new[] { typeof(ClusterEvent.IMemberEvent) }); - } - - protected override void PostStop() - { - CancelTimer(); - _cluster.Unsubscribe(Self); - } - - private void CancelTimer() - { - if (_identityTimer != null) - { - _identityTimer.Cancel(); - _identityTimer = null; - } - } - - private bool MatchingRole(Member member) - { - if (string.IsNullOrEmpty(_settings.Role)) return true; - - return member.HasRole(_settings.Role); - } - - private void IdentifySingleton() - { - Log.Debug("Creating singleton identification timer..."); - _identityCounter++; - _identityId = CreateIdentifyId(_identityCounter); - _singleton = null; - CancelTimer(); - _identityTimer = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable( - initialDelay: TimeSpan.FromMilliseconds(1), //TODO: this should be TimeSpan.Zero - interval: _settings.SingletonIdentificationInterval, - receiver: Self, - message: TryToIdentifySingleton.Instance, - sender: Self); - } - - private void TrackChanges(Action block) - { - var before = _membersByAge.FirstOrDefault(); - block(); - var after = _membersByAge.FirstOrDefault(); - - // if the head has changed, I need to find the new singleton - if (!Equals(before, after)) IdentifySingleton(); - } - - private void HandleInitial(ClusterEvent.CurrentClusterState state) - { - TrackChanges(() => _membersByAge = state.Members.Where(m => m.Status == MemberStatus.Up && MatchingRole(m)).ToImmutableSortedSet(MemberAgeOrdering.Descending)); - } - - private void Add(Member member) - { - if (MatchingRole(member)) - TrackChanges(() => _membersByAge = _membersByAge.Add(member)); - } - - private void Remove(Member member) - { - if (MatchingRole(member)) - TrackChanges(() => _membersByAge = _membersByAge.Remove(member)); - } - - private string CreateIdentifyId(int i) - { - return "identify-singleton-" + string.Join("/", _singletonPath) + i; - } - - private void Buffer(object message) - { - if (_settings.BufferSize == 0) - Log.Debug("Singleton not available and buffering is disabled, dropping message [{0}]", message.GetType()); - else if (_buffer.Count == _settings.BufferSize) - { - var first = _buffer.Dequeue(); - Log.Debug("Singleton not available, buffer is full, dropping first message [{0}]", first.Key.GetType()); - _buffer.Enqueue(new KeyValuePair(message, Sender)); - } - else - { - Log.Debug("Singleton not available, buffering message type [{0}]", message.GetType()); - _buffer.Enqueue(new KeyValuePair(message, Sender)); - } - } - - private void SendBuffered() - { - Log.Debug("Sending buffered messages to current singleton instance"); - while (_buffer.Count != 0) - { - var pair = _buffer.Dequeue(); - _singleton.Tell(pair.Key, pair.Value); - } - } - } -} diff --git a/src/contrib/cluster/Akka.Cluster.Tools/Singleton/ClusterSingletonProxySettings.cs b/src/contrib/cluster/Akka.Cluster.Tools/Singleton/ClusterSingletonProxySettings.cs deleted file mode 100644 index ec300bfe7b7..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools/Singleton/ClusterSingletonProxySettings.cs +++ /dev/null @@ -1,103 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using Akka.Actor; -using Akka.Configuration; - -namespace Akka.Cluster.Tools.Singleton -{ - public sealed class ClusterSingletonProxySettings - { - public static ClusterSingletonProxySettings Create(ActorSystem system) - { - var config = system.Settings.Config.GetConfig("akka.cluster.singleton-proxy"); - if (config == null) - throw new ConfigurationException(string.Format("Cannot create {0}: akka.cluster.singleton-proxy configuration node not found", typeof(ClusterSingletonProxySettings))); - - return Create(config); - } - - public static ClusterSingletonProxySettings Create(Config config) - { - var role = config.GetString("role"); - if (role == string.Empty) role = null; - - return new ClusterSingletonProxySettings( - singletonName: config.GetString("singleton-name"), - role: role, - singletonIdentificationInterval: config.GetTimeSpan("singleton-identification-interval"), - bufferSize: config.GetInt("buffer-size")); - } - - public readonly string SingletonName; - public readonly string Role; - public readonly TimeSpan SingletonIdentificationInterval; - public readonly int BufferSize; - - /// - /// Creates new instance of the . - /// - /// The actor name of the singleton actor that is started by the . - /// The role of the cluster nodes where the singleton can be deployed. If None, then any node will do. - /// Interval at which the proxy will try to resolve the singleton instance. - /// - /// If the location of the singleton is unknown the proxy will buffer this number of messages and deliver them - /// when the singleton is identified.When the buffer is full old messages will be droppedwhen new messages - /// are sent viea the proxy.Use 0 to disable buffering, i.e.messages will be dropped immediately if the location - /// of the singleton is unknown. - /// - public ClusterSingletonProxySettings(string singletonName, string role, TimeSpan singletonIdentificationInterval, int bufferSize) - { - if (string.IsNullOrEmpty(singletonName)) - throw new ArgumentNullException("singletonName"); - if (singletonIdentificationInterval == TimeSpan.Zero) - throw new ArgumentException("ClusterSingletonProxySettings.SingletonIdentificationInterval must be positive", "singletonIdentificationInterval"); - if (bufferSize <= 0) - throw new ArgumentException("ClusterSingletonProxySettings.BufferSize must be positive", "bufferSize"); - - SingletonName = singletonName; - Role = role; - SingletonIdentificationInterval = singletonIdentificationInterval; - BufferSize = bufferSize; - } - - public ClusterSingletonProxySettings WithSingletonName(string singletonName) - { - return Copy(singletonName: singletonName); - } - - public ClusterSingletonProxySettings WithRole(string role) - { - return new ClusterSingletonProxySettings( - singletonName: SingletonName, - role: role, - singletonIdentificationInterval: SingletonIdentificationInterval, - bufferSize: BufferSize); - } - - public ClusterSingletonProxySettings WithSingletonIdentificationInterval(string singletonIdentificationInterval) - { - return Copy(singletonIdentificationInterval: SingletonIdentificationInterval); - } - - public ClusterSingletonProxySettings WithBufferSize(int bufferSize) - { - return Copy(bufferSize: bufferSize); - } - - public ClusterSingletonProxySettings Copy(string singletonName = null, string role = null, - TimeSpan? singletonIdentificationInterval = null, int? bufferSize = null) - { - return new ClusterSingletonProxySettings( - singletonName: singletonName ?? SingletonName, - role: role ?? Role, - singletonIdentificationInterval: singletonIdentificationInterval ?? SingletonIdentificationInterval, - bufferSize: bufferSize ?? BufferSize); - } - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Tools/Singleton/MemberAgeOrdering.cs b/src/contrib/cluster/Akka.Cluster.Tools/Singleton/MemberAgeOrdering.cs deleted file mode 100644 index 9c12e04c069..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools/Singleton/MemberAgeOrdering.cs +++ /dev/null @@ -1,30 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System.Collections.Generic; - -namespace Akka.Cluster.Tools.Singleton -{ - internal sealed class MemberAgeOrdering : IComparer - { - private readonly bool _ascending; - private MemberAgeOrdering(bool ascending) - { - _ascending = ascending; - } - - public int Compare(Member x, Member y) - { - if (x.Equals(y)) return 0; - return x.IsOlderThan(y) - ? (_ascending ? 1 : -1) - : (_ascending ? -1 : 1); - } - public static readonly MemberAgeOrdering Ascending = new MemberAgeOrdering(true); - public static readonly MemberAgeOrdering Descending = new MemberAgeOrdering(false); - } -} diff --git a/src/contrib/cluster/Akka.Cluster.Tools/Singleton/OldestChangedBuffer.cs b/src/contrib/cluster/Akka.Cluster.Tools/Singleton/OldestChangedBuffer.cs deleted file mode 100644 index fa854484b75..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools/Singleton/OldestChangedBuffer.cs +++ /dev/null @@ -1,172 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using System.Collections.Immutable; -using System.Linq; -using Akka.Actor; - -namespace Akka.Cluster.Tools.Singleton -{ - /// - /// Notifications of member events that track oldest member is tunneled - /// via this actor (child of ClusterSingletonManager) to be able to deliver - /// one change at a time. Avoiding simultaneous changes simplifies - /// the process in ClusterSingletonManager. ClusterSingletonManager requests - /// next event with when it is ready for it. Only one outstanding - /// request is allowed. Incoming events are buffered and delivered - /// upon request. - /// - internal sealed class OldestChangedBuffer : UntypedActor - { - #region Internal messages - - [Serializable] - public sealed class GetNext - { - public static readonly GetNext Instance = new GetNext(); - private GetNext() { } - } - - [Serializable] - public sealed class InitialOldestState - { - public readonly Address Oldest; - public readonly bool SafeToBeOldest; - - public InitialOldestState(Address oldest, bool safeToBeOldest) - { - Oldest = oldest; - SafeToBeOldest = safeToBeOldest; - } - } - - [Serializable] - public sealed class OldestChanged - { - public readonly Address Oldest; - - public OldestChanged(Address oldest) - { - Oldest = oldest; - } - } - - #endregion - - public OldestChangedBuffer(string role) - { - _role = role; - } - - private string _role; - private ImmutableSortedSet _membersByAge = ImmutableSortedSet.Empty.WithComparer(MemberAgeOrdering.Descending); - private ImmutableQueue _changes = ImmutableQueue.Empty; - - private readonly Cluster _cluster = Cluster.Get(Context.System); - - private void TrackChanges(Action block) - { - var before = _membersByAge.FirstOrDefault(); - block(); - var after = _membersByAge.FirstOrDefault(); - - // todo: fix neq comparison - if (!Equals(before, after)) - _changes = _changes.Enqueue(new OldestChanged(MemberAddressOrDefault(after))); - } - - private bool MatchingRole(Member member) - { - return string.IsNullOrEmpty(_role) || member.HasRole(_role); - } - - private Address MemberAddressOrDefault(Member member) - { - return (member == null) ? null : member.Address; - } - - private void HandleInitial(ClusterEvent.CurrentClusterState state) - { - _membersByAge = state.Members - .Where(m => (m.Status == MemberStatus.Up || m.Status == MemberStatus.Leaving) && MatchingRole(m)) - .ToImmutableSortedSet(MemberAgeOrdering.Descending); - - var safeToBeOldest = !state.Members.Any(m => m.Status == MemberStatus.Down || m.Status == MemberStatus.Exiting); - var initial = new InitialOldestState(MemberAddressOrDefault(_membersByAge.FirstOrDefault()), safeToBeOldest); - _changes = _changes.Enqueue(initial); - } - - private void Add(Member member) - { - if (MatchingRole(member)) - TrackChanges(() => _membersByAge = _membersByAge.Add(member)); - } - - private void Remove(Member member) - { - if (MatchingRole(member)) - TrackChanges(() => _membersByAge = _membersByAge.Remove(member)); - } - - private void SendFirstChange() - { - object change; - _changes = _changes.Dequeue(out change); - Context.Parent.Tell(change); - } - - protected override void PreStart() - { - _cluster.Subscribe(Self, new[] { typeof(ClusterEvent.IMemberEvent) }); - } - - protected override void PostStop() - { - _cluster.Unsubscribe(Self); - } - - protected override void OnReceive(object message) - { - if (message is ClusterEvent.CurrentClusterState) HandleInitial((ClusterEvent.CurrentClusterState)message); - else if (message is ClusterEvent.MemberUp) Add(((ClusterEvent.MemberUp)message).Member); - else if (message is ClusterEvent.MemberExited || message is ClusterEvent.MemberRemoved) Remove(((ClusterEvent.IMemberEvent)(message)).Member); - else if (message is GetNext && _changes.IsEmpty) Context.BecomeStacked(OnDeliverNext); - else if (message is GetNext) SendFirstChange(); - } - - private void OnDeliverNext(object message) - { - if (message is ClusterEvent.CurrentClusterState) - { - HandleInitial((ClusterEvent.CurrentClusterState)message); - SendFirstChange(); - Context.UnbecomeStacked(); - } - else if (message is ClusterEvent.MemberUp) - { - var memberUp = (ClusterEvent.MemberUp)message; - Add(memberUp.Member); - if (!_changes.IsEmpty) - { - SendFirstChange(); - Context.UnbecomeStacked(); - } - } - else if (message is ClusterEvent.MemberExited || message is ClusterEvent.MemberRemoved) - { - var memberEvent = (ClusterEvent.IMemberEvent)message; - Remove(memberEvent.Member); - if (!_changes.IsEmpty) - { - SendFirstChange(); - Context.UnbecomeStacked(); - } - } - } - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Tools/Singleton/Serialization/ClusterSingletonMessageSerializer.cs b/src/contrib/cluster/Akka.Cluster.Tools/Singleton/Serialization/ClusterSingletonMessageSerializer.cs deleted file mode 100644 index 7bb9b957473..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools/Singleton/Serialization/ClusterSingletonMessageSerializer.cs +++ /dev/null @@ -1,82 +0,0 @@ -//----------------------------------------------------------------------- -// -// Copyright (C) 2009-2015 Typesafe Inc. -// Copyright (C) 2013-2015 Akka.NET project -// -//----------------------------------------------------------------------- - -using System; -using System.Collections.Generic; -using Akka.Actor; -using Akka.Serialization; - -namespace Akka.Cluster.Tools.Singleton.Serialization -{ - public class ClusterSingletonMessageSerializer : SerializerWithStringManifest - { - private const string HandOverToMeManifest = "A"; - private const string HandOverInProgressManifest = "B"; - private const string HandOverDoneManifest = "C"; - private const string TakeOverFromMeManifest = "D"; - - private static readonly byte[] EmptyBytes = new byte[0]; - private static readonly IDictionary FromBinaryMap = new Dictionary - { - {HandOverToMeManifest, ClusterSingletonMessage.HandOverToMe}, - {HandOverInProgressManifest, ClusterSingletonMessage.HandOverInProgress}, - {HandOverDoneManifest, ClusterSingletonMessage.HandOverDone}, - {TakeOverFromMeManifest, ClusterSingletonMessage.TakeOverFromMe} - }; - - private readonly int _identifier; - - public ClusterSingletonMessageSerializer(ExtendedActorSystem system) : base(system) - { - _identifier = SerializerIdentifierHelper.GetSerializerIdentifierFromConfig(this.GetType(), system); - } - - public override int Identifier { get { return _identifier; } } - public override byte[] ToBinary(object o) - { - if (o is ClusterSingletonMessage) - { - switch ((ClusterSingletonMessage)o) - { - case ClusterSingletonMessage.HandOverToMe: - case ClusterSingletonMessage.HandOverInProgress: - case ClusterSingletonMessage.HandOverDone: - case ClusterSingletonMessage.TakeOverFromMe: - return EmptyBytes; - default: throw new ArgumentException(string.Format("Cannot serialize object of type [{0}] in [{1}]", o.GetType(), GetType())); - } - } - else throw new ArgumentException(string.Format("Cannot serialize object of type [{0}] in [{1}]", o.GetType(), GetType())); - } - - public override object FromBinary(byte[] binary, string manifest) - { - ClusterSingletonMessage mapping; - if (FromBinaryMap.TryGetValue(manifest, out mapping)) - { - return mapping; - } - else throw new ArgumentException(string.Format("Unimplemented deserialization of message with manifest [{0}] in [{1}]", manifest, GetType())); - } - - public override string Manifest(object o) - { - if (o is ClusterSingletonMessage) - { - switch ((ClusterSingletonMessage)o) - { - case ClusterSingletonMessage.HandOverToMe: return HandOverToMeManifest; - case ClusterSingletonMessage.HandOverInProgress: return HandOverInProgressManifest; - case ClusterSingletonMessage.HandOverDone: return HandOverDoneManifest; - case ClusterSingletonMessage.TakeOverFromMe: return TakeOverFromMeManifest; - default: throw new ArgumentException(string.Format("Cannot serialize object of type [{0}] in [{1}]", o.GetType(), GetType())); - } - } - else throw new ArgumentException(string.Format("Cannot serialize object of type [{0}] in [{1}]", o.GetType(), GetType())); - } - } -} \ No newline at end of file diff --git a/src/contrib/cluster/Akka.Cluster.Tools/Singleton/reference.conf b/src/contrib/cluster/Akka.Cluster.Tools/Singleton/reference.conf deleted file mode 100644 index 706d923d5ec..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools/Singleton/reference.conf +++ /dev/null @@ -1,64 +0,0 @@ -############################################ -# Akka Cluster Tools Reference Config File # -############################################ - -# This is the reference config file that contains all the default settings. -# Make your edits/overrides in your application.conf. - -# //#singleton-config -akka.cluster.singleton { - # The actor name of the child singleton actor. - singleton-name = "singleton" - - # Singleton among the nodes tagged with specified role. - # If the role is not specified it's a singleton among all nodes in the cluster. - role = "" - - # When a node is becoming oldest it sends hand-over request to previous oldest, - # that might be leaving the cluster. This is retried with this interval until - # the previous oldest confirms that the hand over has started or the previous - # oldest member is removed from the cluster (+ akka.cluster.down-removal-margin). - hand-over-retry-interval = 1s - - # The number of retries are derived from hand-over-retry-interval and - # akka.cluster.down-removal-margin (or ClusterSingletonManagerSettings.removalMargin), - # but it will never be less than this property. - min-number-of-hand-over-retries = 10 -} -# //#singleton-config - -# //#singleton-proxy-config -akka.cluster.singleton-proxy { - # The actor name of the singleton actor that is started by the ClusterSingletonManager - singleton-name = ${akka.cluster.singleton.singleton-name} - - # The role of the cluster nodes where the singleton can be deployed. - # If the role is not specified then any node will do. - role = "" - - # Interval at which the proxy will try to resolve the singleton instance. - singleton-identification-interval = 1s - - # If the location of the singleton is unknown the proxy will buffer this - # number of messages and deliver them when the singleton is identified. - # When the buffer is full old messages will be dropped when new messages are - # sent via the proxy. - # Use 0 to disable buffering, i.e. messages will be dropped immediately if - # the location of the singleton is unknown. - # Maximum allowed buffer size is 10000. - buffer-size = 1000 -} -# //#singleton-proxy-config - -# Serializer for cluster ClusterSingleton messages -akka.actor { - serializers { - akka-singleton = "Akka.Cluster.Tools.Singleton.Serialization.ClusterSingletonMessageSerializer, Akka.Cluster.Tools" - } - serialization-bindings { - "Akka.Cluster.Tools.Singleton.ClusterSingletonMessage, Akka.Cluster.Tools" = akka-singleton - } - serialization-identifiers { - "Akka.Cluster.Tools.Singleton.Serialization.ClusterSingletonMessageSerializer, Akka.Cluster.Tools" = 14 - } -} diff --git a/src/contrib/cluster/Akka.Cluster.Tools/packages.config b/src/contrib/cluster/Akka.Cluster.Tools/packages.config deleted file mode 100644 index 4ae7e7e980b..00000000000 --- a/src/contrib/cluster/Akka.Cluster.Tools/packages.config +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/core/Akka.Cluster/Akka.Cluster.csproj b/src/core/Akka.Cluster/Akka.Cluster.csproj index 61ca820d828..f368cd524ce 100644 --- a/src/core/Akka.Cluster/Akka.Cluster.csproj +++ b/src/core/Akka.Cluster/Akka.Cluster.csproj @@ -113,6 +113,7 @@ + diff --git a/src/core/Akka.Cluster/ClusterSettings.cs b/src/core/Akka.Cluster/ClusterSettings.cs index 4b6e837d7c5..2b6f4458542 100644 --- a/src/core/Akka.Cluster/ClusterSettings.cs +++ b/src/core/Akka.Cluster/ClusterSettings.cs @@ -45,7 +45,6 @@ public sealed class ClusterSettings readonly TimeSpan _metricsMovingAverageHalfLife; readonly int _minNrOfMembers; readonly ImmutableDictionary _minNrOfMembersOfRole; - readonly TimeSpan _downRemovalMargin; public ClusterSettings(Config config, string systemName) { @@ -67,7 +66,6 @@ public ClusterSettings(Config config, string systemName) _leaderActionsInterval = cc.GetTimeSpan("leader-actions-interval"); _unreachableNodesReaperInterval = cc.GetTimeSpan("unreachable-nodes-reaper-interval"); _publishStatsInterval = cc.GetTimeSpanWithOffSwitch("publish-stats-interval"); - _downRemovalMargin = cc.GetTimeSpan("down-removal-margin"); _autoDownUnreachableAfter = cc.GetTimeSpanWithOffSwitch("auto-down-unreachable-after"); @@ -236,11 +234,6 @@ public ImmutableDictionary MinNrOfMembersOfRole { get { return _minNrOfMembersOfRole; } } - - public TimeSpan DownRemovalMargin - { - get { return _downRemovalMargin; } - } } } diff --git a/src/core/Akka.Cluster/Configuration/Cluster.conf b/src/core/Akka.Cluster/Configuration/Cluster.conf index 78c051c5f10..f2a42ac6629 100644 --- a/src/core/Akka.Cluster/Configuration/Cluster.conf +++ b/src/core/Akka.Cluster/Configuration/Cluster.conf @@ -28,13 +28,7 @@ akka { # formed in case of network partition. # Disable with "off" or specify a duration to enable auto-down. auto-down-unreachable-after = off - - # Margin until shards or singletons that belonged to a downed/removed - # partition are created in surviving partition. The purpose of this margin is that - # in case of a network partition the persistent actors in the non-surviving partitions - # must be stopped before corresponding persistent actors are started somewhere else. - down-removal-margin = 20s - + # The roles of this member. List of strings, e.g. roles = ["A", "B"]. # The roles are part of the membership information and can be used by # routers or other services to distribute work to certain member types, diff --git a/src/core/Akka.FSharp/Properties/AssemblyInfo.fs b/src/core/Akka.FSharp/Properties/AssemblyInfo.fs index ede3203756a..45ed219319b 100644 --- a/src/core/Akka.FSharp/Properties/AssemblyInfo.fs +++ b/src/core/Akka.FSharp/Properties/AssemblyInfo.fs @@ -10,9 +10,9 @@ open System.Runtime.InteropServices [] [] [] -[] -[] +[] +[] do () module internal AssemblyVersionInformation = - let [] Version = "1.0.6.0" + let [] Version = "1.0.5.0" diff --git a/src/core/Akka/Routing/ConsistentHash.cs b/src/core/Akka/Routing/ConsistentHash.cs index e1eacd11954..5b9971d57a6 100644 --- a/src/core/Akka/Routing/ConsistentHash.cs +++ b/src/core/Akka/Routing/ConsistentHash.cs @@ -29,7 +29,7 @@ public class ConsistentHash private readonly SortedDictionary _nodes; private readonly int _virtualNodesFactor; - public ConsistentHash(SortedDictionary nodes, int virtualNodesFactor) + internal ConsistentHash(SortedDictionary nodes, int virtualNodesFactor) { _nodes = nodes; diff --git a/src/core/Akka/Serialization/Serializer.cs b/src/core/Akka/Serialization/Serializer.cs index 1bcc47e6785..23580d0faae 100644 --- a/src/core/Akka/Serialization/Serializer.cs +++ b/src/core/Akka/Serialization/Serializer.cs @@ -6,7 +6,6 @@ //----------------------------------------------------------------------- using System; -using System.Linq; using Akka.Actor; namespace Akka.Serialization @@ -83,56 +82,5 @@ public byte[] ToBinaryWithAddress(Address address, object obj) /// The object contained in the array public abstract object FromBinary(byte[] bytes, Type type); } - - public abstract class SerializerWithStringManifest : Serializer - { - protected SerializerWithStringManifest(ExtendedActorSystem system) : base(system) - { - } - - public sealed override bool IncludeManifest { get { return true; } } - - public sealed override object FromBinary(byte[] bytes, Type type) - { - var manifest = type == null ? string.Empty : type.FullName; - return FromBinary(bytes, manifest); - } - - /// - /// Produces an object from an array of bytes, with an optional type-hint. - /// - public abstract object FromBinary(byte[] binary, string manifest); - - /// - /// Return the manifest (type hint) that will be provided in the fromBinary method. - /// Return if not needed. - /// - public abstract string Manifest(object o); - } - - /// - /// INTERNAL API. - /// - public static class SerializerIdentifierHelper - { - public const string SerializationIdentifiers = "akka.actor.serialization-identifiers"; - - public static int GetSerializerIdentifierFromConfig(Type type, ExtendedActorSystem system) - { - var config = system.Settings.Config.GetConfig(SerializationIdentifiers); - var identifiers = config.AsEnumerable() - .ToDictionary(pair => Type.GetType(pair.Key, true), pair => pair.Value.GetInt()); - - int value; - if (identifiers.TryGetValue(type, out value)) - { - return value; - } - else - { - throw new ArgumentException(string.Format("Couldn't find serializer id for [{0}] under [{1}] HOCON path", type, SerializationIdentifiers)); - } - } - } } diff --git a/src/examples/Cluster/ClusterSharding/ClusterSharding.Node/App.config b/src/examples/Cluster/ClusterSharding/ClusterSharding.Node/App.config deleted file mode 100644 index 1cec105421e..00000000000 --- a/src/examples/Cluster/ClusterSharding/ClusterSharding.Node/App.config +++ /dev/null @@ -1,61 +0,0 @@ - - - -
- - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/examples/Cluster/ClusterSharding/ClusterSharding.Node/AutomaticJoin/AutomaticCluster.cs b/src/examples/Cluster/ClusterSharding/ClusterSharding.Node/AutomaticJoin/AutomaticCluster.cs deleted file mode 100644 index 4b4b87c4f42..00000000000 --- a/src/examples/Cluster/ClusterSharding/ClusterSharding.Node/AutomaticJoin/AutomaticCluster.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System.Collections.Immutable; -using System.Data.SQLite; -using System.Linq; -using Akka.Actor; -using Akka.Cluster; -using Akka.Persistence.Sqlite; - -namespace ClusterSharding.Node.AutomaticJoin -{ - /// - /// Extension for Akka.NET cluster to establish cluster automatically through shared sqlite store. - /// - public class AutomaticCluster - { - private readonly ActorSystem _system; - private readonly Cluster _cluster; - private readonly SqlitePersistence _persistence; - private readonly DbHelper _dbHelper; - - public AutomaticCluster(ActorSystem system) - { - _system = system; - _cluster = Cluster.Get(system); - _persistence = SqlitePersistence.Get(system); - _dbHelper = new DbHelper(() => - { - var conn = new SQLiteConnection(_persistence.JournalSettings.ConnectionString); - conn.Open(); - return conn; - }); - } - - public void Join() - { - _dbHelper.InitializeNodesTable(); - - var members = _dbHelper.GetClusterMembers().ToImmutableList(); - if (members.Any()) - { - _cluster.JoinSeedNodes(members); - _dbHelper.AddClusterMember(_cluster.SelfAddress); - } - else - { - var self = _cluster.SelfAddress; - _dbHelper.AddClusterMember(self); - _cluster.JoinSeedNodes(ImmutableList.Create(self)); - } - } - - public void Leave() - { - _dbHelper.RemoveClusterMember(_cluster.SelfAddress); - } - } -} \ No newline at end of file diff --git a/src/examples/Cluster/ClusterSharding/ClusterSharding.Node/AutomaticJoin/DBHelper.cs b/src/examples/Cluster/ClusterSharding/ClusterSharding.Node/AutomaticJoin/DBHelper.cs deleted file mode 100644 index c74d45443a2..00000000000 --- a/src/examples/Cluster/ClusterSharding/ClusterSharding.Node/AutomaticJoin/DBHelper.cs +++ /dev/null @@ -1,78 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SQLite; -using Akka.Actor; - -namespace ClusterSharding.Node.AutomaticJoin -{ - public class DbHelper - { - private readonly Func _connectionFactory; - - public DbHelper(Func connectionFactory) - { - _connectionFactory = connectionFactory; - } - - public void InitializeNodesTable() - { - using (var cmd = new SQLiteCommand(_connectionFactory())) - { - cmd.CommandText = @"CREATE TABLE IF NOT EXISTS cluster_nodes ( - member_address VARCHAR(255) NOT NULL PRIMARY KEY - );"; - - cmd.ExecuteNonQuery(); - } - } - - public IEnumerable
GetClusterMembers() - { - using (var cmd = new SQLiteCommand(@"SELECT member_address from cluster_nodes", _connectionFactory())) - { - using (var reader = cmd.ExecuteReader()) - { - var result = new List
(); - while (reader.Read()) - { - var addr = reader.GetString(0); - result.Add(Address.Parse(addr)); - } - return result; - } - } - } - - public void AddClusterMember(Address address) - { - using (var cmd = new SQLiteCommand(@"INSERT INTO cluster_nodes(member_address) VALUES (@addr)", _connectionFactory())) - using (var tx = cmd.Connection.BeginTransaction()) - { - cmd.Transaction = tx; - var addr = address.ToString(); - cmd.Parameters.Add("@addr", DbType.String); - cmd.Parameters["@addr"].Value = addr; - - cmd.ExecuteNonQuery(); - tx.Commit(); - } - } - - public void RemoveClusterMember(Address address) - { - using (var cmd = new SQLiteCommand(@"DELETE FROM cluster_nodes WHERE member_address = @addr", _connectionFactory())) - using (var tx = cmd.Connection.BeginTransaction()) - { - cmd.Transaction = tx; - var addr = address.ToString(); - cmd.Parameters.Add("@addr", DbType.String); - cmd.Parameters["@addr"].Value = addr; - - cmd.ExecuteNonQuery(); - tx.Commit(); - } - } - } -} \ No newline at end of file diff --git a/src/examples/Cluster/ClusterSharding/ClusterSharding.Node/ClusterSharding.Node.csproj b/src/examples/Cluster/ClusterSharding/ClusterSharding.Node/ClusterSharding.Node.csproj deleted file mode 100644 index 21caa5aa6e7..00000000000 --- a/src/examples/Cluster/ClusterSharding/ClusterSharding.Node/ClusterSharding.Node.csproj +++ /dev/null @@ -1,343 +0,0 @@ - - - - - Debug - AnyCPU - {30A0B17D-B913-49AB-8CBB-8DF383AB7A52} - Exe - Properties - ClusterSharding.Node - ClusterSharding.Node - v4.5 - 512 - - - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\..\..\..\packages\Google.ProtocolBuffers.2.4.1.555\lib\net40\Google.ProtocolBuffers.dll - True - - - ..\..\..\..\packages\Google.ProtocolBuffers.2.4.1.555\lib\net40\Google.ProtocolBuffers.Serialization.dll - True - - - ..\..\..\..\packages\Helios.1.4.1\lib\net45\Helios.dll - True - - - ..\..\..\..\packages\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll - True - - - - ..\..\..\..\packages\System.Collections.Immutable.1.1.37\lib\dotnet\System.Collections.Immutable.dll - True - - - - ..\..\..\..\packages\System.Data.SQLite.Core.1.0.98.1\lib\net45\System.Data.SQLite.dll - True - - - - - - - - - ..\..\..\..\packages\Wire.0.0.6\lib\Wire.dll - True - - - - - - - - - - - - Designer - - - - - - {a05c31e8-0246-46a1-b3bc-4d6fe7a9aa49} - Akka.Cluster.Sharding - - - {5CF8A8BE-B634-473F-BB01-EBA878746BD4} - Akka.Cluster.Tools - - - {3b9e6211-9488-4db5-b714-24248693b38f} - Akka.Persistence.Sql.Common - - - {453efd22-7c53-4887-9dbf-fcfc9172e909} - Akka.Persistence.Sqlite - - - {b47ca568-40cf-48de-b87e-31bd400ebb08} - Akka.Serialization.Wire - - - {6ab00f61-269a-4501-b06a-026707f000a7} - Akka.Cluster - - - {fca84dea-c118-424b-9eb8-34375dfef18a} - Akka.Persistence - - - {ea4ff8fd-7c53-49c8-b9aa-02e458b3e6a7} - Akka.Remote - - - {5deddf90-37f0-48d3-a0b0-a5cbd8a7e377} - Akka - - - - - - - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\net35\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\net35\Google.ProtocolBuffers.dll - True - True - - - - - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\net20\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\net20\Google.ProtocolBuffers.dll - True - True - - - - - - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\sl30\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\sl30\Google.ProtocolBuffers.dll - True - True - - - - - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\sl40\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\sl40\Google.ProtocolBuffers.dll - True - True - - - - - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\portable-net40+sl4+sl5+wp7+wp8+win8\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\portable-net40+sl4+sl5+wp7+wp8+win8\Google.ProtocolBuffers.dll - True - True - - - - - - - - - ..\..\..\..\..\packages\Helios\lib\net40\Helios.NET40.dll - True - True - - - - - - - - - - ..\..\..\..\..\packages\Newtonsoft.Json\lib\net35\Newtonsoft.Json.dll - True - True - - - - - - - ..\..\..\..\..\packages\Newtonsoft.Json\lib\net20\Newtonsoft.Json.dll - True - True - - - - - - - ..\..\..\..\..\packages\Newtonsoft.Json\lib\net40\Newtonsoft.Json.dll - True - True - - - - - - - - ..\..\..\..\..\packages\Newtonsoft.Json\lib\portable-net45+wp80+win8+wpa81+dnxcore50\Newtonsoft.Json.dll - True - True - - - - - - - ..\..\..\..\..\packages\Newtonsoft.Json\lib\portable-net40+sl5+wp80+win8+wpa81\Newtonsoft.Json.dll - True - True - - - - - - - - - - - <__paket__System_Data_SQLite_Core_targets>net45\System.Data.SQLite.Core - - - - - <__paket__System_Data_SQLite_Core_targets>net46\System.Data.SQLite.Core - - - - - <__paket__System_Data_SQLite_Core_targets>net20\System.Data.SQLite.Core - - - - - <__paket__System_Data_SQLite_Core_targets>net40\System.Data.SQLite.Core - - - - - <__paket__System_Data_SQLite_Core_targets>net451\System.Data.SQLite.Core - - - - - - - - - ..\..\..\..\..\packages\System.Data.SQLite.Core\lib\net46\System.Data.SQLite.dll - True - True - - - - - - - ..\..\..\..\..\packages\System.Data.SQLite.Core\lib\net20\System.Data.SQLite.dll - True - True - - - - - - - ..\..\..\..\..\packages\System.Data.SQLite.Core\lib\net40\System.Data.SQLite.dll - True - True - - - - - - - ..\..\..\..\..\packages\System.Data.SQLite.Core\lib\net451\System.Data.SQLite.dll - True - True - - - - - - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - - \ No newline at end of file diff --git a/src/examples/Cluster/ClusterSharding/ClusterSharding.Node/Printer.cs b/src/examples/Cluster/ClusterSharding/ClusterSharding.Node/Printer.cs deleted file mode 100644 index 63b0ba62a51..00000000000 --- a/src/examples/Cluster/ClusterSharding/ClusterSharding.Node/Printer.cs +++ /dev/null @@ -1,59 +0,0 @@ -using System; -using Akka.Actor; -using Akka.Cluster.Sharding; - -namespace ClusterSharding.Node -{ - public class Printer : ReceiveActor - { - #region Message extractor - - public sealed class MessageExtractor : IMessageExtractor - { - public string EntityId(object message) - { - var env = message as Env; - return env != null ? env.EntityId.ToString() : null; - } - - public object EntityMessage(object message) - { - var env = message as Env; - return env != null ? env.Message : null; - } - - public string ShardId(object message) - { - var env = message as Env; - return env != null ? env.ShardId.ToString() : null; - } - } - - #endregion - - #region Messages - - public sealed class Env - { - public readonly int ShardId; - public readonly int EntityId; - public readonly string Message; - - public Env(int shardId, int entityId, string message) - { - ShardId = shardId; - EntityId = entityId; - Message = message; - } - } - - #endregion - - public Printer() - { - Context.SetReceiveTimeout(TimeSpan.FromMinutes(2)); - Receive(message => Console.WriteLine("{0} received message '{1}'", Self, message)); - } - - } -} \ No newline at end of file diff --git a/src/examples/Cluster/ClusterSharding/ClusterSharding.Node/Program.cs b/src/examples/Cluster/ClusterSharding/ClusterSharding.Node/Program.cs deleted file mode 100644 index bb0c8edfc7e..00000000000 --- a/src/examples/Cluster/ClusterSharding/ClusterSharding.Node/Program.cs +++ /dev/null @@ -1,71 +0,0 @@ -using System; -using System.Linq; -using System.Threading; -using Akka.Actor; -using Akka.Cluster.Sharding; -using Akka.Cluster.Tools.Singleton; -using Akka.Configuration; -using ClusterSharding.Node.AutomaticJoin; - -namespace ClusterSharding.Node -{ - using ClusterSharding = Akka.Cluster.Sharding.ClusterSharding; - - class Program - { - static void Main(string[] args) - { - using (var system = ActorSystem.Create("sharded-cluster-system", ConfigurationFactory.Load().WithFallback(ClusterSingletonManager.DefaultConfig()))) - { - var automaticCluster = new AutomaticCluster(system); - try - { - automaticCluster.Join(); - - RunExample(system); - - Console.ReadLine(); - } - finally - { - // you may need to remove SQLite database file from bin/Debug or bin/Release in case when unexpected crash happened - automaticCluster.Leave(); - } - } - } - - private static void RunExample(ActorSystem system) - { - var sharding = ClusterSharding.Get(system); - var shardRegion = sharding.Start( - typeName: "printer", - entityProps: Props.Create(), - settings: ClusterShardingSettings.Create(system), - messageExtractor: new Printer.MessageExtractor()); - - Thread.Sleep(5000); - Console.Write("Press ENTER to start..."); - Console.ReadLine(); - - ProduceMessages(system, shardRegion); - } - - private static void ProduceMessages(ActorSystem system, IActorRef shardRegion) - { - const int entitiesCount = 20; - const int shardsCount = 10; - var rand = new Random(); - - system.Scheduler.Advanced.ScheduleRepeatedly(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5), () => - { - for (int i = 0; i < 2; i++) - { - var shardId = rand.Next(shardsCount); - var entityId = rand.Next(entitiesCount); - - shardRegion.Tell(new Printer.Env(shardId, entityId, "hello world")); - } - }); - } - } -} diff --git a/src/examples/Cluster/ClusterSharding/ClusterSharding.Node/Properties/AssemblyInfo.cs b/src/examples/Cluster/ClusterSharding/ClusterSharding.Node/Properties/AssemblyInfo.cs deleted file mode 100644 index 6353e6f1ad0..00000000000 --- a/src/examples/Cluster/ClusterSharding/ClusterSharding.Node/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("ClusterSharding.Node")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("ClusterSharding.Node")] -[assembly: AssemblyCopyright("Copyright © 2015")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("30a0b17d-b913-49ab-8cbb-8df383ab7a52")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/examples/Cluster/ClusterSharding/ClusterSharding.Node/packages.config b/src/examples/Cluster/ClusterSharding/ClusterSharding.Node/packages.config deleted file mode 100644 index 3fc2555c509..00000000000 --- a/src/examples/Cluster/ClusterSharding/ClusterSharding.Node/packages.config +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Node/App.config b/src/examples/Cluster/ClusterTools/ClusterToolsExample.Node/App.config deleted file mode 100644 index 517167f418e..00000000000 --- a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Node/App.config +++ /dev/null @@ -1,49 +0,0 @@ - - - -
- - - - - - - - - - \ No newline at end of file diff --git a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Node/ClusterToolsExample.Node.csproj b/src/examples/Cluster/ClusterTools/ClusterToolsExample.Node/ClusterToolsExample.Node.csproj deleted file mode 100644 index 34e78ff6916..00000000000 --- a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Node/ClusterToolsExample.Node.csproj +++ /dev/null @@ -1,242 +0,0 @@ - - - - - Debug - AnyCPU - {337A85B5-4A7C-4883-8634-46E7E52A765F} - Exe - Properties - ClusterToolsExample.Node - ClusterToolsExample.Node - v4.5 - 512 - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\..\..\..\packages\Google.ProtocolBuffers.2.4.1.555\lib\net40\Google.ProtocolBuffers.dll - True - - - ..\..\..\..\packages\Google.ProtocolBuffers.2.4.1.555\lib\net40\Google.ProtocolBuffers.Serialization.dll - True - - - ..\..\..\..\packages\Helios.1.4.1\lib\net45\Helios.dll - True - - - ..\..\..\..\packages\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll - True - - - - ..\..\..\..\packages\System.Collections.Immutable.1.1.37\lib\dotnet\System.Collections.Immutable.dll - True - - - - - - - - - - ..\..\..\..\packages\Wire.0.0.6\lib\Wire.dll - True - - - - - - - - - - - - - {5cf8a8be-b634-473f-bb01-eba878746bd4} - Akka.Cluster.Tools - - - {6ab00f61-269a-4501-b06a-026707f000a7} - Akka.Cluster - - - {ea4ff8fd-7c53-49c8-b9aa-02e458b3e6a7} - Akka.Remote - - - {5deddf90-37f0-48d3-a0b0-a5cbd8a7e377} - Akka - - - {88d7d845-2f50-4d37-9026-b0a8353d0e8d} - ClusterToolsExample.Shared - - - - - - - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\net35\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\net35\Google.ProtocolBuffers.dll - True - True - - - - - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\net20\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\net20\Google.ProtocolBuffers.dll - True - True - - - - - - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\sl30\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\sl30\Google.ProtocolBuffers.dll - True - True - - - - - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\sl40\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\sl40\Google.ProtocolBuffers.dll - True - True - - - - - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\portable-net40+sl4+sl5+wp7+wp8+win8\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\portable-net40+sl4+sl5+wp7+wp8+win8\Google.ProtocolBuffers.dll - True - True - - - - - - - - - ..\..\..\..\..\packages\Helios\lib\net40\Helios.NET40.dll - True - True - - - - - - - - - - ..\..\..\..\..\packages\Newtonsoft.Json\lib\net35\Newtonsoft.Json.dll - True - True - - - - - - - ..\..\..\..\..\packages\Newtonsoft.Json\lib\net20\Newtonsoft.Json.dll - True - True - - - - - - - ..\..\..\..\..\packages\Newtonsoft.Json\lib\net40\Newtonsoft.Json.dll - True - True - - - - - - - - ..\..\..\..\..\packages\Newtonsoft.Json\lib\portable-net45+wp80+win8+wpa81+dnxcore50\Newtonsoft.Json.dll - True - True - - - - - - - ..\..\..\..\..\packages\Newtonsoft.Json\lib\portable-net40+sl5+wp80+win8+wpa81\Newtonsoft.Json.dll - True - True - - - - - - - - \ No newline at end of file diff --git a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Node/Program.cs b/src/examples/Cluster/ClusterTools/ClusterToolsExample.Node/Program.cs deleted file mode 100644 index 5276e28829c..00000000000 --- a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Node/Program.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System; -using Akka.Actor; -using Akka.Cluster.Tools.Client; -using Akka.Cluster.Tools.Singleton; -using ClusterToolsExample.Shared; - -namespace ClusterToolsExample.Node -{ - class Program - { - static void Main(string[] args) - { - Console.Title = "Attached node"; - using (var system = ActorSystem.Create("singleton-cluster-system")) - { - //RunClusterSingletonClient(system); - RunDistributedPubSubClient(system); - //RunClusterClient(system); - - Console.ReadLine(); - } - } - - /// - /// Creates a proxy to communicate with cluster singleton initialized by the seed. - /// - static void RunClusterSingletonClient(ActorSystem system) - { - var proxyRef = system.ActorOf(ClusterSingletonProxy.Props( - singletonManagerPath: "/user/manager", - settings: ClusterSingletonProxySettings.Create(system).WithRole("worker")), - name: "managerProxy"); - } - - /// - /// Creates an actor which subscribes to the distributed pub/sub topic. - /// This topic is filled with messages from the cluster seed job. - /// - static void RunDistributedPubSubClient(ActorSystem system) - { - var echo = system.ActorOf(Props.Create(() => new EchoReceiver())); - echo.Tell(new object()); - } - - /// - /// Creates a cluster client, that allows to connect to cluster even thou current actor system is not part of it. - /// - static void RunClusterClient(ActorSystem system) - { - //NOTE: to properly run cluster client set up actor ref provider for nodes on `provider = "Akka.Remote.RemoteActorRefProvider, Akka.Remote"` - system.Settings.InjectTopLevelFallback(ClusterClientReceptionist.DefaultConfig()); - var clusterClient = system.ActorOf(ClusterClient.Props(ClusterClientSettings.Create(system))); - clusterClient.Tell(new ClusterClient.Send("/user/my-service", new Echo("hello from cluster client"))); - } - } -} diff --git a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Node/Properties/AssemblyInfo.cs b/src/examples/Cluster/ClusterTools/ClusterToolsExample.Node/Properties/AssemblyInfo.cs deleted file mode 100644 index 6aa6d925bbe..00000000000 --- a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Node/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("ClusterToolsExample.Node")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("ClusterToolsExample.Node")] -[assembly: AssemblyCopyright("Copyright © 2015")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("337a85b5-4a7c-4883-8634-46e7e52a765f")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Node/packages.config b/src/examples/Cluster/ClusterTools/ClusterToolsExample.Node/packages.config deleted file mode 100644 index 092ab5f1865..00000000000 --- a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Node/packages.config +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Seed/App.config b/src/examples/Cluster/ClusterTools/ClusterToolsExample.Seed/App.config deleted file mode 100644 index dc9fd58202b..00000000000 --- a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Seed/App.config +++ /dev/null @@ -1,43 +0,0 @@ - - - -
- - - - - - - - - - \ No newline at end of file diff --git a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Seed/ClusterToolsExample.Seed.csproj b/src/examples/Cluster/ClusterTools/ClusterToolsExample.Seed/ClusterToolsExample.Seed.csproj deleted file mode 100644 index 611936e0054..00000000000 --- a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Seed/ClusterToolsExample.Seed.csproj +++ /dev/null @@ -1,242 +0,0 @@ - - - - - Debug - AnyCPU - {ED00E6F4-2B5C-4F16-ADE4-45E4A73C17B8} - Exe - Properties - ClusterToolsExample.Seed - ClusterToolsExample.Seed - v4.5 - 512 - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\..\..\..\packages\Google.ProtocolBuffers.2.4.1.555\lib\net40\Google.ProtocolBuffers.dll - True - - - ..\..\..\..\packages\Google.ProtocolBuffers.2.4.1.555\lib\net40\Google.ProtocolBuffers.Serialization.dll - True - - - ..\..\..\..\packages\Helios.1.4.1\lib\net45\Helios.dll - True - - - ..\..\..\..\packages\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll - True - - - - ..\..\..\..\packages\System.Collections.Immutable.1.1.37\lib\dotnet\System.Collections.Immutable.dll - True - - - - - - - - - - ..\..\..\..\packages\Wire.0.0.6\lib\Wire.dll - True - - - - - - - - - - - - - {5cf8a8be-b634-473f-bb01-eba878746bd4} - Akka.Cluster.Tools - - - {6ab00f61-269a-4501-b06a-026707f000a7} - Akka.Cluster - - - {ea4ff8fd-7c53-49c8-b9aa-02e458b3e6a7} - Akka.Remote - - - {5deddf90-37f0-48d3-a0b0-a5cbd8a7e377} - Akka - - - {88d7d845-2f50-4d37-9026-b0a8353d0e8d} - ClusterToolsExample.Shared - - - - - - - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\net35\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\net35\Google.ProtocolBuffers.dll - True - True - - - - - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\net20\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\net20\Google.ProtocolBuffers.dll - True - True - - - - - - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\sl30\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\sl30\Google.ProtocolBuffers.dll - True - True - - - - - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\sl40\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\sl40\Google.ProtocolBuffers.dll - True - True - - - - - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\portable-net40+sl4+sl5+wp7+wp8+win8\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\portable-net40+sl4+sl5+wp7+wp8+win8\Google.ProtocolBuffers.dll - True - True - - - - - - - - - ..\..\..\..\..\packages\Helios\lib\net40\Helios.NET40.dll - True - True - - - - - - - - - - ..\..\..\..\..\packages\Newtonsoft.Json\lib\net35\Newtonsoft.Json.dll - True - True - - - - - - - ..\..\..\..\..\packages\Newtonsoft.Json\lib\net20\Newtonsoft.Json.dll - True - True - - - - - - - ..\..\..\..\..\packages\Newtonsoft.Json\lib\net40\Newtonsoft.Json.dll - True - True - - - - - - - - ..\..\..\..\..\packages\Newtonsoft.Json\lib\portable-net45+wp80+win8+wpa81+dnxcore50\Newtonsoft.Json.dll - True - True - - - - - - - ..\..\..\..\..\packages\Newtonsoft.Json\lib\portable-net40+sl5+wp80+win8+wpa81\Newtonsoft.Json.dll - True - True - - - - - - - - \ No newline at end of file diff --git a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Seed/Program.cs b/src/examples/Cluster/ClusterTools/ClusterToolsExample.Seed/Program.cs deleted file mode 100644 index b3aa43b2994..00000000000 --- a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Seed/Program.cs +++ /dev/null @@ -1,59 +0,0 @@ -using System; -using Akka.Actor; -using Akka.Cluster.Tools.Client; -using Akka.Cluster.Tools.PublishSubscribe; -using Akka.Cluster.Tools.Singleton; -using ClusterToolsExample.Shared; - -namespace ClusterToolsExample.Seed -{ - class Program - { - static void Main(string[] args) - { - Console.Title = "Seed node"; - using (var system = ActorSystem.Create("singleton-cluster-system")) - { - //RunClusterSingletonSeed(system); - RunDistributedPubSubSeed(system); - //RunClusterClientSeed(system); - - Console.ReadLine(); - } - } - - /// - /// Initializes cluster singleton of the actor. - /// - /// - static void RunClusterSingletonSeed(ActorSystem system) - { - var aref = system.ActorOf(ClusterSingletonManager.Props( - singletonProps: Props.Create(() => new WorkerManager()), - terminationMessage: PoisonPill.Instance, - settings: ClusterSingletonManagerSettings.Create(system)), - name: "manager"); - } - - /// - /// Starts a job, which publishes message to distributed cluster pub sub in 5 sec periods. - /// - static void RunDistributedPubSubSeed(ActorSystem system) - { - var mediator = DistributedPubSub.Get(system).Mediator; - - system.Scheduler.ScheduleTellRepeatedly(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5), mediator, - new Distributed.Publish("echo", new Echo("hello world")), ActorRefs.NoSender); - } - - /// - /// Starts a job, which establishes cluster client receptionist for target actor, - /// making it visible from outside of the cluster. - /// - static void RunClusterClientSeed(ActorSystem system) - { - var receptionist = ClusterClientReceptionist.Get(system); - receptionist.RegisterService(system.ActorOf(Props.Create(), "my-service")); - } - } -} diff --git a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Seed/Properties/AssemblyInfo.cs b/src/examples/Cluster/ClusterTools/ClusterToolsExample.Seed/Properties/AssemblyInfo.cs deleted file mode 100644 index 31a74ff3380..00000000000 --- a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Seed/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("ClusterToolsExample.Seed")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("ClusterToolsExample.Seed")] -[assembly: AssemblyCopyright("Copyright © 2015")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("ed00e6f4-2b5c-4f16-ade4-45e4a73c17b8")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Seed/packages.config b/src/examples/Cluster/ClusterTools/ClusterToolsExample.Seed/packages.config deleted file mode 100644 index 092ab5f1865..00000000000 --- a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Seed/packages.config +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Shared/ClusterToolsExample.Shared.csproj b/src/examples/Cluster/ClusterTools/ClusterToolsExample.Shared/ClusterToolsExample.Shared.csproj deleted file mode 100644 index ccfae8efe43..00000000000 --- a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Shared/ClusterToolsExample.Shared.csproj +++ /dev/null @@ -1,239 +0,0 @@ - - - - - Debug - AnyCPU - {88D7D845-2F50-4D37-9026-B0A8353D0E8D} - Library - Properties - ClusterToolsExample.Shared - ClusterToolsExample.Shared - v4.5 - 512 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\..\..\..\packages\Google.ProtocolBuffers.2.4.1.555\lib\net40\Google.ProtocolBuffers.dll - True - - - ..\..\..\..\packages\Google.ProtocolBuffers.2.4.1.555\lib\net40\Google.ProtocolBuffers.Serialization.dll - True - - - ..\..\..\..\packages\Helios.1.4.1\lib\net45\Helios.dll - True - - - ..\..\..\..\packages\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll - True - - - - ..\..\..\..\packages\System.Collections.Immutable.1.1.37\lib\dotnet\System.Collections.Immutable.dll - True - - - - - - - - - - ..\..\..\..\packages\Wire.0.0.6\lib\Wire.dll - True - - - - - - - - - - - - - - - - {5cf8a8be-b634-473f-bb01-eba878746bd4} - Akka.Cluster.Tools - - - {6ab00f61-269a-4501-b06a-026707f000a7} - Akka.Cluster - - - {ea4ff8fd-7c53-49c8-b9aa-02e458b3e6a7} - Akka.Remote - - - {5deddf90-37f0-48d3-a0b0-a5cbd8a7e377} - Akka - - - - - - - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\net35\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\net35\Google.ProtocolBuffers.dll - True - True - - - - - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\net20\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\net20\Google.ProtocolBuffers.dll - True - True - - - - - - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\sl30\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\sl30\Google.ProtocolBuffers.dll - True - True - - - - - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\sl40\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\sl40\Google.ProtocolBuffers.dll - True - True - - - - - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\portable-net40+sl4+sl5+wp7+wp8+win8\Google.ProtocolBuffers.Serialization.dll - True - True - - - ..\..\..\..\..\packages\Google.ProtocolBuffers\lib\portable-net40+sl4+sl5+wp7+wp8+win8\Google.ProtocolBuffers.dll - True - True - - - - - - - - - ..\..\..\..\..\packages\Helios\lib\net40\Helios.NET40.dll - True - True - - - - - - - - - - ..\..\..\..\..\packages\Newtonsoft.Json\lib\net35\Newtonsoft.Json.dll - True - True - - - - - - - ..\..\..\..\..\packages\Newtonsoft.Json\lib\net20\Newtonsoft.Json.dll - True - True - - - - - - - ..\..\..\..\..\packages\Newtonsoft.Json\lib\net40\Newtonsoft.Json.dll - True - True - - - - - - - - ..\..\..\..\..\packages\Newtonsoft.Json\lib\portable-net45+wp80+win8+wpa81+dnxcore50\Newtonsoft.Json.dll - True - True - - - - - - - ..\..\..\..\..\packages\Newtonsoft.Json\lib\portable-net40+sl5+wp80+win8+wpa81\Newtonsoft.Json.dll - True - True - - - - - - - - \ No newline at end of file diff --git a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Shared/Echo.cs b/src/examples/Cluster/ClusterTools/ClusterToolsExample.Shared/Echo.cs deleted file mode 100644 index d081fd2209b..00000000000 --- a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Shared/Echo.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; -using Akka.Actor; -using Akka.Cluster; -using Akka.Cluster.Tools.PublishSubscribe; - -namespace ClusterToolsExample.Shared -{ - public sealed class Echo - { - public readonly string Message; - - public Echo(string message) - { - Message = message; - } - } - - public class EchoReceiver : ReceiveActor - { - public const string Topic = "echo"; - - public readonly Cluster Cluster = Cluster.Get(Context.System); - public readonly IActorRef Mediator = DistributedPubSub.Get(Context.System).Mediator; - - public EchoReceiver() - { - Receive(echo => Console.WriteLine(echo.Message)); - Receive(ack => - Console.WriteLine("Actor [{0}] has subscribed to topic [{1}]", ack.Subscribe.Ref, ack.Subscribe.Topic)); - } - - protected override void PreStart() - { - base.PreStart(); - Mediator.Tell(new Distributed.Subscribe(Topic, Self)); - } - - protected override void PostStop() - { - Mediator.Tell(new Distributed.Unsubscribe(Topic, Self)); - base.PostStop(); - } - } -} \ No newline at end of file diff --git a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Shared/Messages.cs b/src/examples/Cluster/ClusterTools/ClusterToolsExample.Shared/Messages.cs deleted file mode 100644 index e7dc3c1361b..00000000000 --- a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Shared/Messages.cs +++ /dev/null @@ -1,60 +0,0 @@ -using System; -using System.Collections.Generic; -using Akka.Actor; - -namespace ClusterToolsExample.Shared -{ - [Serializable] - public sealed class Batch - { - public readonly int Size; - - public Batch(int size) - { - Size = size; - } - } - - [Serializable] - public sealed class Work - { - public readonly int Id; - - public Work(int id) - { - Id = id; - } - } - - [Serializable] - public sealed class Result - { - public readonly int Id; - - public Result(int id) - { - Id = id; - } - } - - [Serializable] - public sealed class SendReport - { - public static readonly SendReport Instance = new SendReport(); - - private SendReport() - { - } - } - - [Serializable] - public sealed class Report - { - public readonly IDictionary Counts; - - public Report(IDictionary counts) - { - Counts = counts; - } - } -} \ No newline at end of file diff --git a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Shared/Properties/AssemblyInfo.cs b/src/examples/Cluster/ClusterTools/ClusterToolsExample.Shared/Properties/AssemblyInfo.cs deleted file mode 100644 index 8eade652224..00000000000 --- a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Shared/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("ClusterToolsExample.Shared")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("ClusterToolsExample.Shared")] -[assembly: AssemblyCopyright("Copyright © 2015")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("88d7d845-2f50-4d37-9026-b0a8353d0e8d")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Shared/WorkLoadCounter.cs b/src/examples/Cluster/ClusterTools/ClusterToolsExample.Shared/WorkLoadCounter.cs deleted file mode 100644 index 8272942c51d..00000000000 --- a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Shared/WorkLoadCounter.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System.Collections.Generic; -using Akka.Actor; -using Akka.Event; - -namespace ClusterToolsExample.Shared -{ - public class WorkLoadCounter : ReceiveActor - { - public WorkLoadCounter() - { - var log = Context.GetLogger(); - var counts = new Dictionary(); - - Receive(_ => - { - int count; - if (counts.TryGetValue(Sender, out count)) - counts[Sender] = (++count); - else - counts.Add(Sender, 1); - }); - - Receive(_ => Sender.Tell(new Report(counts))); - } - } -} \ No newline at end of file diff --git a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Shared/Worker.cs b/src/examples/Cluster/ClusterTools/ClusterToolsExample.Shared/Worker.cs deleted file mode 100644 index 9fe7e2454e3..00000000000 --- a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Shared/Worker.cs +++ /dev/null @@ -1,21 +0,0 @@ -using Akka.Actor; -using Akka.Event; - -namespace ClusterToolsExample.Shared -{ - public class Worker : ReceiveActor - { - public Worker(IActorRef counter) - { - var log = Context.GetLogger(); - - Receive(work => - { - var result = new Result(work.Id); - log.Info("Worker {0} - result: {1}", Self.Path.Name, result.Id); - Sender.Tell(result); - counter.Tell(result); - }); - } - } -} \ No newline at end of file diff --git a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Shared/WorkerManager.cs b/src/examples/Cluster/ClusterTools/ClusterToolsExample.Shared/WorkerManager.cs deleted file mode 100644 index 516bfc797ae..00000000000 --- a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Shared/WorkerManager.cs +++ /dev/null @@ -1,60 +0,0 @@ -using System; -using Akka.Actor; -using Akka.Cluster.Routing; -using Akka.Event; -using Akka.Routing; - -namespace ClusterToolsExample.Shared -{ - public class WorkerManager : ReceiveActor - { - private readonly Random random = new Random(); - public WorkerManager() - { - var log = Context.GetLogger(); - var counter = Context.ActorOf(name: "workload-counter"); - var workerRouter = GetWorkerRouter(counter); - - Receive(batch => - { - log.Info("Generating a batch of size {0}", batch.Size); - for (int i = 0; i < batch.Size; i++) - workerRouter.Tell(new Work(i)); - - Context.System.Scheduler.ScheduleTellOnce(TimeSpan.FromSeconds(10), Self, GetBatch(), Self); - }); - - Receive(report => - { - foreach (var entry in report.Counts) - { - var key = entry.Key; - var value = entry.Value; - var name = (string.IsNullOrEmpty(key.Path.Address.Host) ? "local/" : key.Path.Address.Host + ":" + key.Path.Address.Port + "/") + key.Path.Name; - - log.Info("{0} -> {1}", name, value); - } - }); - - Context.System.Scheduler.ScheduleTellOnce(TimeSpan.FromSeconds(3), Self, GetBatch(), Self); - Context.System.Scheduler.ScheduleTellRepeatedly(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(10), counter, SendReport.Instance, Self); - } - - private IActorRef GetWorkerRouter(IActorRef counter) - { - return Context.ActorOf(new ClusterRouterPool( - local: new RoundRobinPool(10), - settings: new ClusterRouterPoolSettings( - totalInstances: 30, - allowLocalRoutees: true, - useRole: null, - maxInstancesPerNode: 10)) - .Props(Props.Create(() => new Worker(counter)))); - } - - private Batch GetBatch() - { - return new Batch(random.Next(5) + 5); - } - } -} diff --git a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Shared/packages.config b/src/examples/Cluster/ClusterTools/ClusterToolsExample.Shared/packages.config deleted file mode 100644 index 092ab5f1865..00000000000 --- a/src/examples/Cluster/ClusterTools/ClusterToolsExample.Shared/packages.config +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file