Exemple #1
0
 public static async Task SaveToJournal(this GridDomainNode node, string id, params object[] messages)
 {
     using (var repo = new ActorSystemJournalRepository(node.System, false))
     {
         await repo.Save(id, messages);
     }
 }
Exemple #2
0
 public static async Task <object[]> LoadFromJournal(this GridDomainNode node, string id)
 {
     using (var repo = new ActorSystemJournalRepository(node.System))
     {
         return(await repo.Load(id));
     }
 }
        static void Main(string[] args)
        {
            var node = new GridDomainNode(() => ActorSystem.Create());


            Console.ReadKey();
        }
        public async Task Clear_child_lifetimes()
        {
            _gridDomainNode = new GridDomainNode(CreateConfiguration(), new SoftwareProgrammingSagaRoutes(), () => new [] { Sys });
            await _gridDomainNode.Start();

            switch (_case)
            {
            case PersistentHubTestsStatus.PersistenceCase.Aggregate:
                Infrastructure = new AggregatePersistedHub_Infrastructure(_gridDomainNode.System);
                break;

            case PersistentHubTestsStatus.PersistenceCase.IstanceSaga:
                Infrastructure = new InstanceSagaPersistedHub_Infrastructure(_gridDomainNode.System);
                break;

            case PersistentHubTestsStatus.PersistenceCase.StateSaga:
                Infrastructure = new StateSagaPersistedHub_Infrastructure(_gridDomainNode.System);
                break;

            default:
                throw new UnknownCaseException();
            }
            var actorOfAsTestActorRef = ActorOfAsTestActorRef <PersistentHubActor>(Infrastructure.HubProps, "TestHub_" + Guid.NewGuid());

            Hub    = actorOfAsTestActorRef.UnderlyingActor;
            HubRef = actorOfAsTestActorRef.Ref;
        }
Exemple #5
0
        public static async Task <IActorRef> LookupAggregateActor <T>(this GridDomainNode node,
                                                                      string id,
                                                                      TimeSpan?timeout = null) where T : IAggregate
        {
            var name = EntityActorName.New <T>(id).Name;

            return(await node.ResolveActor($"{typeof(T).Name}_Hub/{name}", timeout));
        }
Exemple #6
0
        public static IMessageWaiter <AnyMessagePublisher> NewDebugWaiter(this GridDomainNode node, TimeSpan?timeout = null)
        {
            var conditionBuilder = new MetadataConditionBuilder <AnyMessagePublisher>();
            var waiter           = new LocalMessagesWaiter <AnyMessagePublisher>(node.System, node.Transport, timeout ?? node.DefaultTimeout, conditionBuilder);

            conditionBuilder.CreateResultFunc = t => new AnyMessagePublisher(node.Pipe, waiter);
            return(waiter);
        }
Exemple #7
0
        public static async Task <IActorRef> LookupProcessActor <TProcess, TData>(this GridDomainNode node,
                                                                                  string id,
                                                                                  TimeSpan?timeout = null) where TData : IProcessState
        {
            var name = EntityActorName.New <TProcess>(id).Name;
            var type = typeof(TProcess).BeautyName();

            return(await node.ResolveActor($"{type}_Hub/{name}", timeout));
        }
Exemple #8
0
 public static async Task <TAggregate> LoadAggregate <TAggregate>(this GridDomainNode node, string id)
     where TAggregate : Aggregate
 {
     using (var eventsRepo = new ActorSystemEventRepository(node.System))
         using (var repo = new AggregateRepository(eventsRepo))
         {
             return(await repo.LoadAggregate <TAggregate>(id));
         }
 }
Exemple #9
0
        public static async Task SaveToJournal <TAggregate>(this GridDomainNode node, TAggregate aggregate) where TAggregate : Aggregate
        {
            var domainEvents = ((IAggregate)aggregate).GetUncommittedEvents()
                               .ToArray();

            await node.SaveToJournal <TAggregate>(aggregate.Id, domainEvents);

            aggregate.ClearUncommitedEvents();
        }
Exemple #10
0
        public void Start()
        {
            Log.Information($"Created shop node {NodeConfiguration.Name} at {NodeConfiguration.Address.Host} on port {NodeConfiguration.Address.PortNumber}");

            var actorSystemFactory = ActorSystemBuilder.New().Build(NodeConfiguration, new ShopNodeDbConfig());

            _gridDomainNode = new GridDomainNode(actorSystemFactory, _logger ?? Log.Logger, new ShopDomainConfiguration(ReadDbConnectionString));
            _gridDomainNode.Start().Wait();
        }
