コード例 #1
0
        private static async Task SubscribeToStream(EventStoreClient client)
        {
            #region subscribe-to-stream
            await client.SubscribeToStreamAsync("some-stream",
                                                async (subscription, evnt, cancellationToken) => {
                Console.WriteLine($"Received event {evnt.OriginalEventNumber}@{evnt.OriginalStreamId}");
                await HandleEvent(evnt);
            });

            #endregion subscribe-to-stream

            #region subscribe-to-stream-from-position
            await client.SubscribeToStreamAsync(
                "some-stream",
                StreamPosition.FromInt64(20),
                EventAppeared);

            #endregion subscribe-to-stream-from-position

            #region subscribe-to-stream-live
            await client.SubscribeToStreamAsync(
                "some-stream",
                StreamPosition.End,
                EventAppeared);

            #endregion subscribe-to-stream-live

            #region subscribe-to-stream-resolving-linktos
            await client.SubscribeToStreamAsync(
                "$et-myEventType",
                StreamPosition.Start,
                EventAppeared,
                resolveLinkTos : true);

            #endregion subscribe-to-stream-resolving-linktos

            #region subscribe-to-stream-subscription-dropped
            var checkpoint = StreamPosition.Start;
            await client.SubscribeToStreamAsync(
                "some-stream",
                checkpoint,
                eventAppeared : async(subscription, evnt, cancellationToken) => {
                await HandleEvent(evnt);
                checkpoint = evnt.OriginalEventNumber;
            },
                subscriptionDropped : ((subscription, reason, exception) => {
                Console.WriteLine($"Subscription was dropped due to {reason}. {exception}");
                if (reason != SubscriptionDroppedReason.Disposed)
                {
                    // Resubscribe if the client didn't stop the subscription
                    Resubscribe(checkpoint);
                }
            }));

            #endregion subscribe-to-stream-subscription-dropped
        }
コード例 #2
0
        public GetEventStoreSubscription(
            IEventSubscriber subscriber,
            EventStoreClient client,
            EventStoreProjectionClient projectionClient,
            IJsonSerializer serializer,
            string?position,
            string?prefix,
            string?streamFilter)
        {
            Task.Run(async() =>
            {
                var ct = cts.Token;

                var streamName = await projectionClient.CreateProjectionAsync(streamFilter);

                async Task OnEvent(StreamSubscription subscription, ResolvedEvent @event,
                                   CancellationToken ct)
                {
                    var storedEvent = Formatter.Read(@event, prefix, serializer);

                    await subscriber.OnEventAsync(this, storedEvent);
                }

                void OnError(StreamSubscription subscription, SubscriptionDroppedReason reason, Exception? ex)
                {
                    if (reason != SubscriptionDroppedReason.Disposed &&
                        reason != SubscriptionDroppedReason.SubscriberError)
                    {
                        ex ??= new InvalidOperationException($"Subscription closed with reason {reason}.");

                        subscriber.OnErrorAsync(this, ex);
                    }
                }

                if (!string.IsNullOrWhiteSpace(position))
                {
                    var streamPosition = position.ToPosition(true);

                    subscription = await client.SubscribeToStreamAsync(streamName, streamPosition,
                                                                       OnEvent, true,
                                                                       OnError,
                                                                       cancellationToken: ct);
                }
                else
                {
                    subscription = await client.SubscribeToStreamAsync(streamName,
                                                                       OnEvent, true,
                                                                       OnError,
                                                                       cancellationToken: ct);
                }
            }, cts.Token);
        }
コード例 #3
0
        private async Task SubscribeToStream()
        {
            var checkpoint = checkpointProvider.Get();

            if (checkpoint.HasValue)
            {
                subscription = await client.SubscribeToStreamAsync(projection.Stream, new StreamPosition(checkpoint.Value), OnEvent, true, OnSubscriptionDropped);
            }
            else
            {
                subscription = await client.SubscribeToStreamAsync(projection.Stream, OnEvent, true, OnSubscriptionDropped);
            }
        }
