public static void ConfigureAkka(IServiceCollection services)
        {
            services.AddSingleton(sp =>
            {
                var metrics = sp.GetRequiredService <IMetricsRoot>();
                var tracer  = sp.GetRequiredService <ITracer>();

                var config = ConfigurationFactory.ParseString(File.ReadAllText("app.conf")).BootstrapFromDocker();

                var phobosSetup = PhobosSetup.Create(new PhobosConfigBuilder()
                                                     .WithMetrics(m =>
                                                                  m.SetMetricsRoot(metrics)) // binds Phobos to same IMetricsRoot as ASP.NET Core
                                                     .WithTracing(t => t.SetTracer(tracer))) // binds Phobos to same tracer as ASP.NET Core
                                  .WithSetup(BootstrapSetup.Create()
                                             .WithConfig(config)                             // passes in the HOCON for Akka.NET to the ActorSystem
                                             .WithActorRefProvider(PhobosProviderSelection
                                                                   .Cluster));               // last line activates Phobos inside Akka.NET

                var sys = ActorSystem.Create("ClusterSys", phobosSetup);

                // create actor "container" and bind it to DI, so it can be used by ASP.NET Core
                return(new AkkaActors(sys));
            });

            // this will manage Akka.NET lifecycle
            services.AddHostedService <AkkaService>();
        }
        public Task StartAsync(CancellationToken cancellationToken)
        {
            var config    = HoconLoader.ParseConfig("web.hocon");
            var bootstrap = BootstrapSetup.Create()
                            .WithConfig(config.ApplyOpsConfig())                       // load HOCON and apply extension methods to inject environment variables
                            .WithActorRefProvider(ProviderSelection.Cluster.Instance); // launch Akka.Cluster

            // N.B. `WithActorRefProvider` isn't actually needed here - the HOCON file already specifies Akka.Cluster

            // enable DI support inside this ActorSystem, if needed
            var diSetup = ServiceProviderSetup.Create(_serviceProvider);

            // merge this setup (and any others) together into ActorSystemSetup
            var actorSystemSetup = bootstrap.And(diSetup);

            // start ActorSystem
            _clusterSystem = ActorSystem.Create("webcrawler", actorSystemSetup);

            _clusterSystem.StartPbm(); // start Petabridge.Cmd (https://cmd.petabridge.com/)

            // instantiate actors
            var router    = _clusterSystem.ActorOf(Props.Empty.WithRouter(FromConfig.Instance), "tasker");
            var processor = _clusterSystem.ActorOf(
                Props.Create(() => new CommandProcessor(router)),
                "commands");
            var signalRProps = ServiceProvider.For(_clusterSystem).Props <SignalRActor>(processor);

            _signalRActor = _clusterSystem.ActorOf(signalRProps, "signalr");

            return(Task.CompletedTask);
        }
