public async ValueTask <SubscriptionGap> GetSubscriptionGap(CancellationToken cancellationToken)
    {
        using var activity = EventuousDiagnostics.ActivitySource
                             .StartActivity(ActivityKind.Internal)
                             ?.SetTag("stream", "$all");

        try {
            var read = _eventStoreClient.ReadAllAsync(
                Direction.Backwards,
                Position.End,
                1,
                cancellationToken: cancellationToken
                );

            var events = await read.ToArrayAsync(cancellationToken).NoContext();

            var last = _getLast();

            activity?.SetActivityStatus(ActivityStatus.Ok());

            return(new SubscriptionGap(
                       _subscriptionId,
                       events[0].Event.Position.CommitPosition - last?.Position ?? 0,
                       DateTime.UtcNow - events[0].Event.Created
                       ));
        }
        catch (Exception e) {
            activity?.SetActivityStatus(ActivityStatus.Error(e));
            throw;
        }
    }
 private void ReadAllResolvingLinkTos(EventStoreClient client, CancellationToken cancellationToken)
 {
     #region read-from-all-stream-resolving-link-Tos
     var result = client.ReadAllAsync(
         Direction.Forwards,
         Position.Start,
         resolveLinkTos: true,
         cancellationToken: cancellationToken);
     #endregion read-from-all-stream-resolving-link-Tos
 }
 private void ReadAllOverridingUserCredentials(EventStoreClient client, CancellationToken cancellationToken)
 {
     #region read-all-overriding-user-credentials
     var result = client.ReadAllAsync(
         Direction.Forwards,
         Position.Start,
         userCredentials: new UserCredentials("admin", "changeit"),
         cancellationToken: cancellationToken);
     #endregion read-all-overriding-user-credentials
 }
        private static async Task FilteringOutSystemEvents(EventStoreClient client)
        {
            var events = client.ReadAllAsync(Direction.Forwards, Position.Start);

            await foreach (var e in events)
            {
                if (!e.Event.EventType.StartsWith("$"))
                {
                    Console.WriteLine(Encoding.UTF8.GetString(e.Event.Data.ToArray()));
                }
            }
        }
Esempio n. 5
0
        /// <summary>
        /// List streams
        /// </summary>
        public static async Task <IEnumerable <string> > GetStreams(this EventStoreClient client)
        {
            IList <string> list = new List <string>();

            await foreach (var @event in client.ReadAllAsync(Direction.Forwards, Position.Start))
            {
                if (!list.Contains(@event.OriginalStreamId))
                {
                    list.Add(@event.OriginalStreamId);
                }
            }

            return(list);
        }
        private static async Task ReadFromAllStreamBackwards(EventStoreClient client)
        {
            #region read-from-all-stream-backwards
            var events = client.ReadAllAsync(
                Direction.Backwards, Position.End);
            #endregion read-from-all-stream-backwards

            #region read-from-all-stream-iterate
            await foreach (var e in events)
            {
                Console.WriteLine(Encoding.UTF8.GetString(e.Event.Data.ToArray()));
            }
            #endregion read-from-all-stream-iterate
        }
Esempio n. 7
0
        public async Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken token = default)
        {
            try
            {
                await _client
                .ReadAllAsync(Direction.Forwards, Position.Start, maxCount : 1, cancellationToken : token)
                .FirstOrDefaultAsync(token);
            }
            catch (Exception e)
            {
                return(new HealthCheckResult(context.Registration.FailureStatus, exception: e));
            }

            return(HealthCheckResult.Healthy());
        }
Esempio n. 8
0
        public static async Task CleanUp(String prefix, EventStoreClientSettings settings)
        {
            if (settings == null)
            {
                settings = EventStoreClientSettings.Create("esdb://127.0.0.1:2113?tls=false");
            }

            var client = new EventStoreClient(settings);

            var result = client.ReadAllAsync(Direction.Backwards, Position.End);
            HashSet <String> streamsToDelete = new HashSet <string>(await result.Where(x => x.OriginalStreamId.StartsWith($"{prefix}-")).Select(x => x.OriginalStreamId).ToListAsync());

            foreach (var item in streamsToDelete)
            {
                await client.TombstoneAsync(item, StreamState.Any);
            }
        }
        private static async Task IgnoreSystemEvents(EventStoreClient client)
        {
            #region ignore-system-events
            var events = client.ReadAllAsync(
                Direction.Forwards, Position.Start);

            await foreach (var e in events)
            {
                if (e.Event.EventType.StartsWith("$"))
                {
                    continue;
                }

                Console.WriteLine(Encoding.UTF8.GetString(e.Event.Data.ToArray()));
            }
            #endregion ignore-system-events
        }
