Esempio n. 1
0
        public TAggregate GetById <TAggregate>(Guid id, int version = int.MaxValue) where TAggregate : class, IEventSource
        {
            if (version <= 0)
            {
                throw new InvalidOperationException("Cannot get version <= 0");
            }

            var streamName = _streamNameBuilder.GenerateForAggregate(typeof(TAggregate), id);
            var aggregate  = ConstructAggregate <TAggregate>();


            long sliceStart = 0;
            StreamEventsSlice currentSlice;
            var appliedEventCount = 0;

            do
            {
                long sliceCount = sliceStart + ReadPageSize <= version
                    ? ReadPageSize
                    : version - sliceStart;

                currentSlice = _streamStoreConnection.ReadStreamForward(streamName, sliceStart, (int)sliceCount);

                if (currentSlice is StreamNotFoundSlice)
                {
                    throw new AggregateNotFoundException(id, typeof(TAggregate));
                }

                if (currentSlice is StreamDeletedSlice)
                {
                    throw new AggregateDeletedException(id, typeof(TAggregate));
                }

                sliceStart = currentSlice.NextEventNumber;

                appliedEventCount += currentSlice.Events.Length;
                aggregate.RestoreFromEvents(currentSlice.Events.Select(evt => _eventSerializer.Deserialize(evt)));
            } while (version > currentSlice.NextEventNumber && !currentSlice.IsEndOfStream);

            if (version != Int32.MaxValue && version != appliedEventCount)
            {
                throw new AggregateVersionException(id, typeof(TAggregate), version, aggregate.ExpectedVersion);
            }

            if (version != Int32.MaxValue && aggregate.ExpectedVersion != version - 1)
            {
                throw new AggregateVersionException(id, typeof(TAggregate), version, aggregate.ExpectedVersion);
            }

            return(aggregate);
        }
Esempio n. 2
0
        /// <summary>
        /// Named Stream Reader
        /// i.e. [StreamName]
        /// </summary>
        /// <param name="streamName">An exact stream name.</param>
        /// <param name="checkpoint">The starting point to read from.</param>
        /// <param name="count">The count of items to read</param>
        /// <param name="readBackwards">Read the stream backwards</param>
        /// <returns>Returns true if any events were read from the stream</returns>
        public virtual bool Read(
            string streamName,
            long?checkpoint    = null,
            long?count         = null,
            bool readBackwards = false)
        {
            var eventsRead = false;

            if (checkpoint != null)
            {
                Ensure.Nonnegative((long)checkpoint, nameof(checkpoint));
            }
            if (count != null)
            {
                Ensure.Positive((long)count, nameof(count));
            }
            if (!ValidateStreamName(streamName))
            {
                throw new ArgumentException("Stream not found.", streamName);
            }

            _cancelled     = false;
            firstEventRead = false;
            StreamName     = streamName;
            long sliceStart = checkpoint ?? (readBackwards ? -1 : 0);
            long remaining  = count ?? long.MaxValue;
            StreamEventsSlice currentSlice;

            do
            {
                var page = remaining < ReadPageSize ? remaining: ReadPageSize;

                currentSlice = !readBackwards
                    ? _streamStoreConnection.ReadStreamForward(streamName, sliceStart, page)
                    : _streamStoreConnection.ReadStreamBackward(streamName, sliceStart, page);

                if (!(currentSlice is StreamEventsSlice))
                {
                    return(false);
                }

                remaining -= currentSlice.Events.Length;
                sliceStart = currentSlice.NextEventNumber;

                Array.ForEach(currentSlice.Events, EventRead);
            } while (!currentSlice.IsEndOfStream && !_cancelled && remaining != 0);
            return(eventsRead);
        }
        private async Task ReadEventsInternalAsync(IStreamStoreConnection connection, UserCredentials userCredentials, long?lastEventNumber)
        {
            StreamEventsSlice slice;

            do
            {
                slice = connection.ReadStreamForward(
                    StreamId,
                    _nextReadEventNumber,
                    ReadBatchSize,
                    userCredentials);
            }while (!await ReadEventsCallbackAsync(slice, lastEventNumber).ConfigureAwait(false));
        }
Esempio n. 4
0
 internal static void WaitForStream(IStreamStoreConnection conn, string streamName)
 {
     //wait for the category projection to be written
     AssertEx.IsOrBecomesTrue(
         () =>
     {
         try
         {
             return(conn.ReadStreamForward(streamName, 0, 1) != null);
         }
         catch
         {
             return(false);
         }
     },
         2000,
         $"Stream '{streamName}' not created");
 }