Exemple #3
0
        static async Task Main(string[] args)
        {
            var config = ConfigurationFactory.ParseString(@"
akka {  
    actor {
        provider = remote
    }
    remote {
        dot-netty.tcp {
            port = 8081
            hostname = 0.0.0.0
            public-hostname = localhost
        }
    }
}
");

            var setup = BootstrapSetup.Create().WithConfig(config);

            using var system = ActorSystem.Create("MyServer", setup);
            system.ActorOf(Props.Create(() => new ChatServerActor()), "ChatServer");

            Console.ReadLine();

            await system.Terminate();
        }
        public void SerializationSettingsShouldOverrideHoconSettings()
        {
            var serializationSettings = new SerializationSetup(_ =>
                                                               ImmutableHashSet <SerializerDetails> .Empty
                                                               .Add(SerializerDetails.Create(
                                                                        "test",
                                                                        new TestSerializer(_),
                                                                        ImmutableHashSet <Type> .Empty.Add(typeof(ProgammaticDummy)))));

            var bootstrap = BootstrapSetup.Create().WithConfig(ConfigurationFactory.ParseString(@"
                akka{
                    actor{
                        serialize-messages = on
                        serializers {
                            test = ""Akka.Tests.Serialization.OverridenSerializer, Akka.Test""
                        }
                        serialization-bindings {
                            ""Akka.Tests.Serialization.ProgammaticDummy, Akka.Tests"" = test
                        }
                    }
                }").WithFallback(TestConfigs.DefaultConfig));

            var actorSystemSettings = ActorSystemSetup.Create(serializationSettings, bootstrap);

            var sys2       = ActorSystem.Create("override-test", actorSystemSettings);
            var serializer = sys2.Serialization.FindSerializerFor(new ProgammaticDummy());

            serializer.Should().BeOfType <TestSerializer>();

            sys2.Terminate().Wait();
        }
        public Task StartAsync(CancellationToken cancellationToken)
        {
            var config    = HoconLoader.ParseConfig("tracker.hocon");
            var bootstrap = BootstrapSetup.Create()
                            .WithConfig(config.ApplyOpsConfig())                       // load HOCON and apply extension methods to inject environment variables
                            .WithActorRefProvider(ProviderSelection.Cluster.Instance); // launch Akka.Cluster

            // N.B. `WithActorRefProvider` isn't actually needed here - the HOCON file already specifies Akka.Cluster

            // enable DI support inside this ActorSystem, if needed
            var diSetup = ServiceProviderSetup.Create(_serviceProvider);

            // merge this setup (and any others) together into ActorSystemSetup
            var actorSystemSetup = bootstrap.And(diSetup);

            // start ActorSystem
            ClusterSystem = ActorSystem.Create("webcrawler", actorSystemSetup);

            ClusterSystem.StartPbm(); // start Petabridge.Cmd (https://cmd.petabridge.com/)

            // instantiate actors
            _apiMaster      = ClusterSystem.ActorOf(Props.Create(() => new ApiMaster()), "api");
            _downloadMaster = ClusterSystem.ActorOf(Props.Create(() => new DownloadsMaster()), "downloads");

            return(Task.CompletedTask);
        }
        static async Task Main(string[] args)
        {
            var config = ConfigurationFactory.ParseString(@"
akka {  
    actor {
        provider = remote
    }
    remote {
        dot-netty.tcp {
		    port = 0
		    hostname = localhost
        }
    }
}
");
            var setup  = BootstrapSetup.Create().WithConfig(config);

            using var system = ActorSystem.Create("MyClient", setup);
            var chatClient = system.ActorOf(Props.Create <ChatClientActor>());

            chatClient.Tell(new ConnectRequest()
            {
                Username = "******",
            });

            while (true)
            {
                var input = Console.ReadLine();
                if (input != null && input.StartsWith("/"))
                {
                    var parts = input.Split(' ');
                    var cmd   = parts[0].ToLowerInvariant();
                    var rest  = string.Join(" ", parts.Skip(1));

                    if (cmd == "/nick")
                    {
                        chatClient.Tell(new NickRequest
                        {
                            NewUsername = rest
                        });
                    }
                    if (cmd == "/exit")
                    {
                        Console.WriteLine("exiting");
                        break;
                    }
                }
                else
                {
                    chatClient.Tell(new SayRequest()
                    {
                        Text = input,
                    });
                }
            }

            await system.Terminate();
        }
Exemple #7
0
        static void Main(string[] args)
        {
            // setup declaring our custom serializer to override the default typeof(object) newtonsoft registration
            var serializationSetup = SerializationSetup.Create(system =>
                                                               ImmutableHashSet <SerializerDetails> .Empty.Add(
                                                                   SerializerDetails.Create("json-custom", new CustomSerializer(system),
                                                                                            ImmutableHashSet <Type> .Empty
                                                                                            // this should make all my messages use CustomSerializer
                                                                                            .Add(typeof(object))
                                                                                            // this is provided to show CustomSerializer gets called,
                                                                                            // i.e, everything appears to be configured correctly
                                                                                            .Add(typeof(World))
                                                                                            )
                                                                   )
                                                               );

            // we just want to force serialization so we don't need to set up remote
            // the goal of the programmatic setup is so apps don't need to register the serializer
            var hocon = ConfigurationFactory.ParseString(@"
akka {
    ""loglevel"": ""DEBUG"",
    ""stdout-loglevel"": ""DEBUG"",
    actor {
        ""serialize-messages"": ""on"",
        ""debug"": {
            ""receive"": ""on"",
            ""lifecycle"": ""on"",
            ""unhandled"": ""on"",
            ""event-stream"": ""on""
        }
    }
}
");
            // I'm not sure why 'serialize-messages' isn't triggering my serializer, not even for
            // my 'World' type. Inspecting system.Serialization._serializerMap reveals the following:
            // [object] = NewtonsoftJsonSerializer
            // [World]  = CustomSerializer
            // [byte[]] = ByteArraySerializer
            // * I thought it might have been dependent on the ordering of ActorSystemSetup.Create(params Setup[] setups)
            //   but I observe the same behavior regardless of the setup ordering.
            var bootstrapSetup = BootstrapSetup.Create().WithConfig(hocon);
            var systemSetup    = ActorSystemSetup.Create(serializationSetup, bootstrapSetup);
            var system         = ActorSystem.Create("system", systemSetup);

            // uncommenting this line and the custom serializer is invoked
            // really bizarre since there is a mapping for typeof(World) but w/out this next line it's not invoked on that type either.
            //system.Serialization.AddSerializationMap(typeof(object), new CustomSerializer(system.Serialization.System));

            var actor    = system.ActorOf(Props.Create(() => new Actor()), "actor");
            var response = actor.Ask <World>(new Hello("world!")).GetAwaiter().GetResult();

            system.Log.Info($"Response: {response.Message}");

            Thread.Sleep(TimeSpan.FromSeconds(20));

            system.Dispose();
        }
        public void ProviderSelectionMustCreateActorSystemWithCustomProviderSelection()
        {
            var other = ProviderSelection.ClusterActorRefProvider;
            var ps    = new ProviderSelection.Custom(other, "test");

            using (var actorSystem = ActorSystem.Create("Test1", BootstrapSetup.Create().WithActorRefProvider(ps)))
            {
                actorSystem.Settings.ProviderClass.Should().Be(ps.Fqn);
            }
        }
        private static ActorSystemSetup CreateBootstrapSetup(DatabaseFixture fixture)
        {
            var connectionString = new MongoUrl(fixture.ConnectionString);
            var client           = new MongoClient(connectionString);
            var databaseName     = connectionString.DatabaseName;
            var settings         = client.Settings;

            return(BootstrapSetup.Create()
                   .WithConfig(CreateSpecConfig())
                   .And(new MongoDbPersistenceSetup(databaseName, settings, null, null)));
        }
Exemple #10
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            var hocon            = ConfigurationLoader.Load();
            var bootstrap        = BootstrapSetup.Create().WithConfig(hocon);
            var di               = ServiceProviderSetup.Create(_serviceProvider);
            var actorSystemSetup = bootstrap.And(di);

            _actorSystem = ActorSystem.Create("shop", actorSystemSetup);

            ClientActor = _actorSystem.ActorOf(Props.Create <ClientActor>());
        }
Exemple #11
0
        public async Task RunAsync()
        {
            var config               = ConfigurationFactory.ParseString(@"
                    akka.actor.default-dispatcher = {
                        executor = channel-executor
                        fork-join-executor { #channelexecutor will re-use these settings
                        parallelism-min = 2
                        parallelism-factor = 1
                        parallelism-max = 64
                        }
                    }

                    akka.actor.internal-dispatcher = {
                        executor = channel-executor
                        throughput = 5
                        fork-join-executor {
                        parallelism-min = 4
                        parallelism-factor = 1.0
                        parallelism-max = 64
                        }
                    }

                    akka.remote.default-remote-dispatcher {
                        type = Dispatcher
                        executor = channel-executor
                        fork-join-executor {
                        parallelism-min = 2
                        parallelism-factor = 0.5
                        parallelism-max = 16
                        }
                    }

                    akka.remote.backoff-remote-dispatcher {
                    executor = channel-executor
                    fork-join-executor {
                        parallelism-min = 2
                        parallelism-max = 2
                    }
                    }
                ");
            var bootstrap            = BootstrapSetup.Create().WithConfig(config);
            var serviceProviderSetup = ServiceProviderSetup.Create(_serviceProvider);
            var actorSystemSetup     = bootstrap.And(serviceProviderSetup);

            _actorSystem = ActorSystem.Create("StatsSys", actorSystemSetup);
            var marketingCoordinator =
                _actorSystem.ActorOf(Props.Create(() => new MarketingCoordinator()), "marketing");
            var actors = new[] { marketingCoordinator };

            // start the work coordinator
            _workCoordinator = _actorSystem.ActorOf(Props.Create(() => new WorkCoordinator(actors)), "work");

            await _actorSystem.WhenTerminated.ConfigureAwait(false);
        }
Exemple #12
0
        private static void Main(string[] args)
        {
            var Bootstrap = BootstrapSetup.Create().WithConfig(ConfigurationFactory.ParseString(@"
akka
{
    actor
    {
        serialize-messages = off
    }
}"));

            var ActorSystemSettings = ActorSystemSetup.Create(SerializationSettings, Bootstrap);
        }
 internal static IServiceCollection AddAkka(this IServiceCollection services,
                                            string actorSystemName,
                                            string hocon,
                                            Func <Config, Config> hoconFunc,
                                            Action <IServiceProvider, ActorSystem> startAction = null) =>
 services.AddSingleton(sp =>
                       BootstrapSetup.Create()
                       .WithConfig(hoconFunc(ConfigurationFactory.ParseString(hocon)))
                       .And(ServiceProviderSetup.Create(sp)))
 .AddSingleton <AkkaHostedServiceStart>(sp => sys => startAction?.Invoke(sp, sys))
 .AddSingleton(typeof(IPropsFactory <>), typeof(PropsFactory <>))
 .AddHostedService <AkkaHostedService>()
 .AddSingleton(sp => ActorSystem.Create(actorSystemName, sp.GetService <ActorSystemSetup>()));
Exemple #14
0
        private static ActorSystem Startup(string port)
        {
            var config = ConfigurationFactory.ParseString($"akka.remote.dot-netty.tcp.port = {port}")
                         .WithFallback(ConfigurationFactory.ParseString(File.ReadAllText("application.conf")));

            var setup = BootstrapSetup.Create()
                        .WithConfig(config)
                        .WithActorRefProvider(ProviderSelection.Cluster.Instance);

            var system = ActorSystem.Create("ClusterSystem", setup);

            system.ActorOf(ClusterListener.Props(), "ClusterListener");
            return(system);
        }
Exemple #15
0
        static async Task Main(string[] args)
        {
            var config = ConfigurationFactory.ParseString(@"
akka.persistence.snapshot-store {
    plugin = ""akka.persistence.snapshot-store.azure-blob-store""
    azure-blob-store {
        container-name = snapshot-greg
        connection-string = not_used
    }
}")
                         .WithFallback(AzurePersistence.DefaultConfig);

            var bootstrap = BootstrapSetup.Create()
                            .WithConfig(config)
                            .And(AzureBlobSnapshotSetup.Create(
                                     new Uri($"https://{YourAccountName}.blob.core.windows.net"),
                                     new DefaultAzureCredential()));

            var actorSystem = ActorSystem.Create("AzureTest", bootstrap);
            var actor       = actorSystem.ActorOf(Props.Create <TestActor>());

            // let everything synched up
            await Task.Delay(1000);

            var response = await actor.Ask <StateResponse>(GetState.Instance);

            switch (response.State)
            {
            case "three":
                Console.WriteLine($"Actor recovered with state: [{response.State}]");
                break;

            case "undefined":
                actor.Tell(new SetState("one"));
                actor.Tell(new SetState("two"));
                actor.Tell(new SetState("three"));
                actor.Tell(Snap.Instance);

                response = await actor.Ask <StateResponse>(GetState.Instance);

                Console.WriteLine($"Last actor state: [{response.State}]");
                break;

            case var unknown:
                Console.WriteLine($"Unknown actor state [{unknown}]");
                break;
            }

            await actorSystem.Terminate();
        }
        public Task StartAsync(CancellationToken cancellationToken)
        {
            var config    = ConfigurationFactory.ParseString(File.ReadAllText("app.conf")).BootstrapFromDocker();
            var bootstrap = BootstrapSetup.Create()
                            .WithConfig(config)                                        // load HOCON
                            .WithActorRefProvider(ProviderSelection.Cluster.Instance); // launch Akka.Cluster

            // N.B. `WithActorRefProvider` isn't actually needed here - the HOCON file already specifies Akka.Cluster

            // enable DI support inside this ActorSystem, if needed
            var diSetup = ServiceProviderSetup.Create(_serviceProvider);

            // merge this setup (and any others) together into ActorSystemSetup
            var actorSystemSetup = bootstrap.And(diSetup);

            ThreadPool.GetMinThreads(out var workerThreads, out var completionThreads);
            Console.WriteLine("Min threads: {0}, Min I/O threads: {1}", workerThreads, completionThreads);
            ThreadPool.SetMinThreads(0, 0);

            // start ActorSystem
            _clusterSystem = ActorSystem.Create("ClusterSys", actorSystemSetup);

            DebugConfigurator("akka.actor.default-dispatcher", _clusterSystem);
            DebugConfigurator("akka.actor.internal-dispatcher", _clusterSystem);
            DebugConfigurator("akka.remote.default-remote-dispatcher", _clusterSystem);
            DebugConfigurator("akka.remote.backoff-remote-dispatcher", _clusterSystem);

            // instantiate actors
            BenchmarkHostRouter = _clusterSystem.ActorOf(Props.Empty.WithRouter(FromConfig.Instance), "host-router");

            BenchmarkCoordinatorManager = _clusterSystem.ActorOf(ClusterSingletonManager.Props(
                                                                     singletonProps: Props.Create(() => new BenchmarkCoordinator(2, 6, BenchmarkHostRouter)),
                                                                     terminationMessage: PoisonPill.Instance,
                                                                     settings: ClusterSingletonManagerSettings.Create(_clusterSystem)), "coordinator");

            BenchmarkCoordinator = _clusterSystem.ActorOf(ClusterSingletonProxy.Props(
                                                              singletonManagerPath: "/user/coordinator",
                                                              settings: ClusterSingletonProxySettings.Create(_clusterSystem)), "coordinator-proxy");

            BenchmarkHost = _clusterSystem.ActorOf(Props.Create(() => new BenchmarkHost(BenchmarkCoordinator)), "host");

            Akka.Cluster.Cluster.Get(_clusterSystem).RegisterOnMemberRemoved(() => {
                _lifetime.StopApplication(); // when the ActorSystem terminates, terminate the process
            });

            return(Task.CompletedTask);
        }
Exemple #17
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            var hocon            = ConfigurationFactory.ParseString(await File.ReadAllTextAsync("app.conf", cancellationToken));
            var bootstrap        = BootstrapSetup.Create().WithConfig(hocon);
            var di               = ServiceProviderSetup.Create(_sp);
            var actorSystemSetup = bootstrap.And(di);

            _actorSystem = ActorSystem.Create("AspNetDemo", actorSystemSetup);
            // </AkkaServiceSetup>

            // <ServiceProviderFor>
            // props created via IServiceProvider dependency injection
            var hasherProps = ServiceProvider.For(_actorSystem).Props <HasherActor>();

            RouterActor = _actorSystem.ActorOf(hasherProps.WithRouter(FromConfig.Instance), "hasher");
            // </ServiceProviderFor>

            await Task.CompletedTask;
        }
        public static IServiceCollection AddAkkaService(this IServiceCollection services, string configfile, bool isdocker = false)
        {
            var config = HoconLoader.ParseConfig(configfile);

            if (isdocker)
            {
                config = config.BootstrapFromDocker();
            }

            services.AddSingleton(provider =>
            {
                var bootstrap        = BootstrapSetup.Create().WithConfig(config);
                var di               = ServiceProviderSetup.Create(provider);
                var actorSystemSetup = bootstrap.And(di);

                return(ActorSystem.Create(config.GetString("akka.MaserServer"), actorSystemSetup).StartPbm());
            });
            return(services);
        }
Exemple #19
0
        public async Task StartAsync()
        {
            var setup = ActorSystemSetup.Create(
                BootstrapSetup.Create()
                .WithConfig(Util.Config(_port))
                .WithConfigFallback(DistributedPubSub.DefaultConfig())
                .WithConfigFallback(ClusterClientReceptionist.DefaultConfig())
                .WithActorRefProvider(ProviderSelection.Cluster.Instance));

            _actorSystem = ActorSystem.Create(Consts.NodeName, setup);
            var cluster = Akka.Cluster.Cluster.Get(_actorSystem);
            await cluster.JoinSeedNodesAsync(Consts.Seeds);

            _receptionist = ClusterClientReceptionist.Get(_actorSystem);
            foreach (var id in Enumerable.Range(_nodeId * Consts.ActorCount, Consts.ActorCount))
            {
                var actor = _actorSystem.ActorOf(Props.Create(() => new ServiceActor(id)), Util.ActorName(id));
                _receptionist.RegisterService(actor);
            }
        }
        public Task StartAsync(CancellationToken cancellationToken)
        {
            var config    = ConfigurationFactory.ParseString(File.ReadAllText("app.conf")).BootstrapFromDocker();
            var bootstrap = BootstrapSetup.Create()
                            .WithConfig(config)                                        // load HOCON
                            .WithActorRefProvider(ProviderSelection.Cluster.Instance); // launch Akka.Cluster

            // N.B. `WithActorRefProvider` isn't actually needed here - the HOCON file already specifies Akka.Cluster

            // enable DI support inside this ActorSystem, if needed
            var diSetup = DependencyResolverSetup.Create(_serviceProvider);

            // merge this setup (and any others) together into ActorSystemSetup
            var actorSystemSetup = bootstrap.And(diSetup);

            // start ActorSystem
            ClusterSystem = ActorSystem.Create("ClusterSys", actorSystemSetup);

            // start Petabridge.Cmd (https://cmd.petabridge.com/)
            var pbm = PetabridgeCmd.Get(ClusterSystem);

            pbm.RegisterCommandPalette(ClusterCommands.Instance);
            pbm.RegisterCommandPalette(new RemoteCommands());
            pbm.Start(); // begin listening for PBM management commands

            // instantiate actors

            // use the ServiceProvider ActorSystem Extension to start DI'd actors
            var sp = DependencyResolver.For(ClusterSystem);;

            ConsoleActor = ClusterSystem.ActorOf(Props.Create(() => new ConsoleActor()), "console");

            // add a continuation task that will guarantee
            // shutdown of application if ActorSystem terminates first
            ClusterSystem.WhenTerminated.ContinueWith(tr => {
                _applicationLifetime.StopApplication();
            });

            return(Task.CompletedTask);
        }
Exemple #21
0
        static void Main(string[] args)
        {
            var logger = new LoggerConfiguration()
                         .WriteTo.File("log.txt", buffered: true, flushToDiskInterval: TimeSpan.FromSeconds(2))
                         .MinimumLevel.Information()
                         .CreateLogger();

            //TestDatabase();

            Serilog.Log.Logger = logger;
            var port = args.Length == 1 ? args[0] : "0";

            var config = hocon
                         .Replace("{{connection_string}}", Environment.GetEnvironmentVariable("CONNECTION_STRING"))
                         .Replace("{{port}}", port)
                         .Replace("{{hostname}}", "172.20.176.1");
            var ConfigBootstrap     = BootstrapSetup.Create().WithConfig(config);
            var ActorSystemSettings = ActorSystemSetup.Create(ConfigBootstrap);

            LotteryActorSystem = ActorSystem.Create(Constants.ActorSystemName, ActorSystemSettings);
            LotteryActorSystem.ActorOf(Props.Create(typeof(SimpleClusterListener)), "clusterListener");
            Props     lotterySupervisorProps = Props.Create <LotterySupervisor>();
            IActorRef lotterySupervisor      = LotteryActorSystem.ActorOf(lotterySupervisorProps, "LotterySupervisor");

            lotterySupervisor.Tell(new BeginPeriodMessage()
            {
                MinTickets = 5, MaxTickets = 10, NumberOfUsers = 20, NumberOfVendors = 150
            });
            Console.WriteLine("Ticket sales have begun, press enter to end period");
            Console.ReadLine();
            lotterySupervisor.Tell(new SupervisorSalesClosedMessage()
            {
            });

            Console.ReadLine();
            LotteryActorSystem.Terminate();

            ////Akka.Logger.Serilog.SerilogLogger
        }
Exemple #22
0
        /// <summary>
        ///     Loads from embedded resources actor system persistence configuration with <see cref="TestJournal"/> and
        ///     <see cref="TestSnapshotStore"/> configured as default persistence plugins.
        /// </summary>
        /// <param name="customConfig">Custom configuration that was passed in the constructor.</param>
        /// <returns>Actor system configuration object.</returns>
        /// <seealso cref="Config"/>
        private static ActorSystemSetup GetConfig(ActorSystemSetup customConfig)
        {
            var bootstrapSetup = customConfig.Get <BootstrapSetup>();
            var config         = bootstrapSetup.FlatSelect(x => x.Config);
            var actorProvider  = bootstrapSetup.FlatSelect(x => x.ActorRefProvider);
            var newSetup       = BootstrapSetup.Create();

            if (config.HasValue)
            {
                newSetup = newSetup.WithConfig(GetConfig(config.Value));
            }
            else
            {
                newSetup = newSetup.WithConfig(GetConfig(Config.Empty));
            }

            if (actorProvider.HasValue)
            {
                newSetup = newSetup.WithActorRefProvider(actorProvider.Value);
            }

            return(customConfig.WithSetup(newSetup));
        }
Exemple #23
0
        static async Task Main(string[] args)
        {
            var cts = new CancellationTokenSource();

            #region Console shutdown setup
            Console.CancelKeyPress += (sender, eventArgs) =>
            {
                eventArgs.Cancel = true;
                cts.Cancel();
            };

            AppDomain.CurrentDomain.ProcessExit += (sender, eventArgs) =>
            {
                cts.Cancel();
            };
            #endregion

            var setup = ActorSystemSetup.Create(
                BootstrapSetup.Create()
                .WithConfig(Util.Config(Consts.PortStart - 1))
                .WithActorRefProvider(ProviderSelection.Remote.Instance));

            var system      = ActorSystem.Create("ClusterClientSystem", setup);
            var clientActor = system.ActorOf(Props.Create(() => new ClientActor()));

            try
            {
                await Task.Delay(Timeout.Infinite, cts.Token);
            }
            catch (TaskCanceledException _)
            {
                // expected
            }

            await system.Terminate();
        }
Exemple #24
0
        /// <summary>
        /// Initializes the <see cref="TestState"/> for a new spec.
        /// </summary>
        /// <param name="system">The actor system this test will use. Can be null.</param>
        /// <param name="config">The configuration that <paramref name="system"/> will use if it's null.</param>
        /// <param name="actorSystemName">The name that <paramref name="system"/> will use if it's null.</param>
        /// <param name="testActorName">The name of the test actor. Can be null.</param>
        protected void InitializeTest(ActorSystem system, ActorSystemSetup config, string actorSystemName, string testActorName)
        {
            _testState = new TestState();

            if (system == null)
            {
                var bootstrap = config.Get <BootstrapSetup>();
                var configWithDefaultFallback = bootstrap.HasValue
                    ? bootstrap.Value.Config.Select(c => c == _defaultConfig ? c : c.WithFallback(_defaultConfig))
                    : _defaultConfig;

                var newBootstrap = BootstrapSetup.Create().WithConfig(
                    configWithDefaultFallback.HasValue
                        ? configWithDefaultFallback.Value
                        : _defaultConfig);
                if (bootstrap.FlatSelect(x => x.ActorRefProvider).HasValue)
                {
                    newBootstrap =
                        newBootstrap.WithActorRefProvider(bootstrap.FlatSelect(x => x.ActorRefProvider).Value);
                }
                system = ActorSystem.Create(actorSystemName ?? "test", config.WithSetup(newBootstrap));
            }

            _testState.System = system;

            system.RegisterExtension(new TestKitExtension());
            system.RegisterExtension(new TestKitAssertionsExtension(_assertions));

            _testState.TestKitSettings    = TestKitExtension.For(_testState.System);
            _testState.Queue              = new BlockingQueue <MessageEnvelope>();
            _testState.Log                = Logging.GetLogger(system, GetType());
            _testState.EventFilterFactory = new EventFilterFactory(this);

            //register the CallingThreadDispatcherConfigurator
            _testState.System.Dispatchers.RegisterConfigurator(CallingThreadDispatcher.Id,
                                                               new CallingThreadDispatcherConfigurator(_testState.System.Settings.Config, _testState.System.Dispatchers.Prerequisites));

            if (string.IsNullOrEmpty(testActorName))
            {
                testActorName = "testActor" + _testActorId.IncrementAndGet();
            }

            var testActor = CreateTestActor(system, testActorName);

            //Wait for the testactor to start
            // Calling sync version here, since .Wait() causes deadlock
            AwaitCondition(() =>
            {
                return(!(testActor is IRepointableRef repRef) || repRef.IsStarted);
            }, TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(10));

            if (!(this is INoImplicitSender))
            {
                InternalCurrentActorCellKeeper.Current = (ActorCell)((ActorRefWithCell)testActor).Underlying;
            }
            else if (!(this is TestProbe))
            //HACK: we need to clear the current context when running a No Implicit Sender test as sender from an async test may leak
            //but we should not clear the current context when creating a testprobe from a test
            {
                InternalCurrentActorCellKeeper.Current = null;
            }
            SynchronizationContext.SetSynchronizationContext(
                new ActorCellKeepingSynchronizationContext(InternalCurrentActorCellKeeper.Current));

            _testState.TestActor = testActor;
        }
        public async Task TestWithAkka()
        {
            const string topicName = "rmq.test.akka";

            var host = Host.CreateDefaultBuilder()
                       .ConfigureHostConfiguration(config =>
            {
                config.AddHoconFile("test.hocon");
            })
                       .ConfigureServices((context, services) =>
            {
                services.AddSingleton(sp =>
                                      new Akka.TestKit.Xunit2.TestKit(BootstrapSetup.Create()
                                                                      .And(ServiceProviderSetup.Create(sp))));

                services.AddSingleton(sp => sp.GetService <Akka.TestKit.Xunit2.TestKit>().Sys);

                services.AddRabbitMQ(context.Configuration, model =>
                {
                    model.QueueDelete(topicName, false, false);
                    model.QueueDeclare(topicName, false, false, false, null);
                });
            })
                       .UseAkka(sys =>
            {
            })
                       .Build();

            await host.StartAsync();

            var testKit = host.Services.GetService <Akka.TestKit.Xunit2.TestKit>();

            var receiverActor = testKit.ActorOf(testKit.Sys.PropsFactory <MQReceiverActor>().Create(topicName, testKit.TestActor), "ReceiverActor");
            var senderActor   = testKit.ActorOf(testKit.Sys.PropsFactory <MQPublisherActor>().Create(topicName), "SenderActor");

            senderActor.Tell("1");
            senderActor.Tell(new Hello());
            senderActor.Tell(new[] { 3 });
            senderActor.Tell("4");
            senderActor.Tell(new[] { "5" });

            testKit.ExpectMsg <MQReceiverActor.Received>((m, s) =>
            {
                m.Message.As <string>().Should().Be("1");
                s.Tell(new MQReceiverActor.Ack());
            }, 5.Seconds());

            testKit.ExpectMsg <MQReceiverActor.Received>((m, s) =>
            {
                m.Message.As <Hello>();
                s.Tell(new MQReceiverActor.Ack());
            });

            testKit.ExpectMsg <MQReceiverActor.Received>((m, s) =>
            {
                m.Message.As <IEnumerable <int> >()
                .Should()
                .BeSubsetOf(new[] { 3 });
                s.Tell(new MQReceiverActor.Nack());
            });

            testKit.ExpectMsg <MQReceiverActor.Received>((m, s) =>
            {
                m.Message.As <IEnumerable <int> >()
                .Should()
                .BeSubsetOf(new[] { 3 });
                s.Tell(new MQReceiverActor.Ack());
            });

            await host.StopAsync();
        }
Exemple #26
0
 public ActorServiceProviderPropsWithScopesSpecs(AkkaDiFixture fixture, ITestOutputHelper output) : base(DependencyResolverSetup.Create(fixture.Provider)
                                                                                                         .And(BootstrapSetup.Create().WithConfig(TestKitBase.DefaultConfig)), output)
 {
 }
Exemple #27
0
 /// <summary>
 /// Create a new instance of the <see cref="TestKitBase"/> class.
 /// A new system with the specified configuration will be created.
 /// </summary>
 /// <param name="assertions">The set of assertions used by the TestKit.</param>
 /// <param name="config">The configuration to use for the system.</param>
 /// <param name="actorSystemName">Optional: the name of the ActorSystem.</param>
 /// <param name="testActorName">Optional: the name of the TestActor.</param>
 /// <exception cref="ArgumentNullException">
 /// This exception is thrown when the given <paramref name="assertions"/> is undefined.
 /// </exception>
 protected TestKitBase(ITestKitAssertions assertions, Config config, string actorSystemName = null, string testActorName = null)
     : this(assertions, null, ActorSystemSetup.Empty.WithSetup(BootstrapSetup.Create().WithConfig(config)), actorSystemName, testActorName)
 {
 }
Exemple #28
0
 /// <summary>
 /// Create a new instance of the <see cref="TestKitBase"/> class.
 /// If no <paramref name="system"/> is passed in, a new system
 /// with <see cref="DefaultConfig"/> will be created.
 /// </summary>
 /// <param name="assertions">The framework-specific assertion tools.</param>
 /// <param name="system">Optional: The actor system.</param>
 /// <param name="testActorName">Optional: The name of the TestActor.</param>
 /// <exception cref="ArgumentNullException">
 /// This exception is thrown when the given <paramref name="assertions"/> is undefined.
 /// </exception>
 protected TestKitBase(ITestKitAssertions assertions, ActorSystem system = null, string testActorName = null)
     : this(assertions, system, ActorSystemSetup.Empty.WithSetup(BootstrapSetup.Create().WithConfig(_defaultConfig)), null, testActorName)
 {
 }
Exemple #29
0
 public ServiceProviderSetupSpecs(AkkaDiFixture fixture, ITestOutputHelper output) : base(ServiceProviderSetup.Create(fixture.Provider)
                                                                                          .And(BootstrapSetup.Create().WithConfig(TestKitBase.DefaultConfig)), output)
 {
 }
Exemple #30
0
 /// <summary>
 /// Initializes the <see cref="TestState"/> for a new spec.
 /// </summary>
 /// <param name="system">The actor system this test will use. Can be null.</param>
 /// <param name="config">The configuration that <paramref name="system"/> will use if it's null.</param>
 /// <param name="actorSystemName">The name that <paramref name="system"/> will use if it's null.</param>
 /// <param name="testActorName">The name of the test actor. Can be null.</param>
 protected void InitializeTest(ActorSystem system, Config config, string actorSystemName, string testActorName)
 {
     InitializeTest(system, ActorSystemSetup.Create(BootstrapSetup.Create().WithConfig(config)), actorSystemName, testActorName);
 }