コード例 #4
0
        public async Task <IStreamSubscription> SubscribeToStreamAsync(string streamName, Func <IStreamSubscription, ResolvedEvent, CancellationToken, Task> eventAppeared,
                                                                       bool resolveLinkTos = false,
                                                                       Action <IStreamSubscription, SubscriptionDroppedReason, Exception> subscriptionDropped = null, Action <EventStoreClientOperationOptions> configureOperationOptions = null, UserCredentials userCredentials = null,
                                                                       CancellationToken cancellationToken = new CancellationToken())
        {
            HttpStreamSubscription subscription = new HttpStreamSubscription();

            return(subscription.WriteThough(await Client.SubscribeToStreamAsync(streamName,
                                                                                async(s, r, c) => eventAppeared?.Invoke(subscription.WriteThough(s), r, c),
                                                                                resolveLinkTos,
                                                                                (s, r, e) => subscriptionDropped?.Invoke(subscription.WriteThough(s), r, e),
                                                                                configureOperationOptions, userCredentials, cancellationToken)));
        }
コード例 #5
0
    public async Task Start()
    {
        var position = await _checkpointStore.GetCheckpoint();

        _subscription = _isAllStream
            ? await _client.SubscribeToAllAsync(
            GetAllStreamPosition(),
            EventAppeared,
            subscriptionDropped : SubscriptionDropped)
            : await _client.SubscribeToStreamAsync(
            _streamName,
            GetStreamPosition(),
            EventAppeared
            );

        FromAll GetAllStreamPosition()
        => position.HasValue
                ? FromAll.After(new Position(position.Value, position.Value))
                : FromAll.Start;

        FromStream GetStreamPosition()
        => position.HasValue
                ? FromStream.After(position.Value)
                : FromStream.Start;
    }
コード例 #6
0
 public async Task Start()
 {
     _subscription = _isAllStream
         ? await _client.SubscribeToAllAsync(
         FromAll.Start,
         EventAppeared)
         : await _client.SubscribeToStreamAsync(
         _streamName,
         FromStream.Start,
         EventAppeared
         );
 }
コード例 #7
0
 protected override Task ExecuteAsync(CancellationToken stoppingToken)
 {
     _logger.LogInformation($"PullRequestCommentsProjector started!");
     stoppingToken.Register(() =>
                            _logger.LogInformation("PullRequestCommentsProjector is stopping!"));
     return(_eventStore.SubscribeToStreamAsync(
                $"$ce-{PullRequestCommentStreamName.CATEGORY}",
                HandleEvent,
                subscriptionDropped: SubscriptionDropped,
                resolveLinkTos: true,
                cancellationToken: stoppingToken
                ));
 }
コード例 #8
0
        /// <summary>
        /// Event Store Initialize (read events and subscribe at the end)
        /// </summary>
        private async Task <bool> Initialize(string stream)
        {
            var _init = _position;

            try
            {
                var ec_stream = _client.ReadStreamAsync(
                    Direction.Forwards, stream,
                    StreamPosition.FromInt64(_position),
                    maxCount: 100
                    );

                if (await ec_stream.ReadState == ReadState.StreamNotFound)
                {
                    await _client.SubscribeToStreamAsync(stream, SubscribeReturn);

                    return(false);
                }

                foreach (var vnt in ec_stream.ToEnumerable().AsParallel())
                {
                    await SubscribeReturn(null, vnt, CancellationToken.None);
                }
                await ec_stream.DisposeAsync();
            }
            catch { }

            if (_init == _position)
            {
                await _client.SubscribeToStreamAsync(stream, StreamPosition.FromInt64(_position), SubscribeReturn);

                return(false);
            }

            return(true);
        }
コード例 #9
0
        public static async Task WhenFruitGrabbed()
        {
            await _client.SubscribeToStreamAsync("$et-FruitGrabbedEvent", StreamPosition.End,
                                                 async (subscription, evnt, cancellationToken) =>
            {
                try
                {
                    var e = JsonConvert.DeserializeObject <FruitGrabbedEvent>(Encoding.UTF8.GetString(evnt.Event.Data.Span));

                    await new EatFruitCommandHandler().Handle(e.Id);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error in subscr. " + e.Message);
                }
            }, true);
        }