Esempio n. 5
0
        public void Connect(
            UserCredentials credentials,
            IPAddress server,
            int tcpPort)
        {
            var tcpEndpoint = new IPEndPoint(server, tcpPort);

            var settings = ConnectionSettings.Create()
                           .SetDefaultUserCredentials(new global::EventStore.ClientAPI.SystemData.UserCredentials(credentials.Username, credentials.Password))
                           .KeepReconnecting()
                           .KeepRetrying()
                           .UseConsoleLogger()
                           //.EnableVerboseLogging()
                           .Build();

            Connection = new EventStoreConnectionWrapper(EventStoreConnection.Create(settings, tcpEndpoint, "Default Connection"));

            if (Connection == null)
            {
                _log.Error("EventStore Connection is null - Diagnostic Monitoring will be unavailable.");
                TeardownEventStore(false);
                return;
            }
            Connection.Connect();
            int retry = 8;
            int count = 0;

            do
            {
                try {
                    Connection.ReadStreamForward("by_event_type", 0, 1);
                    return;
                }
                catch {
                    //ignore
                }
                Thread.Sleep(100);
                count++;
            } while (count < retry);
            throw new Exception("Unable to start Eventstore");
        }
Esempio n. 6
0
        public static bool TryConfirmStream(this IStreamStoreConnection conn, string streamTypeName, int expectedEventCount)
        {
            int count = 0;

            while (true)
            {
                try {
                    var slice = conn.ReadStreamForward(streamTypeName, StreamPosition.Start, 500);
                    if (slice.IsEndOfStream && slice.Events.Length == expectedEventCount)
                    {
                        return(true);
                    }
                    Thread.Sleep(10);
                    count++;
                    if (count > 100)
                    {
                        return(false);
                    }
                }
                catch {
                    //ignore
                }
            }
        }
        public bool ValidateStreamName(string streamName)
        {
            var isValid = _eventStoreConnection.ReadStreamForward(streamName, 0, 1) != null;

            return(isValid);
        }
Esempio n. 8
0
        /// <summary>
        /// Named Stream Reader
        /// i.e. [StreamName]
        /// </summary>
        /// <param name="streamName">An exact stream name.</param>
        /// <param name="completionCheck">Read will block until true to ensure processing has completed, use '()=> true' to continue without blocking. If cancellation or timeout is required it should be implemented in the completion method</param>
        /// <param name="checkpoint">The event number of the last received event. Reading will start with the next event.</param>
        /// <param name="count">The count of items to read</param>
        /// <param name="readBackwards">Read the stream backwards</param>
        /// <returns>Returns true if any events were read from the stream</returns>
        public virtual bool Read(
            string streamName,
            Func <bool> completionCheck,
            long?checkpoint    = null,
            long?count         = null,
            bool readBackwards = false)
        {
            if (checkpoint != null)
            {
                Ensure.Nonnegative((long)checkpoint, nameof(checkpoint));
            }
            if (count != null)
            {
                Ensure.Positive((long)count, nameof(count));
            }
            if (!ValidateStreamName(streamName))
            {
                throw new ArgumentException("Stream not found.", streamName);
            }

            _cancelled     = false;
            FirstEventRead = false;
            StreamName     = streamName;
            long sliceStart;

            if (checkpoint is null)
            {
                sliceStart = readBackwards ? -1 : 0;
            }
            else
            {
                sliceStart = checkpoint.Value + (readBackwards ? -1 : 1);
            }
            long remaining = count ?? long.MaxValue;
            StreamEventsSlice currentSlice;

            do
            {
                var page = remaining < ReadPageSize ? remaining : ReadPageSize;

                currentSlice = !readBackwards
                    ? _streamStoreConnection.ReadStreamForward(streamName, sliceStart, page)
                    : _streamStoreConnection.ReadStreamBackward(streamName, sliceStart, page);

                if (!(currentSlice is StreamEventsSlice))
                {
                    break;
                }
                if (currentSlice.Events.Length > 0)
                {
                    FirstEventRead = true;
                }
                remaining -= currentSlice.Events.Length;
                sliceStart = currentSlice.NextEventNumber;

                Array.ForEach(currentSlice.Events, EventRead);
            } while (!currentSlice.IsEndOfStream && !_cancelled && remaining != 0);
            if (FirstEventRead && completionCheck != null)
            {
                SpinWait.SpinUntil(() => { try { return(completionCheck()); } catch { return(true); } });
            }
            return(FirstEventRead);
        }