Exemple #1
0
        public async Task <EventReadResult> ReadStreamAsync(long eventNumber)
        {
            const string          appName    = nameof(EventStoreSample);
            IEventStoreConnection connection = await GetConnection();

            return(await connection.ReadEventAsync("", eventNumber, false, EventStoreCredentials.Default));
        }
Exemple #2
0
        public async Task <bool> Exists(int productId)
        {
            var stream = GetStreamName(productId);
            var result = await _connection.ReadEventAsync(stream, 1, false);

            return(result.Status != EventReadStatus.NoStream);
        }
Exemple #3
0
        public async Task <bool> Exists <T, TId>(TId aggregateId)
        {
            var stream = GetStreamName <T, TId>(aggregateId);
            var result = await _connection.ReadEventAsync(stream, 1, false);

            return(result.Status != EventReadStatus.NoStream);
        }
        /// <inheritdoc />
        public ulong GetOffset(EventHorizonKey key)
        {
            var result = _connection.ReadEventAsync(GetStreamForEventHorizonKey(key), StreamPosition.End, true).Result;

            if (result.Event.HasValue)
            {
                return(_serializer.FromJsonBytes <ulong>(result.Event.Value.Event.Data));
            }
            return(0);
        }
        private static long?GetLastEventNumber(this IEventStoreConnection connection, string streamName)
        {
            var lastEvent = connection.ReadEventAsync(streamName, -1, false).Result;

            if (lastEvent == null || lastEvent.Event == null)
            {
                return(null);
            }
            return(lastEvent.Event.Value.OriginalEventNumber);
        }
        /// <inheritdoc />
        public CommittedEventVersion Get(EventProcessorId eventProcessorId)
        {
            var result = _connection.ReadEventAsync(GetStreamForEventProcessorId(eventProcessorId), StreamPosition.End, true).Result;

            if (result.Event.HasValue)
            {
                return(_serializer.FromJsonBytes <CommittedEventVersion>(result.Event.Value.Event.Data));
            }
            return(CommittedEventVersion.None);
        }
