Beispiel #1
0
        public void soft_deleted_stream_allows_recreation_when_expver_any()
        {
            const string stream = "soft_deleted_stream_allows_recreation_when_expver_any";

            Assert.AreEqual(1, _conn.AppendToStreamAsync(stream, ExpectedVersion.NoStream, TestEvent.NewTestEvent(), TestEvent.NewTestEvent()).Result.NextExpectedVersion);
            _conn.DeleteStreamAsync(stream, 1).Wait();

            var events = new[] { TestEvent.NewTestEvent(), TestEvent.NewTestEvent(), TestEvent.NewTestEvent() };

            Assert.AreEqual(4, _conn.AppendToStreamAsync(stream, ExpectedVersion.Any, events).Result.NextExpectedVersion);

            Thread.Sleep(50); //TODO: This is a workaround until github issue #1744 is fixed

            var res = _conn.ReadStreamEventsForwardAsync(stream, 0, 100, false).Result;

            Assert.AreEqual(SliceReadStatus.Success, res.Status);
            Assert.AreEqual(4, res.LastEventNumber);
            Assert.AreEqual(3, res.Events.Length);
            Assert.AreEqual(events.Select(x => x.EventId), res.Events.Select(x => x.OriginalEvent.EventId));
            Assert.AreEqual(new[] { 2, 3, 4 }, res.Events.Select(x => x.OriginalEvent.EventNumber));

            var meta = _conn.GetStreamMetadataAsync(stream).Result;

            Assert.AreEqual(2, meta.StreamMetadata.TruncateBefore);
            Assert.AreEqual(1, meta.MetastreamVersion);
        }
Beispiel #2
0
        public override async Task <long> ReadHighestSequenceNrAsync(string persistenceId, long fromSequenceNr)
        {
            try
            {
                var slice = await _conn.ReadStreamEventsBackwardAsync(persistenceId, StreamPosition.End, 1, false);

                long sequence = 0;

                if (slice.Events.Any())
                {
                    var @event  = slice.Events.First();
                    var adapted = _eventAdapter.Adapt(@event);
                    sequence = adapted.SequenceNr;
                }
                else
                {
                    var metadata = await _conn.GetStreamMetadataAsync(persistenceId);

                    if (metadata.StreamMetadata.TruncateBefore != null)
                    {
                        sequence = metadata.StreamMetadata.TruncateBefore.Value;
                    }
                }

                return(sequence);
            }
            catch (Exception e)
            {
                _log.Error(e, e.Message);
                throw;
            }
        }
        public static async Task SetEventMaxAgeIfNull(this IEventStoreConnection connection, string streamName, TimeSpan maxAge)
        {
            for (int i = 0; i < 3; ++i)
            {
                var readRes = await connection.GetStreamMetadataAsync(streamName);

                if (readRes.IsStreamDeleted || readRes.StreamMetadata.MaxAge != null)
                {
                    return;
                }

                var metadata = StreamMetadata.Create(maxAge: maxAge);

                try
                {
                    await connection.SetStreamMetadataAsync(streamName, readRes.MetastreamVersion, metadata);

                    return;
                }
                catch (WrongExpectedVersionException)
                {
                }

                await Task.Delay((i + 1) * 100);
            }
        }
