예제 #1
0
        public virtual void Setup(BenchmarkContext context)
        {
            _counter = context.GetCounter(TotalCommandsExecutedCounter);
            var aggregateId = Guid.NewGuid().ToString();

            _commands = CreateAggregatePlan(100, aggregateId).ToArray();


            _actorSystem = ActorSystem.Create("test", _actorSystemConfig);
            _actorSystem.InitLocalTransportExtension();
            _actorSystem.InitDomainEventsSerialization(new EventsAdaptersCatalog());
            var log = new XUnitAutoTestLoggerConfiguration(_testOutputHelper, LogEventLevel.Warning, GetType().Name).CreateLogger();

            _actorSystem.AttachSerilogLogging(log);

            var dummy = _actorSystem.ActorOf <CustomHandlersActorDummy>();

            _aggregateActor = _actorSystem.ActorOf(Props.Create(
                                                       () => new AggregateActor <Balloon>(new BalloonCommandHandler(),
                                                                                          new EachMessageSnapshotsPersistencePolicy(),
                                                                                          AggregateFactory.Default,
                                                                                          AggregateFactory.Default,
                                                                                          dummy)),
                                                   EntityActorName.New <Balloon>(aggregateId).ToString());
        }
        protected DomainEventSourcedActor(IConstructAggregates aggregateConstructor,
                                          IConstructSnapshots snapshotsConstructor,
                                          ISnapshotsPersistencePolicy policy)
        {
            _snapshotsConstructor = snapshotsConstructor;

            _snapshotsPolicy        = policy;
            _snapshotsSaveTracker   = (policy as ISnapshotsSavePolicy).Tracking;
            _snapshotsDeleteTracker = (policy as ISnapshotsDeletePolicy).Tracking;

            PersistenceId = Self.Path.Name;
            Id            = EntityActorName.Parse <T>(Self.Path.Name).Id;
            State         = (T)aggregateConstructor.Build(typeof(T), Id, null);

            Monitor  = new ActorMonitor(Context, typeof(T).Name);
            Behavior = new BehaviorQueue(Become);

            DefaultBehavior();

            Recover <DomainEvent>(e => State.Apply(e));

            Recover <SnapshotOffer>(offer =>
            {
                _snapshotsPolicy.MarkSnapshotApplied(offer.Metadata.SequenceNr);
                State = (T)aggregateConstructor.Build(typeof(T), Id, (IMemento)offer.Snapshot);
                Log.Debug("Built state from snapshot #{snapshotNum}", offer.Metadata.SequenceNr);
            });

            Recover <RecoveryCompleted>(message =>
            {
                Log.Debug("Recovery completed");
                NotifyPersistenceWatchers(message);
            });
        }
        public async Task Save <T>(T aggr) where T : Aggregate
        {
            var persistId = EntityActorName.New <T>(aggr.Id).ToString();
            await _eventRepository.Save(persistId, ((IAggregate)aggr).GetUncommittedEvents().ToArray());

            aggr.ClearUncommitedEvents();
        }
예제 #4
0
        public Process_actor_should_execute_async_processes_with_block(ITestOutputHelper output)
        {
            var logger  = new XUnitAutoTestLoggerConfiguration(output).CreateLogger();
            var creator = new AsyncLongRunningProcessManagerFactory();

            _localAkkaEventBusTransport = Sys.InitLocalTransportExtension().Transport;
            var blackHole = Sys.ActorOf(BlackHoleActor.Props);

            var messageProcessActor = Sys.ActorOf(Props.Create(() => new HandlersPipeActor(new HandlersDefaultProcessor(), blackHole)));

            _processId = Guid.NewGuid().ToString();

            var container = new ContainerBuilder();

            container.Register <ProcessStateActor <TestState> >(c =>
                                                                new ProcessStateActor <TestState>(CommandAggregateHandler.New <ProcessStateAggregate <TestState> >(),
                                                                                                  new EachMessageSnapshotsPersistencePolicy(),
                                                                                                  AggregateFactory.Default,
                                                                                                  AggregateFactory.Default,
                                                                                                  messageProcessActor));
            Sys.AddDependencyResolver(new AutoFacDependencyResolver(container.Build(), Sys));
            Sys.AttachSerilogLogging(logger);
            //for process state retrival
            var processStateActor = Sys.ActorOf(Props.Create(() => new ProcessStateHubActor <TestState>(new DefaultRecycleConfiguration())), typeof(TestState).BeautyName() + "_Hub");
            var name = EntityActorName.New <ProcessStateAggregate <TestState> >(_processId).Name;

            _processActor = ActorOfAsTestActorRef(() => new ProcessActor <TestState>(new AsyncLongRunningProcess(), creator),
                                                  name);
        }
