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 GetEventStoreAdapter(IEventStoreConnection eventStoreConnection, IEventPublisher eventsPublisher, Func <Type, Guid, string> aggregateIdToStreamName, IConstructAggregates constructAggregates)
 {
     m_EventsPublisher         = eventsPublisher;
     m_EventStoreConnection    = eventStoreConnection;
     m_AggregateIdToStreamName = aggregateIdToStreamName;
     m_ConstructAggregates     = constructAggregates;
 }
        public void SimpleAggregateSnapshottingViaSnapshotCreator()
        {
            IStoreEvents          memoryStore      = Wireup.Init().UsingInMemoryPersistence().Build();
            IConstructAggregates  aggregateFactory = A.Fake <IConstructAggregates>();
            IEventStoreRepository repository       = new InMemoryDomainRepository(memoryStore, aggregateFactory, new CommonDomain.Core.ConflictDetector());
            Guid            aggregateID            = Guid.NewGuid();
            SimpleAggregate aggregate = new SimpleAggregate(aggregateID, DateTime.Now);

            repository.Save(aggregate, Guid.NewGuid());

            A.CallTo(() => aggregateFactory.Build(typeof(SimpleAggregate), aggregate.Id, null)).ReturnsLazily(() => new SimpleAggregate());

            SnapshotCreator <SimpleAggregate> snapshotCreator = new SnapshotCreator <SimpleAggregate>(repository, 1);
            Snapshot snapshot = snapshotCreator.SaveSnapShot(aggregate.Id);

            A.CallTo(() => aggregateFactory.Build(typeof(SimpleAggregate), aggregate.Id, A <IMemento> .That.IsNull())).MustHaveHappened(Repeated.Exactly.Once);

            ISnapshot retrievedSnapshot = repository.EventStore.Advanced.GetSnapshot(aggregate.Id, int.MaxValue);

            A.CallTo(() => aggregateFactory.Build(typeof(SimpleAggregate), aggregate.Id, A <IMemento> .That.IsNull())).MustHaveHappened(Repeated.Exactly.Once);

            retrievedSnapshot.Should().NotBeNull();
            retrievedSnapshot.StreamRevision.Should().Be(1);
            retrievedSnapshot.ShouldBeEquivalentTo(snapshot);

            SimpleAggregate retrievedAggregate = repository.GetById <SimpleAggregate>(aggregate.Id);

            retrievedAggregate.Should().NotBeNull();
            aggregate.Version.Should().Be(1);
            retrievedAggregate.ShouldBeEquivalentTo(aggregate);
            A.CallTo(aggregateFactory).Where(o => o.Method.Name != "Build").MustNotHaveHappened();
            A.CallTo(() => aggregateFactory.Build(typeof(SimpleAggregate), aggregate.Id, A <IMemento> .That.IsNull())).MustHaveHappened(Repeated.Exactly.Once);

            A.CallTo(() => aggregateFactory.Build(typeof(SimpleAggregate), aggregate.Id, A <IMemento> .That.Not.IsNull())).MustHaveHappened();
        }
 public AggregateSnapshotRepository(DbContextOptions dbOptions, 
                                    IConstructAggregates aggregatesConstructor,
                                    IConstructSnapshots snapshotsConstructor)
 {
     _snapshotsConstructor = snapshotsConstructor;
     _aggregatesConstructor = aggregatesConstructor;
     option = dbOptions;
 }
Example #5
0
 public EventStoreRepository(
     IStoreEvents eventStore,
     IConstructAggregates factory,
     IDetectConflicts conflictDetector)
 {
     this.eventStore       = eventStore;
     this.factory          = factory;
     this.conflictDetector = conflictDetector;
 }
Example #6
0
 public PlacementService(
     IDbService dbService,
     IConstructAggregates factory,
     IRepository repository)
 {
     _dbService  = dbService;
     _factory    = factory;
     _repository = repository;
 }