Exemple #7
0
        public async Task <bool> Exists <T, TId>(TId aggregateId)
        {
            if (aggregateId == null)
            {
                throw new ArgumentNullException(nameof(aggregateId));
            }
            var result = await connection.ReadEventAsync(GetStreamName <T, TId>(aggregateId), 1, false);

            return(result.Status != EventReadStatus.NoStream);
        }
        private static long?GetLastEventNumber(this IEventStoreConnection connection, string streamName)
        {
            var lastEvent = connection.ReadEventAsync(streamName, -1, false, EventStoreCredentials.Default);

            if (lastEvent == null || lastEvent.Result.Event == null)
            {
                return(null);
            }

            return(lastEvent.Result.EventNumber);
        }
        public static T GetLastEvent <T>(this IEventStoreConnection connection, string streamName) where T : class
        {
            var lastEvent = connection.ReadEventAsync(streamName, -1, false, EventStoreCredentials.Default);

            if (lastEvent == null || lastEvent.Result.Event == null)
            {
                return(null);
            }

            return(lastEvent.Result.Event.Value.ParseJson <T>());
        }
 public long GetLastEventNumber()
 {
     try
     {
         var readEvent = _conn.ReadEventAsync(_stream, StreamPosition.End, true).Result;
         return(readEvent.Event.Value.Event.EventNumber);
     }
     catch (Exception)
     {
         return(-1);
     }
 }
        /// <inheritdoc />
        public async Task <Snapshot> ReadSnapshot(object id, Type aggregateType)
        {
            var snapshot = await _connection.ReadEventAsync(StreamNameResolver.ResolveForSnapshot(id, aggregateType), StreamPosition.End, true);

            if (NotAnySnapshotExists(snapshot))
            {
                return(await Task.FromResult <Snapshot>(null));
            }

            return((Snapshot)JsonConvert.DeserializeObject(
                       // ReSharper disable once PossibleInvalidOperationException
                       Encoding.UTF8.GetString(snapshot.Event.Value.Event.Data), TypeResolver.ResolveSnapshotType(snapshot.Event.Value.Event.EventType)));
        }
        public static T GetLastEvent <T>(this IEventStoreConnection connection, string streamName)
            where T : class
        {
            if (connection == null)
            {
                throw new ArgumentNullException("connection");
            }
            var lastEvent = connection.ReadEventAsync(streamName, -1, false).Result;

            if (lastEvent == null || lastEvent.Event == null)
            {
                return(null);
            }
            return(lastEvent.Event.Value.ParseJson <T>());
        }
        /// <inheritdoc />
        public async Task TakeSnapshotIfNeed(IAggregateRoot aggregate)
        {
            var lastSnapshotVersion = -1L;
            var lastSnapshot        = await _connection.ReadEventAsync(StreamNameResolver.ResolveForSnapshot(aggregate), StreamPosition.End, true);

            if (AnySnapshotExists(lastSnapshot))
            {
                lastSnapshotVersion = lastSnapshot.Event.GetValueOrDefault().OriginalEventNumber;
            }

            if (NeedToTakeSnapshot(aggregate, lastSnapshotVersion))
            {
                await TakeSnapshot(_connection, aggregate);
            }
        }
        public async Task <EventFromStream> ReadEventAsync(IEventStoreConnection connection, string stream, long index)
        {
            var result = await connection.ReadEventAsync(stream, index, false);

            if (ResultHasNoEvent(result))
            {
                return(new NoEventFound());
            }

            return(new LoadedEvent
            {
                Type = result.Event?.Event.EventType,
                Data = result.Event?.Event.Data ?? new byte[] { }
            });
        }
        public async Task <TEvent> ReadEventAsync <TEvent>(string streamName, int position) where TEvent : class
        {
            var result = await connection.ReadEventAsync(streamName, position, resolveLinkTos : true).ConfigureAwait(false);

            if (!result.Event.HasValue)
            {
                throw new EventNotFoundException(streamName, position);
            }

            var originalEvent = result.Event.Value.OriginalEvent;

            var evt = DeserializeEvent(originalEvent.Metadata, originalEvent.Data);

            return(evt as TEvent);
        }
        public async Task <StreamReadResults> ReadFrom(string streamId, Func <IAmAStoredEvent, bool> predicate = null, StreamReadDirection direction = StreamReadDirection.Backwards, CancellationToken cancellationToken = default)
        {
            predicate ??= _ => true;

            IAsyncEnumerable <StoredEvent> storedEvents;

            if (direction == StreamReadDirection.Backwards)
            {
                var readResult = await connection.ReadStreamEventsBackwardAsync(streamId, StreamPosition.End, pageSize, true);

                if (!StreamExists(readResult))
                {
                    return(new StreamReadResults(EmptyReadResult, false, StoredEventPosition.FromInt64(-1)));
                }

                storedEvents = readResult.Events
                               // Trust me, resharper is wrong in this one. Event can be null
                               // ReSharper disable once ConditionIsAlwaysTrueOrFalse
                               .Where(e => e.Event != null)
                               .Select((e, _) => e.Event.ToStoredEvent(stateFactory))
                               .TakeWhile(e => e.DeserializedEvent is not EntitySoftDeleted)
                               .Where(e => predicate(e))
                               .ToAsyncEnumerable();
            }
            else
            {
                var readResult = await connection.ReadStreamEventsForwardAsync(streamId, StreamPosition.Start, pageSize, true);

                if (!StreamExists(readResult))
                {
                    return(new StreamReadResults(EmptyReadResult, false, StoredEventPosition.FromInt64(-1)));
                }

                storedEvents = readResult.Events
                               // Trust me, resharper is wrong in this one. Event can be null
                               // ReSharper disable once ConditionIsAlwaysTrueOrFalse
                               .Where(e => e.Event != null)
                               .Select((e, c) => e.Event.ToStoredEvent(stateFactory))
                               .Where(e => predicate(e))
                               .ToAsyncEnumerable();
            }

            var result = await connection.ReadEventAsync(streamId, StreamPosition.End, false);

            var idx = result.Event?.OriginalEventNumber ?? -1;

            return(new StreamReadResults(storedEvents, true, StoredEventPosition.FromInt64(idx)));
        }
Exemple #17
0
        public Position Get()
        {
            var resolvedEvent = _connection.ReadEventAsync(StreamId, StreamPosition.End, false).Result.Event;

            if (resolvedEvent == null)
            {
                return(_lastPosition);
            }
            var @event  = SerializationUtils.DeserializeEvent(resolvedEvent.Value.Event);
            var changed = @event as PositionChanged;

            if (changed != null)
            {
                _lastPosition = new Position(changed.Commit, changed.Prepare);
            }
            return(_lastPosition);
        }
        public async Task <ISnapshot> GetSnapshot(String bucket, String stream)
        {
            Logger.DebugFormat("Getting snapshot for stream '{0}' in bucket '{1}'", stream, bucket);

            var streamId = String.Format("{0}.{1}.{2}", bucket, stream, "snapshots");

            if (_shouldCache)
            {
                var cached = _cache.RetreiveSnap(streamId);
                if (cached != null)
                {
                    return(cached);
                }
            }

            var read = await _client.ReadEventAsync(streamId, StreamPosition.End, false);

            if (read.Status != EventReadStatus.Success || !read.Event.HasValue)
            {
                return(null);
            }

            var @event = read.Event.Value.Event;

            var descriptor = @event.Metadata.Deserialize(_settings);
            var data       = @event.Data.Deserialize(@event.EventType, _settings);

            var snapshot = new Snapshot
            {
                EntityType = descriptor.EntityType,
                Bucket     = bucket,
                Stream     = stream,
                Timestamp  = descriptor.Timestamp,
                Version    = descriptor.Version,
                Payload    = data
            };

            if (_shouldCache)
            {
                _cache.CacheSnap(streamId, snapshot);
            }
            return(snapshot);
        }