예제 #5
0
        public static async Task <T> LoadAggregateByActor <T>(this TestKit kit, string id) where T : Aggregate
        {
            var name  = EntityActorName.New <T>(id).ToString();
            var actor = await kit.LoadActor <AggregateActor <T> >(name);

            return(actor.State);
        }
예제 #6
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));
        }
예제 #7
0
 public ShardedAggregateCommand(ICommand command, IMessageMetadata metadata = null, IShardIdGenerator generator = null)
 {
     Metadata  = metadata ?? MessageMetadata.Empty;
     generator = generator ?? DefaultShardIdGenerator.Instance;
     ShardId   = generator.GetShardId(command.AggregateId);
     EntityId  = EntityActorName.GetFullName(command.AggregateType, command.AggregateId);
     Region    = Known.Names.Region(command.AggregateType);
     Message   = new AggregateActor.ExecuteCommand(command, Metadata);
 }
예제 #8
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));
        }
예제 #9
0
        public void Instance_process_actor_can_be_created()
        {
            var actorType = typeof(ProcessActor <SoftwareProgrammingState>);
            var props     = Node.System.DI().Props(actorType);
            var name      = EntityActorName.New <ProcessStateAggregate <SoftwareProgrammingState> >(Guid.NewGuid().ToString()).ToString();
            var actor     = Node.System.ActorOf(props, name);

            actor.Tell(new CheckHealth());
            ExpectMsg <HealthStatus>();
        }
예제 #10
0
        public async Task <T> LoadAggregate <T>(string id, IConstructAggregates factory = null) where T : IAggregate
        {
            var agr       = (factory ?? DefaultFactory).BuildEmpty <T>(id);
            var persistId = EntityActorName.New <T>(id).ToString();
            var events    = await _eventRepository.Load(persistId);

            foreach (var e in events.SelectMany(e => _eventsAdaptersCatalog.Update(e).Cast <DomainEvent>()))
            {
                agr.Apply(e);
            }
            return(agr);
        }
 public async Task Add<T>(T aggregate) where T : class, IAggregate
 {
     using (var repo = new RawSnapshotsRepository(option))
     {
         var snapshot = _snapshotsConstructor.GetSnapshot(aggregate);
         var item = new SnapshotItem
                    {
                        Manifest = snapshot.GetType().AssemblyQualifiedShortName(),
                        PersistenceId = EntityActorName.New<T>(aggregate.Id).Name,
                        Snapshot = new DomainSerializer().ToBinary(snapshot),
                        Timestamp = BusinessDateTime.UtcNow
                    };
         await repo.Save(item.PersistenceId, item);
     }
 }
예제 #12
0
        public AggregateActor()
        {
            Behavior = new BehaviorQueue(Become);
            Behavior.Become(AwaitingCommandBehavior, nameof(AwaitingCommandBehavior));
            PersistenceId = Self.Path.Name;
            Id            = EntityActorName.Parse <TAggregate>(Self.Path.Name).Id;

            var aggregateExtensions = Context.System.GetAggregatesExtension();
            var dependencies        = aggregateExtensions.GetDependencies <TAggregate>();

            Aggregate = dependencies.AggregateFactory.Build();


            Recover <DomainEvent>(e => Aggregate.Apply(e));
        }
        public async Task<Version<T>[]> Load<T>(string id) where T : class, IAggregate
        {
            var snapshotType = _snapshotsConstructor.GetSnapshot(_aggregatesConstructor.BuildEmpty<T>())
                                                    .GetType();

            var serializer = new DomainSerializer();
            
            using (var snapshotItemsRepo = new RawSnapshotsRepository(option))
            {
                return (await snapshotItemsRepo.Load(EntityActorName.New<T>(id).
                                                           Name)).Select(s =>
                                                                         {
                                                                             var memento = (IMemento) serializer.FromBinary(s.Snapshot, snapshotType);
                                                                             var aggregate = (T) _aggregatesConstructor.Build(typeof(T), id, memento);
                                                                             return new Version<T>(aggregate, s.Timestamp);
                                                                         }).
                                                                  ToArray();
            }
        }