Example #7
0
        public EventSourcedActor(IConstructAggregates aggregateConstructor,
                                 ISnapshotsPersistencePolicy policy,
                                 IPublisher publisher)
        {
            PersistenceId         = Self.Path.Name;
            SnapshotsPolicy       = policy;
            _aggregateConstructor = aggregateConstructor;
            Publisher             = publisher;
            Id      = AggregateActorName.Parse <T>(Self.Path.Name).Id;
            State   = (AggregateBase)aggregateConstructor.Build(typeof(T), Id, null);
            Monitor = new ActorMonitor(Context, typeof(T).Name);
            Command <GracefullShutdownRequest>(req =>
            {
                Monitor.IncrementMessagesReceived();
                DeleteSnapshots(SnapshotsPolicy.GetSnapshotsToDelete());
                Become(Terminating);
            });

            Command <CheckHealth>(s => Sender.Tell(new HealthStatus(s.Payload)));

            Command <SaveSnapshotSuccess>(s =>
            {
                NotifyWatchers(s);
                SnapshotsPolicy.MarkSnapshotSaved(s.Metadata);
            });

            Command <NotifyOnPersistenceEvents>(c =>
            {
                var waiter = c.Waiter ?? Sender;
                if (IsRecoveryFinished)
                {
                    waiter.Tell(RecoveryCompleted.Instance);
                }

                _persistenceWaiters.Add(waiter);
            });

            Recover <DomainEvent>(e =>
            {
                State.ApplyEvent(e);
                SnapshotsPolicy.MarkActivity(e.CreatedTime);
            });

            Recover <SnapshotOffer>(offer =>
            {
                SnapshotsPolicy.MarkSnapshotApplied(offer.Metadata);
                State = _aggregateConstructor.Build(typeof(T), Id, (IMemento)offer.Snapshot);
            });

            Recover <RecoveryCompleted>(message =>
            {
                _log.Debug("Recovery for actor {Id} is completed", PersistenceId);
                NotifyWatchers(message);
            });
        }
 public SelfAssessmentService(
     IDbService dbService,
     IConstructAggregates factory,
     IRepository repository,
     ILogger <SelfAssessmentService> logger)
 {
     _dbService  = dbService;
     _factory    = factory;
     _repository = repository;
     _logger     = logger;
 }
 public ProcessStateActor(IAggregateCommandsHandler <ProcessStateAggregate <TState> > handler,
                          ISnapshotsPersistencePolicy snapshotsPersistencePolicy,
                          IConstructAggregates aggregateConstructor,
                          IConstructSnapshots snapshotsConstructor,
                          IActorRef customHandlersActor) : base(handler,
                                                                snapshotsPersistencePolicy,
                                                                aggregateConstructor,
                                                                snapshotsConstructor,
                                                                customHandlersActor)
 {
 }
        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 override void Create(BoundedContext boundedContext, IDependencyResolver resolver)
        {
            m_ConstructAggregates = resolver.HasService(typeof(IConstructAggregates))
                ? (IConstructAggregates)resolver.GetService(typeof(IConstructAggregates))
                : null;

            m_ConnectionFactory = resolver.HasService(typeof(IConnectionFactory))
                ? (IConnectionFactory)resolver.GetService(typeof(IConnectionFactory))
                : new ConfigurationConnectionFactory(null);

            IStoreEvents eventStore = m_ConfigureEventStore(new CommitDispatcher(boundedContext.EventsPublisher), m_ConnectionFactory).Build();

            EventStoreAdapter = new NEventStoreAdapter(eventStore, m_ConstructAggregates);
        }
Example #12
0
 public AggregateActor(IAggregateCommandsHandler <TAggregate> handler,
                       ISnapshotsPersistencePolicy snapshotsPersistencePolicy,
                       IConstructAggregates aggregateConstructor,
                       IConstructSnapshots snapshotsConstructor,
                       IActorRef customHandlersActor) : base(aggregateConstructor, snapshotsConstructor, snapshotsPersistencePolicy)
 {
     _aggregateCommandsHandler = handler;
     _publisher                    = Context.System.GetTransport();
     _customHandlersActor          = customHandlersActor;
     _domainEventProcessEntry      = new ProcessEntry(Self.Path.Name, AggregateActorConstants.PublishingEvent, AggregateActorConstants.CommandExecutionCreatedAnEvent);
     _domainEventProcessFailEntry  = new ProcessEntry(Self.Path.Name, AggregateActorConstants.CommandExecutionFinished, AggregateActorConstants.CommandRaisedAnError);
     _commandCompletedProcessEntry = new ProcessEntry(Self.Path.Name, AggregateActorConstants.CommandExecutionFinished, AggregateActorConstants.ExecutedCommand);
     Behavior.Become(AwaitingCommandBehavior, nameof(AwaitingCommandBehavior));
 }
