Example #1
0
        public void ImplicitConversionFromStreamPositionReturnsExpectedResult()
        {
            const ulong value  = 0UL;
            ulong       actual = new StreamPosition(value);

            Assert.Equal(value, actual);
        }
Example #2
0
        public void SubtractionOperator()
        {
            var sut = new StreamPosition(1);

            Assert.Equal(new StreamPosition(0), sut - 1);
            Assert.Equal(new StreamPosition(0), 1 - sut);
        }
Example #3
0
        public void ImplicitConversionToStreamPositionReturnsExpectedResult()
        {
            const ulong    value    = 0UL;
            var            expected = new StreamPosition(value);
            StreamPosition actual   = value;

            Assert.Equal(expected, actual);
        }
Example #4
0
        public static StreamMetadataResult Create(string streamName, StreamPosition revision,
                                                  StreamMetadata metadata)
        {
            if (metadata == null)
            {
                throw new ArgumentNullException(nameof(metadata));
            }

            return(new StreamMetadataResult(streamName, revision, metadata));
        }
Example #5
0
 public EventRecord(
     string eventStreamId,
     Uuid eventId,
     StreamPosition eventNumber,
     Position position,
     IDictionary <string, string> metadata,
     ReadOnlyMemory <byte> data,
     ReadOnlyMemory <byte> customMetadata)
 {
     EventStreamId = eventStreamId;
     EventId       = eventId;
     EventNumber   = eventNumber;
     Position      = position;
     Data          = data;
     Metadata      = customMetadata;
     EventType     = metadata[Constants.Metadata.Type];
     Created       = Convert.ToInt64(metadata[Constants.Metadata.Created]).FromTicksSinceEpoch();
     ContentType   = metadata[Constants.Metadata.ContentType];
 }
        public PersistentSubscriptionSettings(bool resolveLinkTos      = false, StreamPosition?startFrom = null,
                                              bool extraStatistics     = false, TimeSpan?messageTimeout  = null, int maxRetryCount    = 500,
                                              int liveBufferSize       = 500, int readBatchSize          = 10, int historyBufferSize  = 20,
                                              TimeSpan?checkPointAfter = null, int minCheckPointCount    = 10, int maxCheckPointCount = 1000,
                                              int maxSubscriberCount   = 0, string namedConsumerStrategy = SystemConsumerStrategies.RoundRobin)
        {
            messageTimeout ??= TimeSpan.FromSeconds(30);
            checkPointAfter ??= TimeSpan.FromSeconds(2);
            startFrom ??= StreamPosition.End;

            if (messageTimeout.Value < TimeSpan.Zero || messageTimeout.Value.TotalMilliseconds > int.MaxValue)
            {
                throw new ArgumentOutOfRangeException(
                          nameof(messageTimeout),
                          $"{nameof(messageTimeout)} must be greater than {TimeSpan.Zero} and less than or equal to {TimeSpan.FromMilliseconds(int.MaxValue)}");
            }

            if (checkPointAfter.Value < TimeSpan.Zero || checkPointAfter.Value.TotalMilliseconds > int.MaxValue)
            {
                throw new ArgumentOutOfRangeException(
                          nameof(checkPointAfter),
                          $"{nameof(checkPointAfter)} must be greater than {TimeSpan.Zero} and less than or equal to {TimeSpan.FromMilliseconds(int.MaxValue)}");
            }

            ResolveLinkTos        = resolveLinkTos;
            StartFrom             = startFrom.Value;
            ExtraStatistics       = extraStatistics;
            MessageTimeout        = messageTimeout.Value;
            MaxRetryCount         = maxRetryCount;
            LiveBufferSize        = liveBufferSize;
            ReadBatchSize         = readBatchSize;
            HistoryBufferSize     = historyBufferSize;
            CheckPointAfter       = checkPointAfter.Value;
            MinCheckPointCount    = minCheckPointCount;
            MaxCheckPointCount    = maxCheckPointCount;
            MaxSubscriberCount    = maxSubscriberCount;
            NamedConsumerStrategy = namedConsumerStrategy;
        }
Example #7
0
        public void Equality()
        {
            var sut = new StreamPosition(1);

            Assert.Equal(new StreamPosition(1), sut);
        }
Example #8
0
 public void AdditionOutOfBoundsThrows(StreamPosition StreamPosition, ulong operand)
 {
     Assert.Throws <OverflowException>(() => StreamPosition + operand);
     Assert.Throws <OverflowException>(() => operand + StreamPosition);
 }
Example #9
0
        public void InequalityOperator()
        {
            var sut = new StreamPosition(1);

            Assert.True(new StreamPosition(2) != sut);
        }
 public static StreamMetadataResult Create(string streamName, StreamPosition revision,
                                           StreamMetadata metadata) => new StreamMetadataResult(streamName, revision, metadata);
Example #11
0
 public void Comparability(StreamPosition left, StreamPosition right, int expected)
 => Assert.Equal(expected, left.CompareTo(right));