Exemple #19
0
        StreamVersionedValue <CommitSequenceNumber> GetNextCommitSequenceNumber()
        {
            var result = _connection.ReadEventAsync(GetStreamForCommit(), StreamPosition.End, true).Result;

            ThrowIfStreamWasDeleted(GetStreamForCommit(), result);
            if (result.Status == EventReadStatus.NoStream)
            {
                return(new StreamVersionedValue <CommitSequenceNumber>(GetStreamForCommit(), ExpectedVersion.NoStream, 0));
            }
            try
            {
                var metadata = _serializer.FromJsonBytes <EventMetadata>(result.Event.Value.Event.Metadata);
                return(new StreamVersionedValue <CommitSequenceNumber>(GetStreamForCommit(), result.Event.Value.Event.EventNumber, metadata.Commit.Sequence + 1));
            }
            catch (Exception ex)
            {
                throw new CorruptedEventStore("Could not deserialize event metadata", ex);
            }
        }
        public async Task <long?> GetLastPositionInStreamAsync(string streamId)
        {
            try
            {
                long?lastPosition = null;

                var result = await _connection.ReadEventAsync(streamId, StreamPosition.End, false);

                if (result.Status == EventReadStatus.Success)
                {
                    if (result.Event.HasValue)
                    {
                        lastPosition = result.Event.Value.OriginalEventNumber;
                    }
                }

                return(lastPosition);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Exception while getting end of stream.");
                throw;
            }
        }
        public async Task <TAggregate?> AggregateAsync <TIdentity, TAggregate>(
            TIdentity id,
            AggregateConfiguration <TIdentity, TAggregate> configuration,
            long?version = null,
            CancellationToken cancellationToken = default
            )
            where TAggregate : Aggregate <TIdentity, TAggregate>
        {
            var stream = _streamNameResolver.Stream(id, configuration);

            var createdResult = await _connection.ReadEventAsync(stream, StreamPosition.Start, false);

            if (createdResult.Event == null)
            {
                return(null);
            }

            var createdResolvedEvent = createdResult.Event.Value;
            var createdRecordedEvent = createdResolvedEvent.Event;

            if (!configuration.Constructors.TryGetValue(createdRecordedEvent.EventType, out var constructor))
            {
                throw new InvalidOperationException(
                          $"Unrecognized construction event type: {createdRecordedEvent.EventType}"
                          );
            }

            var aggregate = constructor(id, _serializer, createdRecordedEvent.Data);

            aggregate.Record(new RecordableEvent(createdRecordedEvent.EventNumber));

            var applicators = configuration.Applicators;

            long      sliceStart = 1;
            const int sliceSize  = 100;

            StreamEventsSlice slice;

            do
            {
                slice = await _connection.ReadStreamEventsForwardAsync(stream, sliceStart, sliceSize, false);

                foreach (var resolvedEvent in slice.Events)
                {
                    var recordedEvent = resolvedEvent.Event;
                    if (version.HasValue && recordedEvent.EventNumber > version.Value)
                    {
                        return(aggregate);
                    }

                    if (applicators.TryGetValue(recordedEvent.EventType, out var applicator))
                    {
                        applicator(aggregate, _serializer, recordedEvent.Data);
                        aggregate.Record(new RecordableEvent(recordedEvent.EventNumber));
                    }
                    else
                    {
                        throw new InvalidOperationException(
                                  $"Unexpected recorded event type: {recordedEvent.EventType}"
                                  );
                    }
                }

                sliceStart = slice.NextEventNumber;
            } while (!slice.IsEndOfStream);

            return(aggregate);
        }
        public async Task <HealthCheckResult> CheckHealthAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            await connection.ReadEventAsync("test", 1, false);

            return(new HealthCheckResult(true, "Querying test event from event store."));
        }
Exemple #23
0
        public async Task <bool> Exists(string streamName)
        {
            var result = await _connection.ReadEventAsync(streamName, 1, false);

            return(result.Status != EventReadStatus.NoStream);
        }
 public void throw_if_stream_id_is_null()
 {
     Assert.Throws <ArgumentNullException>(() => _conn.ReadEventAsync(null, 0, resolveLinkTos: false));
 }