Beispiel #4
0
 /// <inheritdoc />
 protected override async Task UpdateStreamMetadata(IStream stream)
 {
     var metaVersion = (await _connection.GetStreamMetadataAsync(stream.Key)).MetastreamVersion;
     await _connection.SetStreamMetadataAsync(
         stream.Key,
         metaVersion,
         Encoding.UTF8.GetBytes(EncodeStreamMetadata(stream))); // JExtensions.JStreamMetadata(stream));
 }
 private static void GetStreamMetadata(IEventStoreConnection connection)
 {
     StreamMetadataResult metadata = connection.GetStreamMetadataAsync("test-stream").Result;
     Console.WriteLine("cache control: " + metadata.StreamMetadata.CacheControl);
     Console.WriteLine("custom value: " + metadata.StreamMetadata.GetValue<string>("key"));
     Console.WriteLine("max age: " + metadata.StreamMetadata.MaxAge);
     Console.WriteLine("max count: " + metadata.StreamMetadata.MaxCount);
 }
        public async Task <bool> AggregateExistsAsync <TIdentity, TAggregate>(
            TIdentity id,
            AggregateConfiguration <TIdentity, TAggregate> configuration,
            CancellationToken cancellationToken = default
            ) where TAggregate : Aggregate <TIdentity, TAggregate>
        {
            var stream = _streamNameResolver.Stream(id, configuration);
            var meta   = await _connection.GetStreamMetadataAsync(stream);

            return(meta.MetastreamVersion >= 0 && !meta.IsStreamDeleted);
        }
        public static async Task <StreamMeta> GetStreamMeta(
            this IEventStoreConnection connection, string stream
            )
        {
            var streamMeta = await
                             Metrics.Measure(
                () => connection.GetStreamMetadataAsync(stream),
                ReplicationMetrics.MetaReadsHistogram
                ).ConfigureAwait(false);

            return(new StreamMeta(
                       streamMeta.IsStreamDeleted,
Beispiel #8
0
        /// <summary>
        /// Enrich the stream from store
        /// </summary>
        /// <remarks>
        /// <para/>
        /// Null if stream exists but some of the ancestors do not
        /// </remarks>
        /// <param name="connection">Stream store</param>
        /// <param name="key">Stream key</param>
        /// <param name="serializer">Serializer</param>
        /// <returns>Stream info</returns>
        public static async Task <IStream> GetStream(
            this IEventStoreConnection connection, string key, ISerializer <IEvent> serializer)
        {
            var metadata = await connection.GetStreamMetadataAsync(key);

            var stream = serializer.DecodeStreamMetadata(metadata.StreamMetadata.AsJsonString());

            if (stream == null)
            {
                return(new Stream(key));
            }

            var count = await connection.DeletedCount(key);

            stream.AddDeleted(count);

            var parent = stream.Parent;

            while (parent != null && parent.Version > ExpectedVersion.EmptyStream)
            {
                var parentMetadata = await connection.GetStreamMetadataAsync(parent.Key);

                if (parentMetadata.StreamMetadata == null)
                {
                    return(null);
                }

                count = await connection.DeletedCount(parent.Key);

                parent.AddDeleted(count);

                var grandParent = serializer.DecodeStreamMetadata(parentMetadata.StreamMetadata.AsJsonString())?.Parent;

                parent.Parent = grandParent;
                parent        = grandParent;
            }

            return(stream);
        }
        protected override async Task DeleteAsync(SnapshotMetadata metadata)
        {
            var streamName = GetStreamName(metadata.PersistenceId);
            var m          = await _conn.GetStreamMetadataAsync(streamName);

            if (m.IsStreamDeleted)
            {
                return;
            }

            var streamMetadata = m.StreamMetadata.Copy();
            var timestamp      = metadata.Timestamp != DateTime.MinValue ? metadata.Timestamp : default(DateTime?);

            var result = await FindSnapshot(streamName, metadata.SequenceNr, timestamp);

            if (result.Snapshot == null)
            {
                return;
            }


            streamMetadata = streamMetadata.SetTruncateBefore(result.EventNumber + 1);
            await _conn.SetStreamMetadataAsync(streamName, ExpectedVersion.Any, streamMetadata.Build());
        }
Beispiel #10
0
        private static async Task <IEnumerable <string> > GetStreamIdsByCategoryBy(IEventStoreConnection conn, string category, bool includeDeleted = false)
        {
            var streamIds = await GetAllRawEvents(conn, "$category-" + category);

            if (includeDeleted)
            {
                return(streamIds);
            }
            else
            {
                var undeletedStreamIds = new List <string>();
                foreach (var id in streamIds)
                {
                    var result = await conn.GetStreamMetadataAsync(id);

                    if (!result.IsStreamDeleted)
                    {
                        undeletedStreamIds.Add(id);
                    }
                }
                return(undeletedStreamIds);
            }
        }
        public async Task setting_metadata_few_times_returns_last_metadata_info()
        {
            const string stream   = "setting_metadata_few_times_returns_last_metadata_info";
            var          metadata =
                StreamMetadata.Create(17, TimeSpan.FromSeconds(0xDEADBEEF), 10, TimeSpan.FromSeconds(0xABACABA));
            await _connection.SetStreamMetadataAsync(stream, ExpectedVersion.NoStream, metadata);

            var meta = await _connection.GetStreamMetadataAsync(stream);

            Assert.AreEqual(stream, meta.Stream);
            Assert.AreEqual(false, meta.IsStreamDeleted);
            Assert.AreEqual(0, meta.MetastreamVersion);
            Assert.AreEqual(metadata.MaxCount, meta.StreamMetadata.MaxCount);
            Assert.AreEqual(metadata.MaxAge, meta.StreamMetadata.MaxAge);
            Assert.AreEqual(metadata.TruncateBefore, meta.StreamMetadata.TruncateBefore);
            Assert.AreEqual(metadata.CacheControl, meta.StreamMetadata.CacheControl);

            metadata = StreamMetadata.Create(37, TimeSpan.FromSeconds(0xBEEFDEAD), 24,
                                             TimeSpan.FromSeconds(0xDABACABAD));
            await _connection.SetStreamMetadataAsync(stream, 0, metadata);

            meta = await _connection.GetStreamMetadataAsync(stream);

            Assert.AreEqual(stream, meta.Stream);
            Assert.AreEqual(false, meta.IsStreamDeleted);
            Assert.AreEqual(1, meta.MetastreamVersion);
            Assert.AreEqual(metadata.MaxCount, meta.StreamMetadata.MaxCount);
            Assert.AreEqual(metadata.MaxAge, meta.StreamMetadata.MaxAge);
            Assert.AreEqual(metadata.TruncateBefore, meta.StreamMetadata.TruncateBefore);
            Assert.AreEqual(metadata.CacheControl, meta.StreamMetadata.CacheControl);
        }
Beispiel #12
0
        public async Task WriteMetadata(string stream, int?maxCount = null, int?truncateBefore = null, TimeSpan?maxAge = null,
                                        TimeSpan?cacheControl       = null, bool?frozen = null, Guid?owner = null)
        {
            Logger.Write(LogLevel.Debug, () => $"Writing metadata to stream [{stream}] [ {nameof(maxCount)}: {maxCount}, {nameof(maxAge)}: {maxAge}, {nameof(cacheControl)}: {cacheControl}, {nameof(frozen)}: {frozen} ]");

            var existing = await _client.GetStreamMetadataAsync(stream).ConfigureAwait(false);

            if ((existing.StreamMetadata?.CustomKeys.Contains("frozen") ?? false) &&
                existing.StreamMetadata?.GetValue <string>("owner") != Defaults.Instance.ToString())
            {
                FrozenExceptions.Mark();
                throw new VersionException("Stream is frozen - we are not the owner");
            }
            if (frozen.HasValue && frozen == false && (
                    existing.StreamMetadata == null ||
                    (existing.StreamMetadata?.CustomKeys.Contains("frozen") ?? false) == false ||
                    existing.StreamMetadata?.GetValue <string>("owner") != Defaults.Instance.ToString()))
            {
                FrozenExceptions.Mark();
                throw new FrozenException();
            }

            // If we are trying to freeze the stream that we've already frozen (to prevent multiple threads from attempting to process the same frozen data)
            if (frozen.HasValue && frozen == true && (existing.StreamMetadata?.CustomKeys.Contains("frozen") ?? false) &&
                existing.StreamMetadata?.GetValue <string>("owner") == Defaults.Instance.ToString())
            {
                FrozenExceptions.Mark();
                throw new FrozenException();
            }

            var metadata = StreamMetadata.Build();

            if ((maxCount ?? existing.StreamMetadata?.MaxCount).HasValue)
            {
                metadata.SetMaxCount((maxCount ?? existing.StreamMetadata?.MaxCount).Value);
            }
            if ((truncateBefore ?? existing.StreamMetadata?.TruncateBefore).HasValue)
            {
                metadata.SetTruncateBefore((truncateBefore ?? existing.StreamMetadata?.TruncateBefore).Value);
            }
            if ((maxAge ?? existing.StreamMetadata?.MaxAge).HasValue)
            {
                metadata.SetMaxAge((maxAge ?? existing.StreamMetadata?.MaxAge).Value);
            }
            if ((cacheControl ?? existing.StreamMetadata?.CacheControl).HasValue)
            {
                metadata.SetCacheControl((cacheControl ?? existing.StreamMetadata?.CacheControl).Value);
            }

            if (frozen.HasValue && frozen == true)
            {
                metadata.SetCustomProperty("frozen", DateTime.UtcNow.ToUnixTime());
            }
            if (owner.HasValue)
            {
                metadata.SetCustomProperty("owner", Defaults.Instance.ToString());
            }

            try
            {
                await _client.SetStreamMetadataAsync(stream, existing.MetastreamVersion, metadata).ConfigureAwait(false);
            }
            catch (WrongExpectedVersionException e)
            {
                throw new VersionException(e.Message, e);
            }
            catch (CannotEstablishConnectionException e)
            {
                throw new PersistenceException(e.Message, e);
            }
            catch (OperationTimedOutException e)
            {
                throw new PersistenceException(e.Message, e);
            }
            catch (EventStoreConnectionException e)
            {
                throw new PersistenceException(e.Message, e);
            }
        }
Beispiel #13
0
 void AssertEventStoreAvailable(IEventStoreConnection Connection)
 => _ = Connection.GetStreamMetadataAsync("$ce-Any").Result;
Beispiel #14
0
        public void setting_metadata_few_times_returns_last_metadata_info()
        {
            var metadata = StreamMetadata.Create(17, TimeSpan.FromSeconds(0xDEADBEEF), 10, TimeSpan.FromSeconds(0xABACABA));

            _connection.SetStreamMetadataAsync(_stream, ExpectedVersion.Any, metadata).Wait();

            var meta = _connection.GetStreamMetadataAsync(_stream).Result;

            Assert.AreEqual(_stream, meta.Stream);
            Assert.AreEqual(false, meta.IsStreamDeleted);
            Assert.AreEqual(0, meta.MetastreamVersion);
            Assert.AreEqual(metadata.MaxCount, meta.StreamMetadata.MaxCount);
            Assert.AreEqual(metadata.MaxAge, meta.StreamMetadata.MaxAge);
            Assert.AreEqual(metadata.TruncateBefore, meta.StreamMetadata.TruncateBefore);
            Assert.AreEqual(metadata.CacheControl, meta.StreamMetadata.CacheControl);

            metadata = StreamMetadata.Create(37, TimeSpan.FromSeconds(0xBEEFDEAD), 24, TimeSpan.FromSeconds(0xDABACABAD));
            _connection.SetStreamMetadataAsync(_stream, 0, metadata).Wait();

            meta = _connection.GetStreamMetadataAsync(_stream).Result;
            Assert.AreEqual(_stream, meta.Stream);
            Assert.AreEqual(false, meta.IsStreamDeleted);
            Assert.AreEqual(1, meta.MetastreamVersion);
            Assert.AreEqual(metadata.MaxCount, meta.StreamMetadata.MaxCount);
            Assert.AreEqual(metadata.MaxAge, meta.StreamMetadata.MaxAge);
            Assert.AreEqual(metadata.TruncateBefore, meta.StreamMetadata.TruncateBefore);
            Assert.AreEqual(metadata.CacheControl, meta.StreamMetadata.CacheControl);
        }
Beispiel #15
0
        public async Task <T> GetStreamMetadata <T>(string id, string key)
        {
            var streamMetadata = await _connection.GetStreamMetadataAsync(id);

            return(streamMetadata.StreamMetadata.GetValue <string>(key).ToObject <T>());
        }