public virtual async Task <IReadOnlyCollection <IDomainEvent <TAggregate, TIdentity> > > StoreAsync <TAggregate, TIdentity>( TIdentity id, IReadOnlyCollection <IUncommittedEvent> uncommittedDomainEvents, ISourceId sourceId, CancellationToken cancellationToken) where TAggregate : IAggregateRoot <TIdentity> where TIdentity : IIdentity { if (id == null) { throw new ArgumentNullException(nameof(id)); } if (sourceId.IsNone()) { throw new ArgumentNullException(nameof(sourceId)); } if (uncommittedDomainEvents == null || !uncommittedDomainEvents.Any()) { return(new IDomainEvent <TAggregate, TIdentity>[] {}); } var aggregateType = typeof(TAggregate); _log.Verbose( "Storing {0} events for aggregate '{1}' with ID '{2}'", uncommittedDomainEvents.Count, aggregateType.Name, id); var batchId = Guid.NewGuid().ToString(); var storeMetadata = new[] { new KeyValuePair <string, string>(MetadataKeys.BatchId, batchId), new KeyValuePair <string, string>(MetadataKeys.SourceId, sourceId.Value) }; var serializedEvents = uncommittedDomainEvents .Select(e => { var md = _metadataProviders .SelectMany(p => p.ProvideMetadata <TAggregate, TIdentity>(id, e.AggregateEvent, e.Metadata)) .Concat(e.Metadata) .Concat(storeMetadata); return(_eventJsonSerializer.Serialize(e.AggregateEvent, md)); }) .ToList(); var committedDomainEvents = await _eventPersistence.CommitEventsAsync( id, serializedEvents, cancellationToken) .ConfigureAwait(false); var domainEvents = committedDomainEvents .Select(e => _eventJsonSerializer.Deserialize <TAggregate, TIdentity>(id, e)) .ToList(); return(domainEvents); }
public async Task StartAsync(CancellationToken cancellationToken) { var connection = await _rabbitMqConnectionFactory.CreateConnectionAsync(_rabbitMqConfiguration.Uri, cancellationToken); await connection.WithModelAsync(model => { model.ExchangeDeclare(_rabbitMqConfiguration.Exchange, ExchangeType.Fanout); model.QueueDeclare(_environmentConfiguration.RabbitQueueName, false, false, true, null); model.QueueBind(_environmentConfiguration.RabbitQueueName, _rabbitMqConfiguration.Exchange, ""); var consume = new EventingBasicConsumer(model); consume.Received += (obj, @event) => { var msg = CreateRabbitMqMessage(@event); var domainEvent = _eventJsonSerializer.Deserialize(msg.Message, new Metadata(msg.Headers)); _dispatchToEventSubscribers.DispatchToAsynchronousSubscribersAsync(domainEvent, cancellationToken); }; model.BasicConsume(_environmentConfiguration.RabbitQueueName, false, consume); return(Task.CompletedTask); }, cancellationToken); }
public async Task <IActionResult> OnPostExportEventsFromFilesStoreToCsv() { if ((_eventPersistence is FilesEventPersistence) == false) { throw new ApplicationException($"{nameof(FilesEventPersistence)} not configured"); } var events = await _eventPersistence.LoadAllCommittedEvents(GlobalPosition.Start, 1000, CancellationToken.None); var result = events.CommittedDomainEvents .Cast <FilesEventPersistence.FileEventData>() .Select(x => new { Source = x, Deserialized = _eventJsonSerializer.Deserialize(x) }) .Select(x => new EventFlow.SQLite.EventStores.SQLiteEventPersistence.EventDataModel() { GlobalSequenceNumber = x.Source.GlobalSequenceNumber, BatchId = Guid.Parse(x.Deserialized.Metadata["batch_id"]), AggregateId = x.Source.AggregateId, AggregateName = x.Deserialized.Metadata["aggregate_name"], Data = x.Source.Data, Metadata = x.Source.Metadata, AggregateSequenceNumber = x.Source.AggregateSequenceNumber }); using (var stream = new System.IO.MemoryStream()) using (var writer = new System.IO.StreamWriter(stream)) using (var csv = new CsvHelper.CsvWriter(writer, new CsvHelper.Configuration.CsvConfiguration(System.Globalization.CultureInfo.CurrentUICulture))) { csv.WriteRecords(result); csv.Flush(); writer.Flush(); return(File(stream.ToArray(), "text/csv", "events.csv")); } }
public IDomainEvent CreateDomainEvent(RabbitMqMessage rabbitMqMessage) { var metadata = new Metadata(rabbitMqMessage.Headers); var domainEvent = _eventJsonSerializer.Deserialize( rabbitMqMessage.Message, metadata); _log.Verbose("Create Domain event {0}", domainEvent); return(domainEvent); }
public async Task <IReadOnlyCollection <IDomainEvent> > CommitAsync( IEventJsonSerializer _eventJsonSerializer, ISourceId sourceId, CancellationToken cancellationToken) { if (!_exists) { await Persistence.Save(this, CancellationToken.None); } else { await Persistence.Update(this, CancellationToken.None); } await Persistence.Dispose(cancellationToken); if (_occuredEvents.HasItems()) { var domainEvents = _occuredEvents .Select(e => { return(_eventJsonSerializer.Serialize(e.AggregateEvent, e.Metadata)); }) .Select((e, i) => { var committedDomainEvent = new CommittedDomainEvent { AggregateId = Id.Value, AggregateName = e.Metadata[MetadataKeys.AggregateName], AggregateSequenceNumber = e.AggregateSequenceNumber, Data = e.SerializedData, Metadata = e.SerializedMetadata, GlobalSequenceNumber = i + 1, }; return(committedDomainEvent); }) .Select(e => _eventJsonSerializer.Deserialize <TAggregate, TIdentity>(Id, e)) .ToList(); _occuredEvents.Clear(); return(domainEvents); } else { _occuredEvents.Clear(); return(new IDomainEvent <TAggregate, TIdentity>[] { }); } }
public async Task SubscribeAsync(string exchange, string queue, Action <IList <IDomainEvent>, IDomainEventPublisher> action, IDomainEventPublisher domainEventPublisher, CancellationToken cancellationToken) { Uri uri = _configuration.Uri; IRabbitConnection rabbitConnection = null; try { rabbitConnection = await GetRabbitMqConnectionAsync(uri, cancellationToken).ConfigureAwait(false); await rabbitConnection.WithModelAsync(model => { model.ExchangeDeclare(exchange, ExchangeType.Fanout); model.QueueDeclare(queue, false, false, true, null); model.QueueBind(queue, exchange, ""); var consume = new EventingBasicConsumer(model); consume.Received += (obj, @event) => { var msg = CreateRabbitMqMessage(@event); var domainEvent = _eventJsonSerializer.Deserialize(msg.Message, new Metadata(msg.Headers)); _dispatchToEventSubscribers.DispatchToAsynchronousSubscribersAsync(domainEvent, cancellationToken); }; model.BasicConsume(queue, false, consume); return(Task.CompletedTask); }, cancellationToken); } catch (OperationCanceledException) { throw; } catch (Exception e) { if (rabbitConnection != null) { using (await _asyncLock.WaitAsync(CancellationToken.None).ConfigureAwait(false)) { rabbitConnection.Dispose(); _connections.Remove(uri); } } _log.Error(e, "Failed to subscribe to RabbitMQ"); throw; } }