Example #13
0
        public AggregateActor(IAggregateCommandsHandler<TAggregate> handler,
                              TypedMessageActor<ScheduleCommand> schedulerActorRef,
                              TypedMessageActor<Unschedule> unscheduleActorRef,
                              IPublisher publisher,
                              ISnapshotsPersistencePolicy snapshotsPersistencePolicy,
                              IConstructAggregates aggregateConstructor) : base(
                                                                            aggregateConstructor,
                                                                            snapshotsPersistencePolicy,
                                                                            publisher)
        {
            _schedulerActorRef = schedulerActorRef;
            _unscheduleActorRef = unscheduleActorRef;
            _handler = handler;

            //async aggregate method execution finished, aggregate already raised events
            //need process it in usual way
            Command<IMessageMetadataEnvelop<AsyncEventsReceived>>(d =>
            {
                var m = d.Message;
                Monitor.IncrementMessagesReceived();
                if (m.Exception != null)
                {
                    ProcessFault(m.Command, m.Exception, d.Metadata);
                    return;
                }

                (State as Aggregate).FinishAsyncExecution(m.InvocationId);
                ProcessAggregateEvents(m.Command, d.Metadata);
            });

            Command<IMessageMetadataEnvelop<ICommand>>(m =>
            {
                var cmd = m.Message;
                Monitor.IncrementMessagesReceived();
                _log.Trace("{Aggregate} received a {@command}", State.Id, cmd);
                try
                {
                    State = _handler.Execute((TAggregate)State, cmd);
                }
                catch (Exception ex)
                {
                    ProcessFault(cmd, ex, m.Metadata);
                    return;
                }

                ProcessAggregateEvents(cmd, m.Metadata);
            });
        }
        public void SimpleAggregateRetrieval()
        {
            IStoreEvents          memoryStore      = Wireup.Init().UsingInMemoryPersistence().Build();
            IConstructAggregates  aggregateFactory = A.Fake <IConstructAggregates>();
            IEventStoreRepository repository       = new InMemoryDomainRepository(memoryStore, aggregateFactory, new CommonDomain.Core.ConflictDetector());
            Guid            aggregateID            = Guid.NewGuid();
            SimpleAggregate aggregate = new SimpleAggregate(aggregateID, DateTime.Now);

            repository.Save(aggregate, Guid.NewGuid());

            A.CallTo(() => aggregateFactory.Build(typeof(SimpleAggregate), aggregate.Id, null)).Returns(new SimpleAggregate(aggregateID, DateTime.Now));

            repository.GetById <SimpleAggregate>(aggregate.Id);

            A.CallTo(aggregateFactory).MustHaveHappened();
            A.CallTo(aggregateFactory).Where(o => o.Method.Name != "Build").MustNotHaveHappened();
            A.CallTo(() => aggregateFactory.Build(typeof(SimpleAggregate), aggregate.Id, A <IMemento> .That.Not.IsNull())).MustNotHaveHappened();
        }
Example #15
0
        public SagaActor(ISagaProducer <TSaga> producer,
                         IPublisher publisher,
                         ISnapshotsPersistencePolicy snapshotsPersistencePolicy,
                         IConstructAggregates aggregatesConstructor)
            : base(aggregatesConstructor,
                   snapshotsPersistencePolicy,
                   publisher)
        {
            _producer = producer;
            _sagaStartMessageTypes = new HashSet <Type>(producer.KnownDataTypes.Where(t => typeof(DomainEvent).IsAssignableFrom(t)));
            _sagaIdFields          = producer.Descriptor.AcceptMessages.ToDictionary(m => m.MessageType, m => m.CorrelationField);

            //id from name is used due to saga.Data can be not initialized before messages not belonging to current saga will be received
            Command <IMessageMetadataEnvelop <DomainEvent> >(m =>
            {
                var msg = m.Message;
                Monitor.IncrementMessagesReceived();
                if (_sagaStartMessageTypes.Contains(msg.GetType()))
                {
                    _saga = _producer.Create(msg);
                    State = _saga.Data;
                }

                ProcessSaga(msg, m.Metadata);
            }, e => GetSagaId(e.Message) == Id);

            Command <IMessageMetadataEnvelop <IFault> >(m =>
            {
                var fault = m.Message;
                Monitor.IncrementMessagesReceived();
                ProcessSaga(fault, m.Metadata);
            }, fault => fault.Message.SagaId == Id);

            _sagaProducedEntry = new ProcessEntry(Self.Path.Name, SagaActorLiterals.PublishingCommand, SagaActorLiterals.SagaProducedACommand);

            _exceptionOnTransit = new ProcessEntry(Self.Path.Name, SagaActorLiterals.CreatedFaultForSagaTransit, SagaActorLiterals.SagaTransitCasedAndError);
        }
        public void SimpleAggregateDirectSnapshotting()
        {
            IStoreEvents          memoryStore      = Wireup.Init().UsingInMemoryPersistence().Build();
            IConstructAggregates  aggregateFactory = A.Fake <IConstructAggregates>();
            IEventStoreRepository repository       = new InMemoryDomainRepository(memoryStore, aggregateFactory, new CommonDomain.Core.ConflictDetector());
            Guid            aggregateID            = Guid.NewGuid();
            SimpleAggregate aggregate = new SimpleAggregate(aggregateID, DateTime.Now);

            repository.Save(aggregate, Guid.NewGuid());
            IMemento  memento  = aggregate.CreateMemento();
            ISnapshot snapshot = new Snapshot(aggregate.Id.ToString(), aggregate.Version, memento);

            repository.EventStore.Advanced.AddSnapshot(snapshot);

            ISnapshot retrievedSnapshot = repository.EventStore.Advanced.GetSnapshot(aggregate.Id, int.MaxValue);

            retrievedSnapshot.Should().NotBeNull();
            retrievedSnapshot.StreamRevision.Should().Be(1);
            retrievedSnapshot.ShouldBeEquivalentTo(snapshot);

            repository.GetById <SimpleAggregate>(aggregate.Id);

            A.CallTo(() => aggregateFactory.Build(typeof(SimpleAggregate), aggregate.Id, A <IMemento> .That.Not.IsNull())).MustHaveHappened();
        }
 public AggregateConfiguration(Func <ISnapshotsPersistencePolicy> snapshotsPolicy, IConstructAggregates snapshotsFactory) : base(snapshotsPolicy, snapshotsFactory)
 {
 }
 public EventStoreModule ConstructAggregatesWith(IConstructAggregates constructor)
 {
     aggregateConstructor = constructor;
     return(this);
 }
        public static DefaultAggregateDependencyFactory <TCommandAggregate> ForCommandAggregate <TCommandAggregate>(IConstructAggregates factory = null) where TCommandAggregate : CommandAggregate
        {
            var depFactory = new DefaultAggregateDependencyFactory <TCommandAggregate>(() => CommandAggregateHandler.New <TCommandAggregate>(factory));

            if (factory != null)
            {
                depFactory.AggregateFactoryCreator = () => factory;
            }
            return(depFactory);
        }
 public AggregateSnapshotRepository(string connString,
                                    IConstructAggregates aggregatesConstructor,
                                    IConstructSnapshots snapshotsConstructor
                                    ) : this(new DbContextOptionsBuilder().UseSqlServer(connString).Options,
                                                                                       aggregatesConstructor,
                                             snapshotsConstructor) { }
