Example #1
0
    protected override async ValueTask Subscribe(CancellationToken cancellationToken)
    {
        var settings = Options.SubscriptionSettings ?? new PersistentSubscriptionSettings(Options.ResolveLinkTos);

        try {
            _subscription = await LocalSubscribe(HandleEvent, HandleDrop, cancellationToken).NoContext();
        }
        catch (PersistentSubscriptionNotFoundException) {
            await CreatePersistentSubscription(settings, cancellationToken);

            _subscription = await LocalSubscribe(HandleEvent, HandleDrop, cancellationToken).NoContext();
        }

        void HandleDrop(
            PersistentSubscription __,
            SubscriptionDroppedReason reason,
            Exception?exception
            )
        => Dropped(EsdbMappings.AsDropReason(reason), exception);

        async Task HandleEvent(
            PersistentSubscription subscription,
            ResolvedEvent re,
            int?retryCount,
            CancellationToken ct
            )
        {
            var context = CreateContext(re, ct)
                          .WithItem(ResolvedEventKey, re)
                          .WithItem(SubscriptionKey, subscription);

            try {
                await Handler(context).NoContext();

                LastProcessed = EventPosition.FromContext(context);
                await Ack(context).NoContext();
            }
            catch (Exception e) {
                await Nack(context, e).NoContext();
            }
        }
    }