Example #12
0
        public void FromStreamPositionReturnsExpectedResult()
        {
            var result = StreamPosition.FromStreamRevision(new StreamRevision(0));

            Assert.Equal(new StreamPosition(0), result);
        }
        public override StreamMetadata Read(ref Utf8JsonReader reader, Type typeToConvert,
                                            JsonSerializerOptions options)
        {
            int?           maxCount = null;
            TimeSpan?      maxAge = null, cacheControl = null;
            StreamPosition?truncateBefore = null;
            StreamAcl?     acl            = null;

            using var stream = new MemoryStream();
            using var customMetadataWriter = new Utf8JsonWriter(stream);

            if (reader.TokenType != JsonTokenType.StartObject)
            {
                throw new InvalidOperationException();
            }

            customMetadataWriter.WriteStartObject();

            while (reader.Read())
            {
                if (reader.TokenType == JsonTokenType.EndObject)
                {
                    break;
                }

                if (reader.TokenType != JsonTokenType.PropertyName)
                {
                    throw new InvalidOperationException();
                }

                switch (reader.GetString())
                {
                case SystemMetadata.MaxCount:
                    if (!reader.Read())
                    {
                        throw new InvalidOperationException();
                    }

                    maxCount = reader.GetInt32();
                    break;

                case SystemMetadata.MaxAge:
                    if (!reader.Read())
                    {
                        throw new InvalidOperationException();
                    }

                    var int64 = reader.GetInt64();
                    maxAge = TimeSpan.FromSeconds(int64);
                    break;

                case SystemMetadata.CacheControl:
                    if (!reader.Read())
                    {
                        throw new InvalidOperationException();
                    }

                    cacheControl = TimeSpan.FromSeconds(reader.GetInt64());
                    break;

                case SystemMetadata.TruncateBefore:
                    if (!reader.Read())
                    {
                        throw new InvalidOperationException();
                    }

                    var value = reader.GetInt64();
                    truncateBefore = value == long.MaxValue
                                                        ? StreamPosition.End
                                                        : StreamPosition.FromInt64(value);
                    break;

                case SystemMetadata.Acl:
                    if (!reader.Read())
                    {
                        throw new InvalidOperationException();
                    }

                    acl = StreamAclJsonConverter.Instance.Read(ref reader, typeof(StreamAcl), options);
                    break;

                default:
                    customMetadataWriter.WritePropertyName(reader.GetString() !);
                    reader.Read();
                    switch (reader.TokenType)
                    {
                    case JsonTokenType.Comment:
                        customMetadataWriter.WriteCommentValue(reader.GetComment());
                        break;

                    case JsonTokenType.String:
                        customMetadataWriter.WriteStringValue(reader.GetString());
                        break;

                    case JsonTokenType.Number:
                        customMetadataWriter.WriteNumberValue(reader.GetDouble());
                        break;

                    case JsonTokenType.True:
                    case JsonTokenType.False:
                        customMetadataWriter.WriteBooleanValue(reader.GetBoolean());
                        break;

                    case JsonTokenType.Null:
                        reader.Read();
                        customMetadataWriter.WriteNullValue();
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }

                    break;
                }
            }

            customMetadataWriter.WriteEndObject();
            customMetadataWriter.Flush();

            stream.Position = 0;

            return(new StreamMetadata(maxCount, maxAge, truncateBefore, cacheControl, acl,
                                      JsonDocument.Parse(stream)));
        }
Example #14
0
        private async Task <TAggregate> GetByIdOrDefaultAsync <TAggregate>(string aggregateId, int version)
            where TAggregate : class, IAggregateRoot, new()
        {
            if (version <= 0)
            {
                throw new InvalidOperationException("Cannot get version <= 0");
            }

            var        streamName = $"{typeof(TAggregate).Name}:{aggregateId}";
            TAggregate aggregate  = new TAggregate
            {
                Version = -1
            };

            RedisValue value = await Policies.RedisValueFallbackPolicy.ExecuteAsync(() => _cache.StringGetAsync(streamName));

            if (value.HasValue)
            {
                aggregate = JsonSerializer.Deserialize <TAggregate>(value);
            }

            long sliceStart = aggregate.Version + 1;

            EventStoreClient.ReadStreamResult stream = _eventStoreClient.ReadStreamAsync(Direction.Forwards, streamName, StreamPosition.FromInt64(sliceStart));

            if (await stream.ReadState == ReadState.StreamNotFound)
            {
                return(null);
            }

            await foreach (var @event in stream)
            {
                object eventObject      = DeserializeEvent(@event.Event.Metadata, @event.Event.Data);
                Type   applyType        = typeof(IApply <>).MakeGenericType(eventObject.GetType());
                var    isAssignableFrom = applyType.IsAssignableFrom(aggregate.GetType());
                if (isAssignableFrom)
                {
                    ((dynamic)aggregate).Apply((dynamic)eventObject);
                }
                aggregate.Version++;
            }

            aggregate.Context = _context;
            return(aggregate);
        }
Example #15
0
 public void SubtractionOutOfBoundsThrows(StreamPosition streamPosition, ulong operand)
 {
     Assert.Throws <OverflowException>(() => streamPosition - operand);
     Assert.Throws <OverflowException>(() => (ulong)streamPosition - new StreamPosition(operand));
 }
Example #16
0
 public static StreamRevision FromStreamPosition(StreamPosition position) => position.ToUInt64() switch
 {
Example #17
0
        public void Inequality()
        {
            var sut = new StreamPosition(1);

            Assert.NotEqual(new StreamPosition(2), sut);
        }
        private static CreateReq.Types.StreamOptions StreamOptionsForCreateProto(string streamName, StreamPosition position)
        {
            if (position == StreamPosition.Start)
            {
                return(new CreateReq.Types.StreamOptions {
                    StreamIdentifier = streamName,
                    Start = new Empty()
                });
            }

            if (position == StreamPosition.End)
            {
                return(new CreateReq.Types.StreamOptions {
                    StreamIdentifier = streamName,
                    End = new Empty()
                });
            }

            return(new CreateReq.Types.StreamOptions {
                StreamIdentifier = streamName,
                Revision = position.ToUInt64()
            });
        }
        public static StreamPosition ParseStreamPosition(this ReadOnlyMemory <byte> json)
        {
            var checkPoint = json.ParseJson <string>();

            return(StreamPosition.FromInt64(int.Parse(checkPoint)));
        }