public async Task IsPrime_ES(int number) { // Arrange await TryCleanECStream(); var grain = _cluster.Client.GetGrain <IPrime>(0); await grain.Consume(); var vnt = new EventData( Uuid.NewUuid(), number.GetType().ToString(), JsonSerializer.SerializeToUtf8Bytes(number) ); // Act await _eventStore.AppendToStreamAsync( InterfaceConst.PSPrime, StreamState.Any, new[] { vnt } ); await Task.Delay(TimeSpan.FromSeconds(1)); // Assert var item = await grain.GetAsync(); Assert.True(item.IsValid); Assert.NotEqual(0, item.Value); }
private static async Task AppendWithSameId(EventStoreClient client) { #region append-duplicate-event var eventData = new EventData( Uuid.NewUuid(), "some-event", Encoding.UTF8.GetBytes("{\"id\": \"1\" \"value\": \"some value\"}") ); await client.AppendToStreamAsync( "same-event-stream", StreamState.Any, new List <EventData> { eventData }); // attempt to append the same event again await client.AppendToStreamAsync( "same-event-stream", StreamState.Any, new List <EventData> { eventData }); #endregion append-duplicate-event }
private static async Task AppendWithNoStream(EventStoreClient client) { #region append-with-no-stream var eventDataOne = new EventData( Uuid.NewUuid(), "some-event", Encoding.UTF8.GetBytes("{\"id\": \"1\" \"value\": \"some value\"}") ); var eventDataTwo = new EventData( Uuid.NewUuid(), "some-event", Encoding.UTF8.GetBytes("{\"id\": \"2\" \"value\": \"some other value\"}") ); await client.AppendToStreamAsync( "no-stream-stream", StreamState.NoStream, new List <EventData> { eventDataOne }); // attempt to append the same event again await client.AppendToStreamAsync( "no-stream-stream", StreamState.NoStream, new List <EventData> { eventDataTwo }); #endregion append-with-no-stream }
public async Task <IDomainEvent <IDomainEventData> > Store(ICreateEvent <IDomainEventData> newEvent) { var eventData = newEvent.Data; var dataJson = _eventFactory.SerializeToData(eventData); var data = Encoding.UTF8.GetBytes(dataJson); var metadata = Encoding.UTF8.GetBytes("{}"); var eventId = Guid.NewGuid(); var eventName = _eventFactory.EventName(eventData); var evt = new EventData(Uuid.FromGuid(eventId), eventName, data, metadata); var eventStream = eventData.GetAggregateKey(); IWriteResult result; if (newEvent.IsNewAggregate) { result = await _client.AppendToStreamAsync(eventStream, StreamState.NoStream, new List <EventData>() { evt }); } else if (newEvent.IsVersioned) { result = await _client.AppendToStreamAsync(eventStream, new StreamRevision(newEvent.Version), new List <EventData>() { evt }); } else { result = await _client.AppendToStreamAsync(eventStream, StreamState.StreamExists, new List <EventData>() { evt }); } _logger.LogDebug("Appended event {position}|{type}.", result.LogPosition, evt.Type); return(_eventFactory.CreateEvent(result.NextExpectedStreamRevision.ToUInt64(), SystemClock.Instance.GetCurrentInstant(), eventData)); }
protected override Task ProduceMany(IEnumerable <object> messages, CancellationToken cancellationToken) { var data = Ensure.NotNull(messages, nameof(messages)) .Select(x => CreateMessage(x, x.GetType())); return(_client.AppendToStreamAsync(_stream, StreamState.Any, data, cancellationToken: cancellationToken)); }
public async Task <ulong> AppendAsync(Guid eventID, string eventName, string streamName, ulong?expectedEventNumber, EventStoreState expectedState, byte[] data) { var eventData = new EventData(Uuid.FromGuid(eventID), eventName, data); if (expectedEventNumber.HasValue) { var revision = new StreamRevision(expectedEventNumber.Value); var writeResult = await client.AppendToStreamAsync(streamName, revision, new EventData[] { eventData }); return(writeResult.NextExpectedStreamRevision); } else { StreamState state; switch (expectedState) { case EventStoreState.Any: state = StreamState.Any; break; case EventStoreState.NotExisting: state = StreamState.NoStream; break; case EventStoreState.Existing: state = StreamState.StreamExists; break; default: throw new NotImplementedException(); } var writeResult = await client.AppendToStreamAsync(streamName, state, new EventData[] { eventData }); return(writeResult.NextExpectedStreamRevision); } }
static async Task Main(string[] args) { CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken cancellationToken = tokenSource.Token; #region createClient var settings = EventStoreClientSettings .Create("{connectionString}"); var client = new EventStoreClient(settings); #endregion createClient #region createEvent var evt = new TestEvent { EntityId = Guid.NewGuid().ToString("N"), ImportantData = "I wrote my first event!" }; var eventData = new EventData( Uuid.NewUuid(), "TestEvent", JsonSerializer.SerializeToUtf8Bytes(evt) ); #endregion createEvent #region appendEvents await client.AppendToStreamAsync( "some-stream", StreamState.Any, new[] { eventData }, cancellationToken : cancellationToken ); #endregion appendEvents #region overriding-user-credentials await client.AppendToStreamAsync( "some-stream", StreamState.Any, new[] { eventData }, userCredentials : new UserCredentials("admin", "changeit"), cancellationToken : cancellationToken ); #endregion overriding-user-credentials #region readStream var result = client.ReadStreamAsync( Direction.Forwards, "some-stream", StreamPosition.Start, cancellationToken: cancellationToken); var events = await result.ToListAsync(cancellationToken); #endregion readStream }
public async Task Add(string stream, string entityId, IReadOnlyCollection <IDomainEvent> events) { var eventData = events.Select(e => new EventData( Uuid.NewUuid(), e.GetType().Name, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(e)))).ToArray(); await _client.AppendToStreamAsync( $"{stream}-{entityId}", StreamState.Any, eventData, configureOperationOptions : (o) => { o.TimeoutAfter = TimeSpan.FromMinutes(5); }); }
public Task AppendEvents(string streamName, long version, params object[] events) { if (events == null || !events.Any()) { return(Task.CompletedTask); } var preparedEvents = events.Select(e => e.Serialize()).ToList(); if (version == -1) { return(_client.AppendToStreamAsync(ToStreamName(streamName), StreamState.NoStream, preparedEvents)); } return(_client.AppendToStreamAsync(ToStreamName(streamName), Convert.ToUInt64(version), preparedEvents)); }
public async Task <long> SaveAsync(AggregateBase aggregate, params KeyValuePair <string, string>[] extraHeaders) { var streamName = $"{aggregate.Identifier}-{aggregate.Id}"; var pendingEvents = aggregate.GetPendingEvents(); var originalVersion = (uint)aggregate.Version - (uint)pendingEvents.Count; //TODO: hamárvanilyenstream-akkorszálljonel-kezelés, StreamState enum ? try { IWriteResult result; var commitHeaders = CreateCommitHeaders(aggregate, extraHeaders); var eventsToSave = pendingEvents.Select(x => ToEventData(Guid.NewGuid(), x, commitHeaders)); result = await _eventStoreConnection.AppendToStreamAsync(streamName, originalVersion, eventsToSave); aggregate.ClearPendingEvents(); return(result.NextExpectedVersion); } catch (WrongExpectedVersionException ex) { throw new /*Concurrency*/ Exception("concurrency exception", ex); } }
private async Task EventStore() { for (uint mil = 0; mil < 100; mil++) { for (uint dez = (uint)(mil == 0 ? 100 : 0); dez < 1000; dez += 10) { var item = mil * 1000 + dez; var events = new List <EventData> { (item + 1).GetEvent(), (item + 3).GetEvent(), (item + 7).GetEvent(), (item + 9).GetEvent() }; try { await _eventStore.AppendToStreamAsync( InterfaceConst.PSPrime, StreamState.Any, events); } catch { } } } }
public async Task <Boolean> Save(AggregateRootWithEvents aggregateRoot, Int32 eventsPerRequest = 100) { var events = aggregateRoot.GetChanges(); String streamName = GetStreamId(aggregateRoot.GetType(), aggregateRoot.Id); var encoding = new UTF8Encoding(); IEnumerable <EventData> data = events.Select(x => new EventData( Uuid.NewUuid(), x.GetType().Name, encoding.GetBytes(JsonConvert.SerializeObject(x, _jsonSerializerSettings)), System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(new EventMeta { BodyType = x.GetType().AssemblyQualifiedName }))); Int32 eventPosition = 0; while (true) { var dataToSend = data.Skip(eventPosition).Take(eventsPerRequest).ToArray(); await _client.AppendToStreamAsync(streamName, StreamState.Any, dataToSend); if (dataToSend.Length != eventsPerRequest) { break; } eventPosition += eventsPerRequest; } return(true); }
public void NotifyOfPackageDelivery(Package package) { const string stream = "Package-delivery-stream"; var settings = EventStoreClientSettings .Create("esdb://127.0.0.1:2113?tls=false"); var packageDeliveryInfo = new PackageDeliveryInfo { Number = package.Number, RecipientName = package.RecipientName, RecipientEmail = package.RecipientEmail, RecipientSurname = package.RecipientSurname, RecipientStreet = package.RecipientStreet, RecipientStreetNumber = package.RecipientStreetNumber, RecipientPostCode = package.RecipientPostCode, RecipientCity = package.RecipientCity, SenderEmail = package.Sender.Email, }; using (var client = new EventStoreClient(settings)) { client.AppendToStreamAsync( stream, StreamState.Any, new[] { GetEventDataFor(packageDeliveryInfo) }).Wait(); } }
public async Task SaveAsync(TEventSourcedAggregate aggregate, CancellationToken token = default) { if (!aggregate.UncommittedEvents.Any()) { return; } var streamName = GetStreamName(aggregate.Id); var originalAggregateVersion = aggregate.Version - aggregate.UncommittedEvents.Count; var expectedStreamRevision = originalAggregateVersion is 0 ? StreamRevision.None : new StreamRevision((ulong)originalAggregateVersion - 1); var metadata = new EventMetadata( CausationId: RequestContext.RequestId, CorrelationId: RequestContext.CorrelationId); var eventsToSave = aggregate.UncommittedEvents.Select(@event => EventStoreSerializer.Serialize(@event, metadata)); try { await _client.AppendToStreamAsync(streamName, expectedStreamRevision, eventsToSave, cancellationToken : token); } catch (WrongExpectedVersionException e) when(e.ExpectedStreamRevision == StreamRevision.None) { throw new Exceptions.DuplicateKeyException(aggregate.Id); } aggregate.MarkEventsAsCommitted(); }
protected async Task ExecuteAsync(CancellationToken cancellationToken) { #region createClient var settings = EventStoreClientSettings .Create("{connectionString}"); var client = new EventStoreClient(settings); #endregion createClient #region createEvent var evt = new TestEvent { EntityId = Guid.NewGuid().ToString("N"), ImportantData = "I wrote my first event!" }; var eventData = new EventData( Uuid.NewUuid(), "TestEvent", JsonSerializer.SerializeToUtf8Bytes(evt) ); #endregion createEvent #region writingEvent await client.AppendToStreamAsync( "testStream", StreamState.Any, new[] { eventData }, cancellationToken : cancellationToken ); #endregion writingEvent }
public static async Task <int> Main(string[] args) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Verbose() .WriteTo.Console() .CreateLogger(); var eventStoreClient = new EventStoreClient(new EventStoreClientSettings { LoggerFactory = new SerilogLoggerFactory() }); await Task.WhenAll(Enumerable.Range(0, 100) .Select(i => eventStoreClient.AppendToStreamAsync($"stream-{i}", StreamState.Any, new[] { new EventData(Uuid.NewUuid(), "-", Array.Empty <byte>(), contentType: "application/octet-stream"), }))); await new HostBuilder() .ConfigureHostConfiguration(builder => builder .AddEnvironmentVariables("DOTNET_") .AddCommandLine(args ?? Array.Empty <string>())) .ConfigureAppConfiguration(builder => builder .AddEnvironmentVariables() .AddCommandLine(args ?? Array.Empty <string>())) .ConfigureLogging(logging => logging.AddSerilog()) .ConfigureWebHostDefaults(builder => builder .UseKestrel() .ConfigureServices(services => services.AddCors().AddRouting()) .Configure(app => app .UseEventStoreHALBrowser() .UseEventStoreHAL(eventStoreClient))) .RunConsoleAsync(); return(0); }
static async Task Main(string[] args) { // run against // .\EventStore-OSS-Windows-2019-v20.6.1\EventStore.ClusterNode.exe --insecure // make sure http://localhost:2113 works var connectionString = "esdb://*****:*****@localhost:2113/?TlsVerifyCert=false&Tls=false"; // run against // .\EventStore-OSS-Windows-2019-v20.6.0\EventStore.ClusterNode.exe --dev // make sure https://localhost:2113 works //var connectionString = "esdb://*****:*****@localhost:2113/?TlsVerifyCert=false"; var settings = EventStoreClientSettings.Create(connectionString); var client = new EventStoreClient(settings); await client.SubscribeToAllAsync(EventAppeared); Console.WriteLine("Subscribed to all events."); var data = Encoding.UTF8.GetBytes("{}"); var eventData = new EventData(Uuid.NewUuid(), "test-event", data); await client.AppendToStreamAsync("test-events", StreamState.Any, new[] { eventData }); Console.WriteLine("Keypress to exit."); Console.ReadKey(); }
public async Task Emit <TEvent>(TEvent @event) where TEvent : T { Events.Add(@event); await _eventStore.AppendToStreamAsync(_stream, StreamState.Any, new[] { @event.GetEvent() } ); }
public Task AppendAsync(EventBase @event) { return(_client.AppendToStreamAsync($"{@event.Type}.{@event.CorrelationId}", StreamState.Any, new List <EventData> { new EventData(Uuid.NewUuid(), @event.EventName, Encoding.UTF8.GetBytes(@event.Payload)) })); }
public async Task Save <TAggregate>(TAggregate aggregate) where TAggregate : Aggregate { if (aggregate == null) { throw new ArgumentNullException(nameof(aggregate)); } var stream = GetStreamName <TAggregate>(aggregate.Id); var changes = aggregate.Changes.ToArray(); var events = changes.Select(CreateEventData); var resultTask = aggregate.Version < 0 ? _client.AppendToStreamAsync(stream, StreamState.NoStream, events) : _client.AppendToStreamAsync(stream, StreamRevision.FromInt64(aggregate.Version), events); var result = await resultTask; aggregate.ClearChanges();
private async Task SoftDeleteByEventImpl(TId selector, EventData softDeleteEvent) { var readResult = await eventReader.ReadFrom(selector.ToString()); if (readResult.streamExists) { await client.AppendToStreamAsync(selector.ToString(), StreamState.Any, new[] { softDeleteEvent }); } }
public static async Task Publish( this EventStoreClient eventStore, string streamName, IDomainEvent domainEvent, IEventSerializer eventSerializer ) { await eventStore.AppendToStreamAsync(streamName, StreamState.Any, new[] { eventSerializer.Serialize(domainEvent) }); }
private static async Task AppendWithConcurrencyCheck(EventStoreClient client) { #region append-with-concurrency-check var clientOneRead = client.ReadStreamAsync( Direction.Forwards, "concurrency-stream", StreamPosition.Start, configureOperationOptions: options => options.ThrowOnAppendFailure = false); var clientOneRevision = (await clientOneRead.LastAsync()).Event.EventNumber.ToUInt64(); var clientTwoRead = client.ReadStreamAsync(Direction.Forwards, "concurrency-stream", StreamPosition.Start); var clientTwoRevision = (await clientTwoRead.LastAsync()).Event.EventNumber.ToUInt64(); var clientOneData = new EventData( Uuid.NewUuid(), "some-event", Encoding.UTF8.GetBytes("{\"id\": \"1\" \"value\": \"clientOne\"}") ); await client.AppendToStreamAsync( "no-stream-stream", clientOneRevision, new List <EventData> { clientOneData }); var clientTwoData = new EventData( Uuid.NewUuid(), "some-event", Encoding.UTF8.GetBytes("{\"id\": \"2\" \"value\": \"clientTwo\"}") ); await client.AppendToStreamAsync( "no-stream-stream", clientTwoRevision, new List <EventData> { clientTwoData }); #endregion append-with-concurrency-check }
public async Task Emit <TEvent>(TEvent @event) where TEvent : IEvent { var vnt = @event as IsPrimeEvent; Events.Add(vnt); await _eventStore.AppendToStreamAsync( InterfaceConst.ESPrime, StreamState.Any, new[] { vnt.GetEvent() } ); }
protected async Task SaveEvent <TEvent>(TEvent @event, string stream) where TEvent : BaseEvent { Debug.WriteLine($"Appending data to {stream}"); var eventData = new EventData( Uuid.NewUuid(), @event.GetType().Name, JsonSerializer.SerializeToUtf8Bytes(@event)); await _storeClient.AppendToStreamAsync(stream, StreamState.Any, new[] { eventData }); }
public async Task Save(T aggregate) { var uncomittedEvents = aggregate.UncomittedEvents; var events = uncomittedEvents.Select(e => { var eventJsonUtf8 = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(e)); var message = new EventData(Uuid.NewUuid(), e.GetType().Name, eventJsonUtf8); return(message); }); await eventStore.AppendToStreamAsync(aggregate.PersistenceId, StreamState.Any, events); aggregate.Commit(); }
protected override async Task ProduceMany( string stream, IEnumerable <object> messages, EventStoreProduceOptions?options, CancellationToken cancellationToken ) { var data = Ensure.NotNull(messages, nameof(messages)) .Select(x => CreateMessage(x, x.GetType(), options?.Metadata)); foreach (var chunk in data.Chunks(ChunkSize)) { await _client.AppendToStreamAsync( stream, options?.ExpectedState ?? StreamState.Any, chunk, options?.ConfigureOperation, options?.Credentials, cancellationToken ).Ignore(); } }
/// <summary> /// Add ES prime only number /// </summary> /// <param name="number">number</param> public Task UpdateAsync(int number) { var key = this.GetPrimaryKeyLong(); _cache = _cache.NextVersion(number); _logger.LogInformation($"{DateTime.Now.TimeOfDay}: {nameof(PrimeOnlyGrain)} {key} updated value to {_cache.Value} with version {_cache.Version}"); return(_client.AppendToStreamAsync( InterfaceConst.PSPrimeOnly, StreamState.Any, new[] { number.GetEvent() } )); }
public Task SaveAsync(IAggregateRoot aggregateRoot, CancellationToken ct) { var events = aggregateRoot .GetEvents() .Select(ToEventData); return(_eventStore.AppendToStreamAsync( StreamName(aggregateRoot.GetType(), aggregateRoot.Id), StreamRevision.FromInt64(aggregateRoot.Version), events, cancellationToken: ct )); }
private async Task RaiseEvent <T>(string eventName, T raisedEvent) { var json = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(raisedEvent)); var eventData = new EventData(Uuid.NewUuid(), eventName, json); await _esClient.AppendToStreamAsync(_stream, Convert.ToUInt64(Version - 1), new List <EventData> { eventData }); base.RaiseEvent(raisedEvent); await ConfirmEvents(); }