Exemple #11
0
        public static async Task <TExpect> SendToProcessManager <TExpect>(this GridDomainNode node, DomainEvent msg, TimeSpan?timeout = null) where TExpect : class
        {
            var res = await node.NewDebugWaiter(timeout)
                      .Expect <TExpect>()
                      .Create()
                      .SendToProcessManagers(msg);

            return(res.Message <TExpect>());
        }
        public NodeCommandExecutionTests(ITestOutputHelper helper) : base(_config, nodeName, helper)
        {
            Serilog.Log.Logger = new LoggerConfiguration().WriteTo.Console()
                                 .WriteTo.File(Path.Combine("Logs", nameof(NodeCommandExecutionTests) + ".log"))
                                 .CreateLogger();

            var node = new GridDomainNode(new[] { new CatDomainConfiguration() },
                                          new DelegateActorSystemFactory(() => Sys), Serilog.Log.Logger, TimeSpan.FromSeconds(5));

            _domain = node.Start().Result;
        }
Exemple #13
0
        public async Task When_settings_are_customized_it_is_used_by_grid_node()
        {
            var node = new GridDomainNode(CustomContainerConfiguration.Empty(), new BalanceRouteMap(), () => ActorSystem.Create("test"));
            await node.Start();

            var ext = DomainEventsJsonSerializationExtensionProvider.Provider.Get(node.System);

            ext.Settings = new MyJsonSettings();

            var serializer = new DomainEventsJsonAkkaSerializer(node.System as ExtendedActorSystem);

            Assert.IsInstanceOf <MyJsonSettings>(serializer.Serializer.Value.JsonSerializerSettings);
        }
Exemple #14
0
        private static async Task ShutDownHubActor(GridDomainNode node, string id, IActorRef aggregateActor, IActorRef aggregateHubActor, TimeSpan?timeout = null)
        {
            using (var inbox = Inbox.Create(node.System))
            {
                inbox.Watch(aggregateActor);
                aggregateHubActor.Tell(new ShutdownChild(id));

                var msg = await inbox.ReceiveAsync(timeout ?? node.DefaultTimeout);

                if (!(msg is Terminated))
                {
                    throw new UnexpectedMessageExpection($"Expected {typeof(Terminated)} but got {msg}");
                }
            }
        }
Exemple #15
0
        protected virtual async Task Start()
        {
            LogManager.SetLoggerFactory(new AutoTestLogFactory());

            var autoTestGridDomainConfiguration = new AutoTestLocalDbConfiguration();

            if (ClearDataOnStart)
            {
                TestDbTools.ClearData(autoTestGridDomainConfiguration, AkkaConf.Persistence);
            }

            GridNode = CreateGridDomainNode(AkkaConf);
            OnNodeCreated();
            await GridNode.Start();

            OnNodeStarted();
        }
Exemple #16
0
        private static GridDomainNode StartSampleDomainNode()
        {
            var unityContainer = new UnityContainer();

            unityContainer.Register(new SampleDomainContainerConfiguration());

            var cfg = new CustomContainerConfiguration(
                c => c.Register(new SampleDomainContainerConfiguration()),
                c => c.RegisterType <IPersistentChildsRecycleConfiguration, InsertOptimazedBulkConfiguration>(),
                c => c.RegisterType <IQuartzConfig, PersistedQuartzConfig>());

            Func <ActorSystem[]> actorSystemFactory = () => new[] { new StressTestAkkaConfiguration().CreateSystem() };

            var node = new GridDomainNode(cfg, new SampleRouteMap(unityContainer), actorSystemFactory);

            node.Start().Wait();
            return(node);
        }
Exemple #17
0
        public static async Task KillAggregate <TAggregate>(this GridDomainNode node, string id, TimeSpan?timeout = null)
            where TAggregate : Aggregate
        {
            IActorRef aggregateHubActor;
            IActorRef aggregateActor;

            try
            {
                aggregateHubActor = await node.LookupAggregateHubActor <TAggregate>(timeout);

                aggregateActor = await node.LookupAggregateActor <TAggregate>(id, timeout);
            }
            catch (ActorNotFoundException)
            {
                return;
            }
            await ShutDownHubActor(node, id, aggregateActor, aggregateHubActor, timeout);
        }
