public void Append(T entity, DomainEvent <TId> @event) { using (var stream = eventStore.CreateStream(@event.AggregateId.ToString())) { stream.Add(new EventMessage { Body = @event }); stream.CommitChanges(@event.EventId); } this.projectionDb.Add(entity); }
private void CreateItem(string itemId, string sku) { using (var stream = _store.CreateStream(_inventoryBucket, itemId)) { stream.Add(new EventMessage() { Headers = new Dictionary <string, object>() { { "secret", "value" } }, Body = new ItemCreatedEvent() { Id = itemId } }); stream.Add(new EventMessage() { Body = new ItemSKUChanged() { SKU = sku } }); FillDiagnosticHeaders(stream.UncommittedHeaders); stream.CommitChanges(commitId: Guid.NewGuid()); } }
private IEventStream PrepareStream(string bucketId, IAggregate aggregate, Dictionary <string, object> headers) { IEventStream stream; var streamId = bucketId + "+" + aggregate.Id; if (!_streams.TryGetValue(streamId, out stream)) { _streams[streamId] = stream = _eventStore.CreateStream(bucketId, aggregate.Id); } foreach (var item in headers) { stream.UncommittedHeaders[item.Key] = item.Value; } aggregate.GetUncommittedEvents() .Cast <object>() .Where(x => x != null) // Don't persist any null events. .Select(x => new EventMessage { Body = x }) .ToList() .ForEach(stream.Add); return(stream); }
protected override void AggregateRootEventAppliedHandler(AggregateRoot aggregateRoot, UncommittedEvent evnt) { var message = new EventMessage { Body = new StoredEvent { Body = evnt.Payload, CommitId = _commitId, EventId = evnt.EventIdentifier, MajorVersion = evnt.EventVersion.Major, MinorVersion = evnt.EventVersion.Minor, Sequence = evnt.EventSequence, TimeStamp = evnt.EventTimeStamp } }; IEventStream stream; var id = aggregateRoot.EventSourceId; if (!_trackedStreams.TryGetValue(id, out stream)) { stream = _eventStore.CreateStream(id); _trackedStreams[id] = stream; } stream.Add(message); _eventStream.Append(evnt); _dirtyInstances.Add(aggregateRoot); }
IEventStream OpenStream(string sagaId) { IEventStream stream; if (_streams.TryGetValue(sagaId, out stream)) { return(stream); } try { stream = _eventStore.OpenStream(sagaId, 0, int.MaxValue); } catch (StreamNotFoundException) { stream = _eventStore.CreateStream(sagaId); } return(_streams[sagaId] = stream); }
protected void CreateStreamAndAppendEvents(Guid streamId, List <T> events) { using (var stream = Store.CreateStream(streamId)) { events.ForEach(@event => stream.Add(new EventMessage { Body = @event })); stream.CommitChanges(Guid.NewGuid()); } }
private IEventStream OpenStream(string bucketId, string sagaId) { IEventStream stream; var sagaKey = bucketId + "+" + sagaId; if (_streams.TryGetValue(sagaKey, out stream)) { return(stream); } try { stream = _eventStore.OpenStream(bucketId, sagaId, 0, int.MaxValue); } catch (StreamNotFoundException) { stream = _eventStore.CreateStream(bucketId, sagaId); } return(_streams[sagaKey] = stream); }
private Task PopulateMaster() { IEventStream stream = _master.CreateStream("tweets"); IEnumerable <Task> tasks = ReadTweets().Select(tweet => { var message = new TweetMessage(tweet); stream.Add(new EventMessage { Body = message }); return(stream.CommitChanges(Guid.NewGuid())); }); return(Task.WhenAll(tasks)); }
public async Task When_new_commit_then_should_dispatch() { using (IStoreEvents eventStore = Wireup.Init().UsingInMemoryPersistence().Build()) { var dispatchedEvents = new List <EventMessage <TestEvent> >(); var handlerModule = new TestHandlerModule(dispatchedEvents); using (var host = new DurableCommitDispatcher( new EventStoreClient(eventStore.Advanced), new InMemoryCheckpointRepository(), new HandlerResolver(handlerModule))) { var projectedCommits = host .ProjectedCommits .Replay(); using (projectedCommits.Connect()) { await host.Start(); var streamId = Guid.NewGuid().ToString().FormatStreamIdWithBucket(); Guid commitId = Guid.NewGuid(); Task <ICommit> commitProjected = projectedCommits .Take(1) .ToTask(); using (IEventStream stream = eventStore.CreateStream(streamId)) { stream.Add(new global::NEventStore.EventMessage { Body = new TestEvent() }); stream.CommitChanges(commitId); } host.PollNow(); await commitProjected; dispatchedEvents.Count.Should().Be(1); dispatchedEvents[0].Commit().Should().NotBeNull(); dispatchedEvents[0].Headers.Should().NotBeNull(); dispatchedEvents[0].Version.Should().Be(1); dispatchedEvents[0].DomainEvent.Should().BeOfType <TestEvent>(); } } } }
private IEventStream PrepareStream(string bucketId, IAggregate aggregate, Dictionary <string, object> headers) { IEventStream stream = _eventStore.CreateStream(bucketId, aggregate.Id); foreach (var item in headers) { stream.UncommittedHeaders[item.Key] = item.Value; } aggregate.GetUncommittedEvents() .Cast <object>() .Select(x => new EventMessage { Body = x }) .ToList() .ForEach(stream.Add); return(stream); }
public async Task When_handler_throws_Then_invoke_exception_callback() { using (IStoreEvents eventStore = Wireup.Init().UsingInMemoryPersistence().Build()) { var projectedEvents = new List <EventMessage <TestEvent> >(); var handlerModule = new TestHandlerModule(projectedEvents); using (var host = new DurableCommitDispatcher( new EventStoreClient(eventStore.Advanced), new InMemoryCheckpointRepository(), new HandlerResolver(handlerModule))) { var projectedCommits = host .ProjectedCommits .Replay(); using (projectedCommits.Connect()) { await host.Start(); var streamId = Guid.NewGuid().ToString().FormatStreamIdWithBucket(); Guid commitId = Guid.NewGuid(); Task <ICommit> commitProjected = projectedCommits .Take(1) .ToTask(); using (IEventStream stream = eventStore.CreateStream(streamId)) { stream.Add(new global::NEventStore.EventMessage { Body = new TestEventThatThrows() }); stream.CommitChanges(commitId); } host.PollNow(); Func <Task> act = async() => await commitProjected; act.ShouldThrow <Exception>(); } } } }
// private readonly Dictionary<Guid, List<EventDescriptor>> _current = new Dictionary<Guid, List<EventDescriptor>>(); public void SaveEvents(Guid aggregateId, IEnumerable <Event> events, int expectedVersion) { //List<EventDescriptor> eventDescriptors; //// try to get event descriptors list for given aggregate id //// otherwise -> create empty dictionary //if (!_current.TryGetValue(aggregateId, out eventDescriptors)) //{ // eventDescriptors = new List<EventDescriptor>(); // _current.Add(aggregateId, eventDescriptors); //} //// check whether latest event version matches current aggregate version //// otherwise -> throw exception //else if (eventDescriptors[eventDescriptors.Count - 1].Version != expectedVersion && expectedVersion != -1) //{ // throw new ConcurrencyException(); //} using (var stream = expectedVersion <= 0 ? _store.CreateStream(aggregateId) : _store.OpenStream(aggregateId, expectedVersion)) { if (stream.StreamRevision != expectedVersion && expectedVersion != -1) { throw new ConcurrencyException(); } var i = stream.StreamRevision; // iterate through current aggregate events increasing version with each processed event foreach (var @event in events) { i++; @event.Version = i; // push event to the event descriptors list for current aggregate //eventDescriptors.Add(new EventDescriptor(aggregateId, @event, i)); stream.Add(new EventMessage { Body = @event }); // publish current event to the bus for further processing by subscribers _publisher.Publish(@event); } stream.CommitChanges(Guid.NewGuid()); } }
public void ReadSetup() { _eventStore.Advanced.Purge(); using (var stream = _eventStore.CreateStream(StreamId)) { // add XXX commits to the stream for (int i = 0; i < CommitsToWrite; i++) { var @event = new SomeDomainEvent { Value = i.ToString() }; stream.Add(new EventMessage { Body = @event }); stream.CommitChanges(Guid.NewGuid()); } } }
public void Add(Concert concert) { lock (_object) { var bucketId = GetBucketId(concert.Id); using (var eventStream = _eventStore.CreateStream(bucketId, concert.Id.ToString())) { foreach (var @event in concert.Changes) { eventStream.Add(new EventMessage() { Body = @event }); } eventStream.CommitChanges(Guid.NewGuid()); } } }
private IEventStream PrepareStream(IStoreEvents eventStore, IAggregateRoot aggregate, Dictionary <string, object> headers, IEnumerable <IDomainEvent> uncommitedEvents) { IEventStream stream; if (!_streams.TryGetValue(aggregate.Key, out stream)) { _streams[aggregate.Key] = stream = eventStore.CreateStream(aggregate.Key); } foreach (var item in headers) { stream.UncommittedHeaders[item.Key] = item.Value; } uncommitedEvents .Cast <object> () .Select(x => new EventMessage { Body = x }) .ToList() .ForEach(stream.Add); return(stream); }
public async Task <string> CreateAsync(string userId, CreateGameModel model) { string userHeroId = string.Empty; string opponentHeroId = string.Empty; Task userTask = _userRepository.GetByIdAsync(userId).ContinueWith(r => { User result = r.Result; if (result?.Heroes != null && result.Heroes.Count > 0) { userHeroId = result.Heroes[0].Id; } }); Task opponentTask = string.IsNullOrEmpty(model.OpponentId) ? Task.FromResult(true) : _userRepository.GetByIdAsync(model.OpponentId).ContinueWith(r => { User result = r.Result; if (result?.Heroes != null && result.Heroes.Count > 0) { opponentHeroId = result.Heroes[0].Id; } }); await Task.WhenAll(userTask, opponentTask); if (string.IsNullOrEmpty(userHeroId) || (!string.IsNullOrEmpty(model.OpponentId) && string.IsNullOrEmpty(opponentHeroId))) { throw new KeyNotFoundException("Hero not found"); } var gameId = Guid.NewGuid(); GameModel gameModel = new GameModel { Id = gameId.ToString(), CreatedBy = userId, UserHeroId = userHeroId, OpponentId = model.OpponentId, OpponentHeroId = opponentHeroId, Status = GameStatus.Requesting, CreatedAt = DateTime.UtcNow, Position = new PositionModel { Lat = model.Lat, Lng = model.Lng }, OpponentExtInfo = model.OpponentExtInfo, SelfPlaying = model.SelfPlaying, Speed = model.Speed, Difficulty = model.Difficulty, UserArmySetting = model.UserArmySetting }; GameModel game = gameModel; using (IEventStream stream = _store.CreateStream(new Guid(game.Id))) { var initEvent = new InitGameEvent { UserId = userId, UserHeroId = userHeroId, OpponentId = model.OpponentId, OpponentHeroId = opponentHeroId, SelfPlaying = model.SelfPlaying, Speed = model.Speed, Difficulty = model.Difficulty, UserArmySetting = Mapper.Map <GameArmySetting>(model.UserArmySetting), UserTroopTypes = Mapper.Map <List <CastleTroopType> >(await GetRandomTroopTypes()), OpponentTroopTypes = Mapper.Map <List <CastleTroopType> >(await GetRandomTroopTypes()), }; initEvent.UserProducedTroopTypes = new List <string>() { initEvent.UserTroopTypes .First(e => e.UpkeepCoins == initEvent.UserTroopTypes.Min(f => f.UpkeepCoins)) .ResourceType }; initEvent.OpponentProducedTroopTypes = new List <string>() { initEvent.OpponentTroopTypes .First(e => e.UpkeepCoins == initEvent.OpponentTroopTypes.Min(f => f.UpkeepCoins)) .ResourceType }; stream.Add(new EventMessage { Body = initEvent }); stream.Add(new EventMessage { Body = new ChangeGameStatusEvent { Status = GameStatus.Requesting } }); stream.CommitChanges(Guid.NewGuid()); } await Repository.AddAsync(Mapper.Map <Game>(game)); _domain.Build(gameId, InitGameSnapshot); return(game.Id); }
/// <summary> /// Creates a new stream. /// </summary> /// <param name="storeEvents">The store events instance.</param> /// <param name="streamId">The value which uniquely identifies the stream to be created.</param> /// <returns>An empty stream.</returns> public static Task <IEventStream> CreateStream(this IStoreEvents storeEvents, string streamId) { EnsureStoreEventsNotNull(storeEvents); return(storeEvents.CreateStream(Bucket.Default, streamId)); }
private IEventStream CreateStream(Command cmd) { return(cmd.IsFirstCommand ? store.CreateStream(cmd.CommandId) : store.OpenStream(cmd.CommandId)); }
/// <summary> /// Creates a new stream. /// </summary> /// <param name="storeEvents">The store events instance.</param> /// <param name="bucketId">The value which uniquely identifies bucket the stream belongs to.</param> /// <param name="streamId">The value which uniquely identifies the stream within the bucket to be created.</param> /// <returns>An empty stream.</returns> public static Task <IEventStream> CreateStream(this IStoreEvents storeEvents, string bucketId, Guid streamId) { EnsureStoreEventsNotNull(storeEvents); return(storeEvents.CreateStream(bucketId, streamId.ToString())); }
static void PopulateStore(IStoreEvents store, IBus bus) { var agID = Guid.NewGuid(); var stream = store.CreateStream(agID); var loE = new List<EventMessage>(); AddTextMessage(loE, "CreateEntity"); AddTextMessage(loE, "SupplyHedgedForPeriod"); AddTextMessage(loE, "SupplyHedgedForPeriod"); AddTextMessage(loE, "Usage"); loE.ForEach(stream.Add); using (var scope = new TransactionScope()) { Console.WriteLine("In transaction {0}", Transaction.Current != null); stream.CommitChanges(Guid.NewGuid()); throw new Exception("Bad stuff here"); bus.Publish(new TestDomainMessage("hello")); scope.Complete(); } }