コード例 #10
0
        //TODO Add possiblity to register notification for given users for selected authors and save it to database
        //TODO When new book arived, check for notifications registrations in databse and send notificcation using appropriate channel
        static void Main(string[] args)
        {
            const string stream      = "bookstore-newbook-stream";
            const int    defaultPort = 2113;

            var settings = EventStoreClientSettings.Create($"esdb://127.0.0.1:{defaultPort}?Tls=false");

            using (var client = new EventStoreClient(settings))
            {
                client.SubscribeToStreamAsync(
                    stream,
                    StreamPosition.End,
                    EventArrived);

                Console.WriteLine("Press any key to close...");
                Console.ReadLine();
            }
        }
コード例 #11
0
        static void Main(string[] args)
        {
            const string stream = "Package-delivery-stream";

            var settings = EventStoreClientSettings
                           .Create("esdb://127.0.0.1:2113?tls=false");

            using (var client = new EventStoreClient(settings))
            {
                client.SubscribeToStreamAsync(
                    stream,
                    StreamPosition.End,
                    EventArrived);

                Console.WriteLine("Press any key to close...");
                Console.ReadLine();
            }
        }
コード例 #12
0
ファイル: Program.cs プロジェクト: PawelSzatkowski/UPSik
        static void Main(string[] args)
        {
            const string stream      = "UPSik-package_delivered-stream";
            const int    defaultPort = 2113;

            var settings = EventStoreClientSettings.Create($"esdb://127.0.0.1:{defaultPort}?Tls=false");

            using (var client = new EventStoreClient(settings))
            {
                client.SubscribeToStreamAsync(
                    stream,
                    StreamPosition.End,
                    EventArrived);

                Console.WriteLine("Awaiting delivery confirmation. Press any key + enter to exit app.");
                Console.WriteLine();
                Console.ReadLine();
            }
        }
コード例 #13
0
 public async Task Start()
 {
     await _client.SubscribeToStreamAsync(_tenantPrefix + _streamName, FromStream.End, EventAppeared,
                                          subscriptionDropped : SubscriptionDropped);
 }
コード例 #14
0
        protected override async Task <EventSubscription> Subscribe(
            Checkpoint checkpoint,
            CancellationToken cancellationToken
            )
        {
            var subTask = checkpoint.Position == null
                ? EventStoreClient.SubscribeToStreamAsync(
                _options.StreamName,
                HandleEvent,
                _options.ResolveLinkTos,
                HandleDrop,
                _options.ConfigureOperation,
                _options.Credentials,
                cancellationToken
                )
                : EventStoreClient.SubscribeToStreamAsync(
                _options.StreamName,
                StreamPosition.FromInt64((long)checkpoint.Position),
                HandleEvent,
                _options.ResolveLinkTos,
                HandleDrop,
                _options.ConfigureOperation,
                _options.Credentials,
                cancellationToken
                );

            var sub = await subTask.Ignore();

            return(new EventSubscription(SubscriptionId, new Stoppable(() => sub.Dispose())));

            async Task HandleEvent(EventStore.Client.StreamSubscription _, ResolvedEvent re, CancellationToken ct)
            {
                await Handler(AsReceivedEvent(re), ct).Ignore();
            }

            void HandleDrop(EventStore.Client.StreamSubscription _, SubscriptionDroppedReason reason, Exception?ex)
            => Dropped(EsdbMappings.AsDropReason(reason), ex);

            ReceivedEvent AsReceivedEvent(ResolvedEvent re)
            {
                var evt = DeserializeData(
                    re.Event.ContentType,
                    re.Event.EventType,
                    re.Event.Data,
                    re.Event.EventStreamId,
                    re.Event.EventNumber
                    );

                return(new ReceivedEvent(
                           re.Event.EventId.ToString(),
                           re.Event.EventType,
                           re.Event.ContentType,
                           re.Event.Position.CommitPosition,
                           re.Event.EventNumber,
                           re.Event.EventStreamId,
                           re.Event.EventNumber,
                           re.Event.Created,
                           evt
                           // re.Event.Metadata
                           ));
            }
        }
コード例 #15
0
        public async override Task OnActivateAsync()
        {
            await _client.SubscribeToStreamAsync(InterfaceConst.PSHello, SubscribeReturn);

            await base.OnActivateAsync();
        }