Exemple #25
0
        public async Task <long?> GetLastEventNumberAsync(string streamName)
        {
            var lastEvent = await eventStoreConnection.ReadEventAsync(streamName, -1, false, CredentialsHelper.Default);

            return(lastEvent?.Event?.OriginalEventNumber);
        }
        private static void ReadEvent(IEventStoreConnection connection)
        {
            EventReadResult result = connection.ReadEventAsync("test-stream", 0, false).Result;
            if (result.Event.HasValue)
            {
                Console.WriteLine("id: " + result.Event.Value.Event.EventId);

                string data = Encoding.UTF8.GetString(result.Event.Value.Event.Data);
                Console.WriteLine("data: " + data);

                string metadata = Encoding.UTF8.GetString(result.Event.Value.Event.Metadata);
                Console.WriteLine("metadata: " + metadata);
            }
        }
 public Task <EventReadResult> ReadEventFromStream(string streamName, long eventNumber, bool resolveLinkTos)
 => _client.ReadEventAsync(streamName, eventNumber, resolveLinkTos);
 protected void ReadEvent(string streamId, string login, string password)
 {
     Connection.ReadEventAsync(streamId, -1, false,
                               login == null && password == null ? null : new UserCredentials(login, password))
     .Wait();
 }
Exemple #29
0
 protected Task ReadEvent(string streamId, string login, string password)
 {
     return(Connection.ReadEventAsync(streamId, -1, false,
                                      login == null && password == null ? null : new UserCredentials(login, password)));
 }
Exemple #30
0
        public async Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
        {
            await connection.ReadEventAsync("test", 1, false);

            return(HealthCheckResult.Healthy("Application must query data from EventStore."));
        }
Exemple #31
0
        private async Task <SnapShotSearchSearch?> FindSnapshotEvent(string persistenceId, string streamName, IEventStoreConnection connection, SnapshotSelectionCriteria criteria)
        {
            if (SnapshotSelectionCriteria.Latest.Equals(criteria))
            {
                // Always just read last snapshot, theres no point trying to read old snapshots..
                // Also here 'criteria.MaxSequenceNr' has no relationship to the position in the event stream, this was a BUG!
                var latestSnapshot = await connection.ReadEventAsync(streamName, StreamPosition.End, false);

                if (latestSnapshot.Status != EventReadStatus.Success)
                {
                    _log.Debug("No snapshot found for: {0}", persistenceId);
                    return(null);
                }
                var @event         = latestSnapshot.Event.Value.Event;
                var representation = (SnapshotRepresentation)_serializer.FromBinary(@event.Data, typeof(SnapshotRepresentation));

                return(new SnapShotSearchSearch {
                    snapshot = ToSelectedSnapshot(representation),
                    streamOffset = latestSnapshot.Event.Value.OriginalEventNumber,
                });
            }
            else
            {
                var currentPosition = (long)StreamPosition.End;
                while (true)
                {
                    // Always just read last snapshot, theres no point trying to read old snapshots..
                    // Also here 'criteria.MaxSequenceNr' has no relationship to the position in the event stream, this was a BUG!
                    var latestSnapshot = await connection.ReadEventAsync(streamName, currentPosition, false);

                    if (latestSnapshot.Status != EventReadStatus.Success)
                    {
                        _log.Debug("No snapshot found for: {0}", persistenceId);
                        break;
                    }
                    else
                    {
                        _log.Debug("Found snapshot of {0}", persistenceId);
                        var @event = latestSnapshot.Event.Value.Event;

                        var representation = (SnapshotRepresentation)_serializer.FromBinary(@event.Data, typeof(SnapshotRepresentation));
                        var result         = ToSelectedSnapshot(representation);

                        if (result.Metadata.SequenceNr < criteria.MinSequenceNr)
                        {
                            break;
                        }

                        if (criteria.MinTimestamp.HasValue)
                        {
                            if (result.Metadata.Timestamp < criteria.MinTimestamp.Value)
                            {
                                break;
                            }
                        }

                        if (result.Metadata.SequenceNr <= criteria.MaxSequenceNr && result.Metadata.Timestamp <= criteria.MaxTimeStamp)
                        {
                            return(new SnapShotSearchSearch
                            {
                                snapshot = ToSelectedSnapshot(representation),
                                streamOffset = currentPosition,
                            });
                        }
                        else
                        {
                            // Read the next event
                            currentPosition = latestSnapshot.Event.Value.OriginalEventNumber - 1L;
                            if (currentPosition < 1L)
                            {
                                break;
                            }
                        }
                    }
                }

                return(null);
            }
        }