Exemple #18
0
        public async Task Given_existing_GridNode()
        {
            var container = new UnityContainer();
            var sampleDomainContainerConfiguration = new SampleDomainContainerConfiguration();

            container.Register(sampleDomainContainerConfiguration);

            var serverConfig = new TestGridNodeConfiguration();

            _node = new GridDomainNode(sampleDomainContainerConfiguration,
                                       new SampleRouteMap(container),
                                       () => serverConfig.CreateInMemorySystem());

            await _node.Start();


            _connector = new GridNodeConnector(serverConfig.Network);
            _connector.Connect();
        }
Exemple #19
0
        public static async Task KillProcessManager <TProcess, TState>(this GridDomainNode node, string id, TimeSpan?timeout = null)
            where TState : IProcessState
        {
            var hub = await node.LookupProcessHubActor <TProcess>(timeout);

            IActorRef processActor;

            try
            {
                processActor = await node.LookupProcessActor <TProcess, TState>(id, timeout);
            }
            catch
            {
                return;
            }

            await ShutDownHubActor(node, id, processActor, hub, timeout);

            var processStateHubActor = await node.ResolveActor($"{typeof(TState).Name}_Hub", timeout);

            var processStateActor = await node.ResolveActor($"{typeof(TState).Name}_Hub/" + EntityActorName.New <ProcessStateAggregate <TState> >(id), timeout);

            await ShutDownHubActor(node, id, processStateActor, processStateHubActor, timeout);
        }
Exemple #20
0
 public static async Task SaveToJournal <TAggregate>(this GridDomainNode node, string id, params DomainEvent[] messages)
     where TAggregate : Aggregate
 {
     var name = EntityActorName.New <TAggregate>(id).Name;
     await node.SaveToJournal(name, messages);
 }
Exemple #21
0
 public static IMessageWaiter <AnyMessagePublisher> NewDebugWaiter(this GridDomainNode node, TimeSpan?timeout = null)
 {
     return(new DebugLocalWaiter(node.Transport, node.System, node.Transport, timeout ?? node.DefaultTimeout));
 }
Exemple #22
0
        public static async Task <WarmUpResult> WarmUpProcessManager <TProcess>(this GridDomainNode node, string id, TimeSpan?timeout = null)
        {
            var processHub = await node.LookupProcessHubActor <TProcess>(timeout);

            return(await processHub.Ask <WarmUpResult>(new WarmUpChild(id)));
        }
Exemple #23
0
 public static async Task <IActorRef> LookupProcessHubActor <TProcess>(this GridDomainNode node, TimeSpan?timeout = null)
 {
     return(await node.ResolveActor($"{typeof(TProcess).BeautyName()}_Hub", timeout));
 }
Exemple #24
0
        public static async Task <TState> GetCreatedState <TState>(this GridDomainNode node, DomainEvent msg, TimeSpan?timeout = null) where TState : IProcessState
        {
            var res = await node.SendToProcessManager <ProcessManagerCreated <TState> >(msg, timeout);

            return(res.State);
        }
Exemple #25
0
 private static void ApplySeeds(GridDomainNode node)
 {
 }
Exemple #26
0
 public static Task SendToProcessManagers(this GridDomainNode node, DomainEvent msg, TimeSpan?timeout = null)
 {
     return(node.Pipe.ProcessesPipeActor.Ask <ProcessesTransitComplete>(new MessageMetadataEnvelop(msg), timeout));
 }
Exemple #27
0
        private static Task <IWaitResults> WaitAggregateCommands(int changeNumber, Random random, GridDomainNode node)
        {
            var commands  = new List <ICommand>(changeNumber + 1);
            var createCmd = new CreateSampleAggregateCommand(random.Next(), Guid.NewGuid());

            commands.Add(createCmd);

            var expectBuilder = node.NewCommandWaiter()
                                .Expect <SampleAggregateCreatedEvent>(e => e.SourceId == createCmd.AggregateId);


            var changeCmds = Enumerable.Range(0, changeNumber)
                             .Select(n => new ChangeSampleAggregateCommand(random.Next(), createCmd.AggregateId))
                             .ToArray();

            commands.AddRange(changeCmds);


            foreach (var cmd in changeCmds)
            {
                expectBuilder.And <SampleAggregateChangedEvent>(e => e.SourceId == cmd.AggregateId && e.Value == cmd.Parameter.ToString());
            }

            return(expectBuilder.Create()
                   .Execute(commands.ToArray()));
        }