Example #21
0
 public NEventStoreAdapter(IStoreEvents storeEvents, IConstructAggregates aggregateFactory = null)
 {
     m_StoreEvents = storeEvents;
     Repository    = new EventStoreRepository(storeEvents, aggregateFactory ?? new AggregateFactory(), new ConflictDetector());
 }
 public EventStoreModule ConstructAggregatesWith(IConstructAggregates constructor)
 {
     aggregateConstructor = constructor;
     return this;
 }
 public AggregateFactoryHeaderBased(IConstructAggregates factory, params Assembly[] domainAssemblies)
 {
     this.factory          = factory;
     this.domainAssemblies = domainAssemblies;
 }
Example #24
0
 public static IAggregateCommandsHandler <T> New <T>(IConstructAggregates factory = null) where T : CommandAggregate
 {
     return(new ConventionAggregateHandler <T>((T)(factory ?? AggregateFactory.Default).Build(typeof(T), null, null)));
 }
 public InMemoryDomainRepository(IStoreEvents eventStore, IConstructAggregates aggregateFactory, ConflictDetector conflictDetector)
     : base(eventStore, aggregateFactory, conflictDetector)
 {
     this.EventStore = eventStore;
 }
Example #26
0
 public InMemoryEventRepository(IConstructAggregates aggregateFactory)
 {
     _aggregateFactory = aggregateFactory;
     ProducedEvents    = new List <DomainEvent>();
 }
 public AggregateSnapshotRepository(string akkaWriteDbConnectionString, IConstructAggregates aggregatesConstructor)
 {
     _aggregatesConstructor = aggregatesConstructor;
     _writeString           = akkaWriteDbConnectionString;
 }
 public GetEventStoreAdapter(IEventStoreConnection eventStoreConnection, IEventPublisher eventsPublisher, IConstructAggregates constructAggregates)
     : this(eventStoreConnection, eventsPublisher, (t, g) => string.Format("{0}-{1}", char.ToLower(t.Name[0]) + t.Name.Substring(1), g.ToString("N")), constructAggregates)
 {
 }
Example #29
0
 public InMemoryEventRepository(List <IEvent> givenEvents, IConstructAggregates aggregateFactory)
 {
     this.givenEvents      = givenEvents;
     this.aggregateFactory = aggregateFactory;
 }
 public static T BuildEmpty <T>(this IConstructAggregates factory, string id = null) where T : IAggregate
 {
     return((T)factory.Build(typeof(T), id ?? Guid.NewGuid().ToString(), null));
 }
 public static T Build <T>(this IConstructAggregates constructor, string id, IMemento snapshot = null) where T : IAggregate
 {
     return((T)constructor.Build(typeof(T), id, snapshot));
 }