private async Task Tick(CancellationToken cancellationToken) { var eventMapping = new EventMapping(EventMapping.DiscoverEventNamesInAssembly(typeof(ClockHasTicked).Assembly)); var clockStreamId = new StreamId(ClockStreamId); var lastClockHasTicked = await _streamStore.ReadStreamBackwards( streamId : clockStreamId, fromVersionInclusive : StreamVersion.End, maxCount : 1, prefetchJsonData : true, cancellationToken : cancellationToken); if (!lastClockHasTicked.Messages.Any()) { await AppendClockHasTicked(cancellationToken, clockStreamId, eventMapping); } else { var lastClockTickJsonData = await lastClockHasTicked.Messages[0].GetJsonData(cancellationToken); var lastClockTick = JsonConvert.DeserializeObject <ClockHasTicked>(lastClockTickJsonData); if (LocalDate.FromDateTime(lastClockTick.DateTime.Date) != _clockProvider.Today) { await AppendClockHasTicked(cancellationToken, clockStreamId, eventMapping); } } }
public ExampleAggregateCommandHandlerModule( Func <IStreamStore> getStreamStore, Func <ConcurrentUnitOfWork> getUnitOfWork, EventMapping eventMapping, EventSerializer eventSerializer, Func <IExampleAggregates> getExampleAggregates) { For <NameExampleAggregate>() .AddSqlStreamStore(getStreamStore, getUnitOfWork, eventMapping, eventSerializer) .Handle(async(message, ct) => { var exampleAggregates = getExampleAggregates(); var exampleAggregateId = message.Command.ExampleAggregateId; var possibleExampleAggregate = await exampleAggregates.GetOptionalAsync(exampleAggregateId, ct); if (!possibleExampleAggregate.HasValue) { possibleExampleAggregate = new Optional <ExampleAggregate>(ExampleAggregate.Register(exampleAggregateId)); exampleAggregates.Add(exampleAggregateId, possibleExampleAggregate.Value); } var exampleAggregate = possibleExampleAggregate.Value; exampleAggregate.NameExampleAggregate(message.Command.ExampleAggregateName); }); }
public void event_name_for_event_type() { var options = new StoreOptions(); var mapping = new EventMapping <MembersJoined>(new EventGraph(options)); mapping.EventTypeName.ShouldBe("members_joined"); }
protected override Task Context() { _parameterMapper = A.Fake <ParameterMapper>(); _eventMappingFactory = A.Fake <IEventMappingFactory>(); sut = new EventMappingMapper(_parameterMapper, _eventMappingFactory); _event = new PKSimEvent() .WithName("E1") .WithId("EventId"); _eventMapping = new EventMapping { TemplateEventId = _event.Id, StartTime = DomainHelperForSpecs.ConstantParameterWithValue(1) }; _snapshotEventStartTime1 = new Parameter { Name = "P1" }; _project = new PKSimProject(); _project.AddBuildingBlock(_event); A.CallTo(() => _parameterMapper.MapToSnapshot(_eventMapping.StartTime)).Returns(_snapshotEventStartTime1); return(_completed); }
private static async Task <long> AddSqlStreamStore( Func <IStreamStore> getStreamStore, Func <ConcurrentUnitOfWork> getUnitOfWork, EventMapping eventMapping, EventSerializer eventSerializer, CommandMessage message, CancellationToken ct) { var aggregate = getUnitOfWork().GetChanges().SingleOrDefault(); if (aggregate == null) { return(-1L); } if (!message.Metadata.ContainsKey("CommandId")) { message.Metadata.Add("CommandId", message.CommandId); } var i = 1; var result = await getStreamStore().AppendToStream( aggregate.Identifier, aggregate.ExpectedVersion, aggregate.Root.GetChangesWithMetadata() .Select(o => new NewStreamMessage( messageId: Deterministic.Create(Deterministic.Namespaces.Events, $"{message.CommandId}-{i++}"), type: eventMapping.GetEventName(o.Event.GetType()), jsonData: eventSerializer.SerializeObject(o.Event), jsonMetadata: eventSerializer.SerializeObject(GetMetadata(message.Metadata, o.Metadata)))) .ToArray(), ct); return(result.CurrentPosition); }
public PostalInformationCommandHandlerModule( Func <IPostalInformationSet> getPostalInformationSet, Func <ConcurrentUnitOfWork> getUnitOfWork, Func <IStreamStore> getStreamStore, EventMapping eventMapping, EventSerializer eventSerializer, BPostPostalInformationProvenanceFactory bpostProvenanceFactory, CrabPostalInformationProvenanceFactory crabProvenanceFactory) { For <ImportPostalInformationFromBPost>() .AddSqlStreamStore(getStreamStore, getUnitOfWork, eventMapping, eventSerializer) .AddProvenance(getUnitOfWork, bpostProvenanceFactory) .Handle(async(message, ct) => { var postalCode = message.Command.PostalCode; var postalInformationSet = getPostalInformationSet(); var postalInformation = await postalInformationSet.GetOptionalAsync(postalCode, ct); if (!postalInformation.HasValue) { postalInformation = new Optional <PostalInformation>(PostalInformation.Register(postalCode)); postalInformationSet.Add(postalCode, postalInformation.Value); } postalInformation.Value.ImportPostalInformationFromBPost( message.Command.PostalCode, message.Command.PostalNames, message.Command.IsSubMunicipality, message.Command.Province, message.Command.Modification); }); For <ImportPostalInformationFromCrab>() .AddSqlStreamStore(getStreamStore, getUnitOfWork, eventMapping, eventSerializer) .AddProvenance(getUnitOfWork, crabProvenanceFactory) .Handle(async(mesage, ct) => { // need to use the subcanton => in crab postcode = 1030, subcanton = 1031 // in bpost postcode = 1031 var postalCode = new PostalCode(mesage.Command.SubCantonCode); var postalInformation = await getPostalInformationSet().GetOptionalAsync(postalCode, ct); if (!postalInformation.HasValue) // Crab has possible outdated postalcodes { return; } postalInformation.Value.ImportPostalInformationFromCrab( mesage.Command.PostalCode, mesage.Command.SubCantonId, mesage.Command.SubCantonCode, mesage.Command.NisCode, mesage.Command.MunicipalityName, mesage.Command.Lifetime, mesage.Command.Timestamp, mesage.Command.Operator, mesage.Command.Modification, mesage.Command.Organisation); }); }
public IdempotentCommandHandlerModuleProcessor( Func <IAddresses> getAddresses, ConcurrentUnitOfWork concurrentUnitOfWork, IPersistentLocalIdGenerator persistentLocalIdGenerator, Func <IStreamStore> getStreamStore, EventMapping eventMapping, EventSerializer eventSerializer, AddressProvenanceFactory addressProvenanceFactory, CrabAddressProvenanceFactory crabProvenanceFactory, AddressPersistentLocalIdentifierProvenanceFactory addressPersistentLocalIdentifierProvenanceFactory) { _getAddresses = getAddresses; _concurrentUnitOfWork = concurrentUnitOfWork; _provenanceFactory = crabProvenanceFactory.CreateFrom; _addressPersistentLocalIdProvenanceFactory = addressPersistentLocalIdentifierProvenanceFactory.CreateFrom; _addressCommandHandlerModule = new AddressCommandHandlerModule( _getAddresses, () => concurrentUnitOfWork, persistentLocalIdGenerator, getStreamStore, eventMapping, eventSerializer, addressProvenanceFactory, crabProvenanceFactory, addressPersistentLocalIdentifierProvenanceFactory); }
private static void PublishToConsumer <T>(IConsumer <T> x, T eventMessage) where T : IEventMessage { if (x is DummyConsumer <T> ) { return; } if (x is ESBConsumer <T> ) { EventMapping.AddEvent <T>(eventMessage.Subject); } if (x.ExecuteMode == ExecuteMode.Sync || (x.ExecuteMode == ExecuteMode.AccordingToTransaction && Transaction.Current != null)) // 同步执行 { x.HandleEvent(eventMessage); } else // 异步执行 { Action <T> act = new Action <T>(x.HandleEvent); act.BeginInvoke(eventMessage, ar => { Action <T> tmp = ar.AsyncState as Action <T>; if (tmp != null) { tmp.EndInvoke(ar); } }, act); } }
public DomainCommandHandlerModule( Func <IStreamStore> getStreamStore, Func <ConcurrentUnitOfWork> getUnitOfWork, EventMapping eventMapping, EventSerializer eventSerializer, Func <IDomains> getDomains) { For <CreateDomain>() .AddSqlStreamStore(getStreamStore, getUnitOfWork, eventMapping, eventSerializer) .Handle(async(message, ct) => { var domains = getDomains(); var domainName = message.Command.DomainName; var domain = Domain.Register(domainName); domains.Add(domainName, domain); }); For <AddManual>() .AddSqlStreamStore(getStreamStore, getUnitOfWork, eventMapping, eventSerializer) .Handle(async(message, ct) => { var domains = getDomains(); var domainName = message.Command.DomainName; var domain = await domains.GetAsync(domainName, ct); domain.AddManual( message.Command.ServiceId, message.Command.Label, message.Command.Records); }); For <AddGoogleSuite>() .AddSqlStreamStore(getStreamStore, getUnitOfWork, eventMapping, eventSerializer) .Handle(async(message, ct) => { var domains = getDomains(); var domainName = message.Command.DomainName; var domain = await domains.GetAsync(domainName, ct); domain.AddGoogleSuite( message.Command.ServiceId, message.Command.VerificationToken); }); For <RemoveService>() .AddSqlStreamStore(getStreamStore, getUnitOfWork, eventMapping, eventSerializer) .Handle(async(message, ct) => { var domains = getDomains(); var domainName = message.Command.DomainName; var domain = await domains.GetAsync(domainName, ct); domain.RemoveService(message.Command.ServiceId); }); }
public RoadNetworkChangesArchives(EventSourcedEntityMap map, IStreamStore store, JsonSerializerSettings settings, EventMapping mapping) { _map = map ?? throw new ArgumentNullException(nameof(map)); _store = store ?? throw new ArgumentNullException(nameof(store)); _settings = settings ?? throw new ArgumentNullException(nameof(settings)); _mapping = mapping ?? throw new ArgumentNullException(nameof(mapping)); }
public void SetUp() { _model = new Model(); var eventDeserializer = new EventDeserializer(SimpleJson.DeserializeObject); var eventSerializer = new EventSerializer(SimpleJson.SerializeObject); var eventMapping = new EventMapping(new Dictionary <string, Type> { { typeof(SnapshotStub).AssemblyQualifiedName, typeof(SnapshotStub) }, { typeof(EventStub).AssemblyQualifiedName, typeof(EventStub) }, }); var snapshotContainer = new SnapshotContainer { Info = { Position = 4, Type = typeof(SnapshotStub).AssemblyQualifiedName }, Data = eventSerializer.SerializeObject(new SnapshotStub(1)) }; _sut = new RepositoryScenarioBuilder(eventMapping, eventDeserializer) .ScheduleAppendToStream(_model.KnownIdentifier, new EventStub(0)) .ScheduleAppendToStream(_model.KnownIdentifier, new EventStub(1)) .ScheduleAppendToStream(_model.KnownIdentifier, new EventStub(2)) .ScheduleAppendToStream(_model.KnownIdentifier, new EventStub(3)) .ScheduleAppendToStream(_model.KnownIdentifier, new EventStub(4)) .ScheduleAppendToStream($"{_model.KnownIdentifier}-snapshots", snapshotContainer) .ScheduleAppendToStream(_model.KnownIdentifier, new EventStub(5)) .ScheduleAppendToStream(_model.KnownIdentifier, new EventStub(6)) .BuildForRepository <AggregateRootEntitySnapshotableStub>(); }
private Func <TestMessage, Task <AppendResult> > CreateMessageStorerAndStartHandling(ConnectedProjection <TestDbContext> projection) { var eventMapping = new EventMapping(EventMapping.DiscoverEventNamesInAssembly(typeof(RunnerTests).Assembly)); var testRunner = new TestRunner( new EnvelopeFactory( eventMapping, new EventDeserializer(JsonConvert.DeserializeObject)), new Logger <TestRunner>(new LoggerFactory()), projection); var options = new DbContextOptionsBuilder <TestDbContext>() .UseInMemoryDatabase("testing") .Options; using (var testDbContext = new TestDbContext(options)) { testDbContext.Database.EnsureDeleted(); } var inMemoryStreamStore = new InMemoryStreamStore(() => DateTime.UtcNow); testRunner.Handle( inMemoryStreamStore, () => new Owned <TestDbContext>(new TestDbContext(options), this)); return(async message => await inMemoryStreamStore.AppendToStream(new StreamId("Bla"), ExpectedVersion.Any, new NewStreamMessage(Guid.NewGuid(), eventMapping.GetEventName(typeof(TestMessage)), JsonConvert.SerializeObject(message)))); }
public IdempotentCommandHandlerModuleProcessor( Func <IParcels> getParcels, IParcelFactory parcelFactory, ConcurrentUnitOfWork concurrentUnitOfWork, Func <IStreamStore> getStreamStore, EventMapping eventMapping, EventSerializer eventSerializer, ParcelProvenanceFactory provenanceFactory) { _getParcels = getParcels; _parcelFactory = parcelFactory; _concurrentUnitOfWork = concurrentUnitOfWork; _provenanceFactory = provenanceFactory.CreateFrom; var fixGrar1475ProvenanceFactory = new FixGrar1475ProvenanceFactory(); _fixGrar1475ProvenanceFactory = fixGrar1475ProvenanceFactory.CreateFrom; var fixGrar1637ProvenanceFactory = new FixGrar1637ProvenanceFactory(); _fixGrar1637ProvenanceFactory = fixGrar1637ProvenanceFactory.CreateFrom; _parcelCommandHandlerModule = new ParcelCommandHandlerModule( getParcels, parcelFactory, () => concurrentUnitOfWork, getStreamStore, eventMapping, eventSerializer, provenanceFactory, fixGrar1475ProvenanceFactory, fixGrar1637ProvenanceFactory); }
public AccountCommandHandlerModule( Func <IStreamStore> getStreamStore, Func <ConcurrentUnitOfWork> getUnitOfWork, EventMapping eventMapping, EventSerializer eventSerializer, Func <IAccounts> getAccounts) { For <NameAccount>() .AddSqlStreamStore(getStreamStore, getUnitOfWork, eventMapping, eventSerializer) .Handle(async(message, ct) => { var accounts = getAccounts(); var accountId = message.Command.AccountId; var possibleAccount = await accounts.GetOptionalAsync(accountId, ct); if (!possibleAccount.HasValue) { possibleAccount = new Optional <Account>(Account.Register(accountId)); accounts.Add(accountId, possibleAccount.Value); } var account = possibleAccount.Value; account.NameAccount(message.Command.AccountName); }); }
public void ConfigureServices(IServiceCollection services) { PrometheusMetrics.TryConfigure(Environment.ApplicationName); EventMapping.Map(); var esConnection = ConfigureEsConnection( Configuration["EventStore:ConnectionString"], Environment.ApplicationName); var documentStore = ConfigureRavenDb( Configuration["RavenDb:Server"], Configuration["RavenDb:Database"] ); var ravenDbStore = new RavenDBProvider(documentStore); services.AddSingleton(c => (Func <IAsyncDocumentSession>)GetSession); services.AddSingleton <IHostedService>( new EventStoreService( esConnection, Props.FromProducer(() => new SubscriptionActor( esConnection, new RavenDbCheckpointStore(GetSession, "readmodels"), "ravenDbSubscription", (Props.FromProducer( () => new CustomerVehiclesProjection(ravenDbStore)), "customerVehicles"), (Props.FromProducer( () => new VehicleItemProjection(ravenDbStore)), "vehicleItems") ) ) ) ); IAsyncDocumentSession GetSession() => documentStore.OpenAsyncSession(); }
public void CreateDependencies() { var store = new InMemoryStreamStore(); var eventMapping = new EventMapping(new Dictionary <string, Type> { { "SomethingHappened", typeof(SomethingHappened) }, { "SomethingElseHappened", typeof(SomethingElseHappened) }, }); var eventSerializer = new EventSerializer(JsonConvert.SerializeObject); var eventDeserializer = new EventDeserializer(JsonConvert.DeserializeObject); _factRepository = new StreamStoreFactRepository(store, eventMapping, eventSerializer, eventDeserializer); _handlerFactory = (eventType, @events) => async(command) => { long position = 0; foreach (var @event in events) { position = (await store.AppendToStream( (command as DoSomething).Identifier, ExpectedVersion.Any, new NewStreamMessage(Guid.NewGuid(), eventType, eventSerializer.SerializeObject(@event)), CancellationToken.None) ).CurrentPosition; } return(position); }; _handlerResolver = new Mocking <IHandlerResolver, HandlerResolverSetup>(); //_handlerResolver.When().ResolvesHandler(_handlerFactory); }
public void SqlServerEventStore_RetrieveEvents_PlainEvent_Should_Work() { var eventStore = new SqlServerEventStore(this.Settings, this.EventDispatcher); var aggId = Guid.NewGuid(); var events = new[] { new PlainEvent(aggId, PlainEvent.TestEnum.Nope), new PlainEvent(aggId, null), new PlainEvent(Guid.NewGuid(), null), new PlainEvent(aggId, PlainEvent.TestEnum.Ok), }; var eventsCount = events.Count(e => e.MyAggId == aggId); foreach (var @event in events) { eventStore.Save(@event); } var eventMapping = new EventMapping { AggregateIdPropertyName = nameof(PlainEvent.MyAggId), EventType = typeof(PlainEvent) }; var eventDescriptors = new[] { eventMapping }; var savedEvents = eventStore.RetrieveEvents(aggId, DateTime.Now, eventDescriptors, timelineId: null); Assert.NotNull(savedEvents); Assert.NotEmpty(savedEvents); Assert.True(savedEvents.All(e => e is PlainEvent)); Assert.Equal(eventsCount, savedEvents.Count()); }
private static async Task <long> AddSqlStreamStore( Func <IStreamStore> getStreamStore, Func <ConcurrentUnitOfWork> getUnitOfWork, EventMapping eventMapping, EventSerializer eventSerializer, CommandMessage message, CancellationToken ct) { var uow = getUnitOfWork(); var aggregate = uow.GetChanges().SingleOrDefault(); if (aggregate == null) { return(-1L); } var streamStore = getStreamStore(); if (!message.Metadata.ContainsKey("CommandId")) { message.Metadata.Add("CommandId", message.CommandId); } var i = 1; var events = aggregate.Root.GetChangesWithMetadata().ToImmutableList(); var changes = events .Select(o => new NewStreamMessage( messageId: Deterministic.Create(Deterministic.Namespaces.Events, $"{message.CommandId}-{i++}"), type: eventMapping.GetEventName(o.Event.GetType()), jsonData: eventSerializer.SerializeObject(o.Event), jsonMetadata: eventSerializer.SerializeObject(GetMetadata(message.Metadata, o.Metadata)))) .ToArray(); var result = await streamStore.AppendToStream( aggregate.Identifier, aggregate.ExpectedVersion, changes, ct); if (aggregate.Root is ISnapshotable support) { await CreateSnapshot( support, new SnapshotStrategyContext( aggregate, events, result.CurrentPosition), streamStore, uow, eventMapping, eventSerializer, ct); } return(result.CurrentPosition); // Position of the last event written }
public void SetUp() { var eventDeserializer = new EventDeserializer(SimpleJson.DeserializeObject); var eventMapping = new EventMapping(new Dictionary <string, Type>()); _model = new Model(); _sut = new RepositoryScenarioBuilder(eventMapping, eventDeserializer).BuildForRepository(); }
private void PhaseChangedSlot(object[] parameters) { DraggableItem item = (DraggableItem)parameters[0]; EventMapping mapping = (EventMapping)item.Data; //Debug.Log(string.Format("PhaseChangedSlot: {0}", mapping)); EventMappingDescriptor.ProcessPhases(Adapter, null, mapping, mapping.Enabled); }
public ScenarioRunner(CommandHandlerResolver resolver, IStreamStore store, JsonSerializerSettings settings, EventMapping mapping, StreamNameConverter converter) { _resolver = resolver ?? throw new ArgumentNullException(nameof(resolver)); _store = store ?? throw new ArgumentNullException(nameof(store)); _settings = settings ?? throw new ArgumentNullException(nameof(settings)); _mapping = mapping ?? throw new ArgumentNullException(nameof(mapping)); _converter = converter ?? throw new ArgumentNullException(nameof(converter)); }
public void SetUp() { _store = new InMemoryStreamStore(() => DateTime.UtcNow); _unitOfWork = new ConcurrentUnitOfWork(); _factory = AggregateRootEntityStub.Factory; _eventDeserializer = new EventDeserializer(SimpleJson.DeserializeObject); _eventMapping = new EventMapping(new Dictionary <string, Type>()); }
public Repository( Func <TAggregateRoot> factory, ConcurrentUnitOfWork unitOfWork, IStreamStore eventStore, EventMapping eventMapping, EventDeserializer eventDeserializer) : base(factory, unitOfWork, eventStore, eventMapping, eventDeserializer) { }
public RepositoryScenarioBuilder(EventMapping eventMapping, EventDeserializer eventDeserializer) { _eventStore = new InMemoryStreamStore(() => DateTime.UtcNow); _unitOfWork = new ConcurrentUnitOfWork(); _eventStoreSchedule = new List <Action <IStreamStore> >(); _unitOfWorkSchedule = new List <Action <ConcurrentUnitOfWork> >(); _eventMapping = eventMapping; _eventDeserializer = eventDeserializer; }
public RoadNetworks(EventSourcedEntityMap map, IStreamStore store, IRoadNetworkSnapshotReader snapshotReader, JsonSerializerSettings settings, EventMapping mapping) { _map = map ?? throw new ArgumentNullException(nameof(map)); _store = store ?? throw new ArgumentNullException(nameof(store)); _settings = settings ?? throw new ArgumentNullException(nameof(settings)); _mapping = mapping ?? throw new ArgumentNullException(nameof(mapping)); _snapshotReader = snapshotReader ?? throw new ArgumentNullException(nameof(snapshotReader)); }
public StreamStoreFactRepository( IStreamStore streamStore, EventMapping eventMapping, EventSerializer eventSerializer, EventDeserializer eventDeserializer) { _streamStore = streamStore ?? throw new ArgumentNullException(nameof(streamStore)); _eventMapping = eventMapping ?? throw new ArgumentNullException(nameof(eventMapping)); _eventSerializer = eventSerializer ?? throw new ArgumentNullException(nameof(eventSerializer)); _eventDeserializer = eventDeserializer ?? throw new ArgumentNullException(nameof(eventDeserializer)); }
public void SetUp() { var eventDeserializer = new EventDeserializer(SimpleJson.DeserializeObject); var eventMapping = new EventMapping(new Dictionary <string, Type>()); _model = new Model(); _sut = new RepositoryScenarioBuilder(eventMapping, eventDeserializer). ScheduleAppendToStream(_model.KnownIdentifier, new EventStub(1)). ScheduleDeleteStream(_model.KnownIdentifier). BuildForRepository(); }
//Return Event Defintions using Contract as an indentifier to traverse the Event mapping. public HashSet <EventDefinition> retrieveEventDefinitionsUsingContract(ContractDefinition contract) { if (EventMapping.ContainsKey(contract)) { return(EventMapping[contract]); } else { return(new HashSet <EventDefinition>()); } }
public void SetUp() { var eventDeserializer = new EventDeserializer(SimpleJson.DeserializeObject); var eventMapping = new EventMapping(new Dictionary <string, Type>()); _model = new Model(); _root = AggregateRootEntityStub.Factory(); _sut = new RepositoryScenarioBuilder(eventMapping, eventDeserializer). ScheduleAttachToUnitOfWork(new Aggregate(_model.KnownIdentifier, 0, _root)). BuildForRepository(); }
public StreamStoreCommandHandlerModule( Func <IStreamStore> getStreamStore, Func <ConcurrentUnitOfWork> getUnitOfWork, Func <ReturnHandler <CommandMessage>, T> innerModuleFactory, EventMapping eventMapping, EventSerializer eventSerializer) { _eventMapping = eventMapping; _eventSerializer = eventSerializer; Wrap(innerModuleFactory((message, ct) => ToStreamStore(getStreamStore, getUnitOfWork, message, ct))); }