Exemple #28
0
 public static async Task <IActorRef> LookupAggregateHubActor <T>(this GridDomainNode node, TimeSpan?timeout = null)
     where T : IAggregate
 {
     return(await node.ResolveActor($"{typeof(T).Name}_Hub", timeout));
 }
Exemple #29
0
        private static void RawCommandExecution(int totalAggregateScenariosCount, int aggregateScenarioPackSize, int aggregateChangeAmount)
        {
            var dbCfg = new AutoTestAkkaConfiguration();

            using (var connection = new SqlConnection(dbCfg.Persistence.JournalConnectionString))
            {
                connection.Open();
                var sqlText    = @"TRUNCATE TABLE Journal";
                var cmdJournal = new SqlCommand(sqlText, connection);
                cmdJournal.ExecuteNonQuery();

                var sqlText1     = @"TRUNCATE TABLE Snapshots";
                var cmdSnapshots = new SqlCommand(sqlText, connection);
                cmdSnapshots.ExecuteNonQuery();
            }

            var unityContainer = new UnityContainer();

            unityContainer.Register(new SampleDomainContainerConfiguration());

            var cfg = new CustomContainerConfiguration(
                c => c.Register(new SampleDomainContainerConfiguration()),
                c => c.RegisterType <IPersistentChildsRecycleConfiguration, InsertOptimazedBulkConfiguration>(),
                c => c.RegisterType <IQuartzConfig, PersistedQuartzConfig>());

            Func <ActorSystem[]> actorSystemFactory = () => new[] { new StressTestAkkaConfiguration().CreateSystem() };

            var node = new GridDomainNode(cfg, new SampleRouteMap(unityContainer), actorSystemFactory);

            node.Start().Wait();

            var timer = new Stopwatch();

            timer.Start();

            int timeoutedCommads     = 0;
            var random               = new Random();
            var commandsInScenario   = aggregateScenarioPackSize * (aggregateChangeAmount + 1);
            var totalCommandsToIssue = commandsInScenario * totalAggregateScenariosCount;


            for (int i = 0; i < totalAggregateScenariosCount; i++)
            {
                var packTimer = new Stopwatch();
                packTimer.Start();
                var tasks = Enumerable.Range(0, aggregateScenarioPackSize)
                            .Select(t => WaitAggregateCommands(aggregateChangeAmount, random, node))
                            .ToArray();
                try
                {
                    Task.WhenAll(tasks).Wait();
                }
                catch
                {
                    timeoutedCommads += tasks.Count(t => t.IsCanceled || t.IsFaulted);
                }

                packTimer.Stop();
                var speed    = (decimal)(commandsInScenario / packTimer.Elapsed.TotalSeconds);
                var timeLeft = TimeSpan.FromSeconds((double)((totalCommandsToIssue - i * commandsInScenario) / speed));

                Console.WriteLine($"speed :{speed} cmd/sec," +
                                  $"total errors: {timeoutedCommads}, " +
                                  $"total commands executed: {i*commandsInScenario}/{totalCommandsToIssue}," +
                                  $"approx time remaining: {timeLeft}");
            }


            timer.Stop();
            node.Stop().Wait();

            var speedTotal = (decimal)(totalCommandsToIssue / timer.Elapsed.TotalSeconds);

            Console.WriteLine(
                $"Executed {totalAggregateScenariosCount} batches = {totalCommandsToIssue} commands in {timer.Elapsed}");
            Console.WriteLine($"Average speed was {speedTotal} cmd/sec");

            using (var connection = new SqlConnection(dbCfg.Persistence.JournalConnectionString))
            {
                connection.Open();
                var sqlText    = @"SELECT COUNT(*) FROM Journal";
                var cmdJournal = new SqlCommand(sqlText, connection);
                var count      = (int)cmdJournal.ExecuteScalar();

                Console.WriteLine(count == totalCommandsToIssue
                    ? "Journal contains all events"
                    : $"Journal contains only {count} of {totalCommandsToIssue}");
            }
        }
Exemple #30
0
 public static async Task <IActorRef> ResolveActor(this GridDomainNode node, string actorPath, TimeSpan?timeout = null)
 {
     return(await node.System.ActorSelection("user/" + actorPath).ResolveOne(timeout ?? node.DefaultTimeout));
 }