예제 #14
0
        public void Aggregate_actor_produce_fault_with_processId_from_command()
        {
            var command = new GoSleepCommand(null, null).CloneForProcess(Guid.NewGuid().ToString());

            var transport = Sys.InitLocalTransportExtension().Transport;

            transport.Subscribe <MessageMetadataEnvelop <Fault <GoSleepCommand> > >(TestActor);
            var handlersActor = Sys.ActorOf(Props.Create(() => new HandlersPipeActor(new HandlersDefaultProcessor(), TestActor)));

            var actor = Sys.ActorOf(Props.Create(() => new AggregateActor <ProgrammerAggregate>(CommandAggregateHandler.New <ProgrammerAggregate>(null),
                                                                                                new SnapshotsPersistencePolicy(1, null, 5, null),
                                                                                                AggregateFactory.Default,
                                                                                                AggregateFactory.Default,
                                                                                                handlersActor)),
                                    EntityActorName.New <ProgrammerAggregate>(command.Id).Name);

            actor.Tell(new MessageMetadataEnvelop <ICommand>(command, MessageMetadata.New(command.Id, null, null)));

            var fault = FishForMessage <MessageMetadataEnvelop>(m => m.Message is Fault <GoSleepCommand>).Message as IFault;

            Assert.Equal(command.ProcessId, fault.ProcessId);
        }
        public async Task Given_only_aggregate_events_persisted_it_can_be_loaded(IRepository <DomainEvent> eventRepo,
                                                                                 AggregateRepository aggrRepo)
        {
            try
            {
                _sourceId = Guid.NewGuid().ToString();
                _created  = new BalloonCreated("initial value", _sourceId);
                _changed  = new BalloonTitleChanged("changed value", _sourceId);

                var persistenceId = EntityActorName.New <Balloon>(_sourceId).ToString();
                await eventRepo.Save(persistenceId, _created, _changed);

                _aggregate = await aggrRepo.LoadAggregate <Balloon>(_sourceId);

                Assert.Equal(_sourceId, _aggregate.Id);
                Assert.Equal(_changed.Value, _aggregate.Title);
            }
            finally
            {
                eventRepo.Dispose();
                aggrRepo.Dispose();
            }
        }
예제 #16
0
        public ProcessActor(IProcess <TState> process, IProcessStateFactory <TState> processStateFactory)

        {
            Process  = process;
            Monitor  = new ActorMonitor(Context, "Process" + typeof(TState).Name);
            Behavior = new BehaviorQueue(Become);

            if (!EntityActorName.TryParseId(Self.Path.Name, out var id))
            {
                throw new BadNameFormatException();
            }

            Id = id;

            _publisher           = Context.System.GetTransport();
            _processStateFactory = processStateFactory;
            _log = Context.GetSeriLogger();

            _exceptionOnTransit  = ProcessManagerActorConstants.ExceptionOnTransit(Self.Path.Name);
            _producedCommand     = ProcessManagerActorConstants.ProcessProduceCommands(Self.Path.Name);
            _stateActorSelection = Context.System.ActorSelection(ProcessStateActorSelection);

            Behavior.Become(InitializingBehavior, nameof(InitializingBehavior));
        }
예제 #17
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);
 }
예제 #18
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);
        }
예제 #19
0
 internal override string GetChildActorName(string childId)
 {
     return(EntityActorName.New <TAggregate>(childId).ToString());
 }