Esempio n. 10
0
        public static IApplicationBuilder UseAllStream(this IApplicationBuilder builder, EventStoreClient eventStore)
        {
            return(builder.MapMethods("/stream", (HttpMethod.Get, GetStream)));

            async ValueTask <Response> GetStream(HttpContext context)
            {
                var embedPayload          = context.Request.GetEmbedPayload();
                var readDirection         = context.Request.GetReadDirection();
                var fromPositionInclusive = context.Request.GetPosition(readDirection);
                var maxCount = context.Request.GetMaxCount();

                var events = await eventStore
                             .ReadAllAsync(readDirection, fromPositionInclusive, maxCount,
                                           resolveLinkTos : false, userCredentials : context.GetUserCredentials(),
                                           cancellationToken : context.RequestAborted)
                             .OrderByDescending(e => e.OriginalEvent.Position)
                             .ToArrayAsync(context.RequestAborted);

                return(new HALResponse(AllStreamRepresentation.Instance,
                                       new AllStreamResource(readDirection, fromPositionInclusive, maxCount, embedPayload, events)));
            }
        }
 public IAsyncEnumerable <ResolvedEvent> ReadAllAsync(Direction direction, Position position, ulong maxCount,
                                                      Action <EventStoreClientOperationOptions> configureOperationOptions = null, bool resolveLinkTos = false, FilterOptions filterOptions = null,
                                                      UserCredentials userCredentials = null, CancellationToken cancellationToken = new CancellationToken())
 {
     return(Client.ReadAllAsync(direction, position, maxCount, configureOperationOptions, resolveLinkTos, filterOptions, userCredentials, cancellationToken));
 }
 public IAsyncEnumerable <ResolvedEvent> Get()
 {
     return(_eventStoreClient.ReadAllAsync(Direction.Forwards, Position.Start));
 }
Esempio n. 13
0
        public async Task ReadEvents(
            Shared.Position fromPosition, Func <BaseOriginalEvent, ValueTask> next, CancellationToken cancellationToken
            )
        {
            var sequence     = 0;
            var lastPosition = 0L;

            _log.Info("Starting gRPC reader");

            await _realtime.Start();

            var read = _client.ReadAllAsync(
                Direction.Forwards,
                new Position(
                    fromPosition.EventPosition,
                    fromPosition.EventPosition
                    ),
                cancellationToken: cancellationToken
                );

            var enumerator = read.GetAsyncEnumerator(cancellationToken);

            do
            {
                using var activity = new Activity("read");
                activity.Start();

                var hasValue = await Metrics.Measure(
                    () => enumerator.MoveNextAsync(cancellationToken),
                    ReplicationMetrics.ReadsHistogram,
                    ReplicationMetrics.ReadErrorsCount
                    ).ConfigureAwait(false);

                if (!hasValue)
                {
                    break;
                }

                var evt = enumerator.Current;
                lastPosition = (long)(evt.OriginalPosition?.CommitPosition ?? 0);

                _debugLog?.Debug(
                    "gRPC: Read event with id {Id} of type {Type} from {Stream} at {Position}",
                    evt.Event.EventId,
                    evt.Event.EventType,
                    evt.OriginalStreamId,
                    evt.OriginalPosition
                    );

                BaseOriginalEvent originalEvent;

                if (evt.Event.EventType == Predefined.MetadataEventType)
                {
                    if (Encoding.UTF8.GetString(evt.Event.Data.Span) == StreamDeletedBody)
                    {
                        originalEvent = MapStreamDeleted(
                            evt,
                            sequence++,
                            activity
                            );
                    }
                    else
                    {
                        originalEvent = MapMetadata(evt, sequence++, activity);
                    }
                }
                else if (evt.Event.EventType[0] != '$')
                {
                    originalEvent = Map(evt, sequence++, activity);
                }
                else
                {
                    await next(MapIgnored(evt, sequence++, activity)).ConfigureAwait(false);

                    continue;
                }

                await next(originalEvent).ConfigureAwait(false);
            } while (true);

            _log.Info("Reached the end of the stream at {Position}", lastPosition);
        }