예제 #1
0
        public async Task PersistentSubscription_CanBeCreatedAndFilterOutSystemEvent()
        {
            PersistentSubscriptionDetails      persistentSubscriptionDetails = new("$ce-test", "local-1");
            TestDomainEventHandler             eventHandler = new();
            Mock <IDomainEventHandlerResolver> domainEventHandlerResolver = new Mock <IDomainEventHandlerResolver>();

            domainEventHandlerResolver.Setup(d => d.GetDomainEventHandlers(It.IsAny <IDomainEvent>())).Returns(new List <IDomainEventHandler>()
            {
                eventHandler
            });
            InMemoryPersistentSubscriptionsClient persistentSubscriptionsClient = new();
            CancellationToken cancellationToken = CancellationToken.None;

            var persistentSubscription =
                PersistentSubscription.Create(persistentSubscriptionsClient, persistentSubscriptionDetails, domainEventHandlerResolver.Object);

            await persistentSubscription.ConnectToSubscription(cancellationToken);

            persistentSubscription.Connected.ShouldBeTrue();

            String @event = "";

            //Manually add events.
            persistentSubscriptionsClient.WriteEvent(@event, "$", cancellationToken);

            //Crude - but a decent start point
            eventHandler.DomainEvents.Count.ShouldBe(0);
        }
예제 #2
0
        public void Add(PersistentSubscription subscription)
        {
            using (ISession session = _sessionFactory.OpenSession())
                using (ITransaction transaction = session.BeginTransaction())
                {
                    PersistentSubscription existingSubscription = session.QueryOver <PersistentSubscription>()
                                                                  .Where(x => x.BusUri == subscription.BusUri)
                                                                  .Where(x => x.PeerId == subscription.PeerId)
                                                                  .Where(x => x.SubscriptionId == subscription.SubscriptionId)
                                                                  .SingleOrDefault();

                    if (existingSubscription != null)
                    {
                        _log.DebugFormat("Updating: {0}", existingSubscription);

                        existingSubscription.Updated = DateTime.UtcNow;
                        session.Update(existingSubscription);
                    }
                    else
                    {
                        _log.DebugFormat("Adding: {0}", subscription);

                        session.Save(subscription);
                    }

                    transaction.Commit();
                }
        }
예제 #3
0
 static Task DefaultEventProcessingFailureHandler(
     EventStoreClient client,
     PersistentSubscription subscription,
     ResolvedEvent resolvedEvent,
     Exception exception
     )
 => subscription.Nack(PersistentSubscriptionNakEventAction.Retry, exception.Message, resolvedEvent);
예제 #4
0
            protected override async Task Given()
            {
                await Client.CreateToAllAsync(Group,
                                              new PersistentSubscriptionSettings(startFrom : Position.Start, resolveLinkTos : true),
                                              TestCredentials.Root);

                _subscription = await Client.SubscribeToAllAsync(Group,
                                                                 async (subscription, e, retryCount, ct) => {
                    await subscription.Nack(PersistentSubscriptionNakEventAction.Park, "fail", e);

                    if (e.OriginalStreamId.StartsWith("test-") &&
                        Interlocked.Increment(ref _eventReceivedCount) == _events.Length)
                    {
                        _eventsReceived.TrySetResult(true);
                    }
                }, (s, r, e) => {
                    if (e != null)
                    {
                        _eventsReceived.TrySetException(e);
                    }
                },
                                                                 autoAck : false,
                                                                 bufferSize : BufferCount,
                                                                 userCredentials : TestCredentials.Root);
            }
예제 #5
0
            protected override async Task Given()
            {
                foreach (var e in _events)
                {
                    await StreamsClient.AppendToStreamAsync("test-" + Guid.NewGuid(), StreamState.Any, new[] { e });
                }

                await Client.CreateToAllAsync(Group,
                                              new PersistentSubscriptionSettings(startFrom : Position.Start, resolveLinkTos : true),
                                              TestCredentials.Root);

                _subscription = await Client.SubscribeToAllAsync(Group,
                                                                 async(subscription, e, retryCount, ct) => {
                    await subscription.Ack(e);

                    if (e.OriginalStreamId.StartsWith("test-") &&
                        Interlocked.Increment(ref _eventReceivedCount) == _events.Length)
                    {
                        _eventsReceived.TrySetResult(true);
                    }
                }, (s, r, e) => {
                    if (e != null)
                    {
                        _eventsReceived.TrySetException(e);
                    }
                },
                                                                 autoAck : false,
                                                                 bufferSize : BufferCount,
                                                                 userCredentials : TestCredentials.Root);
            }
예제 #6
0
            protected override async Task Given()
            {
                foreach (var e in _events)
                {
                    await StreamsClient.AppendToStreamAsync(Stream, StreamState.Any, new[] { e });
                }

                await Client.CreateAsync(Stream, Group,
                                         new PersistentSubscriptionSettings(startFrom : StreamPosition.Start, resolveLinkTos : true),
                                         TestCredentials.Root);

                _subscription = await Client.SubscribeAsync(Stream, Group,
                                                            (subscription, e, retryCount, ct) => {
                    if (Interlocked.Increment(ref _eventReceivedCount) == _events.Length)
                    {
                        _eventsReceived.TrySetResult(true);
                    }

                    return(Task.CompletedTask);
                }, (s, r, e) => {
                    if (e != null)
                    {
                        _eventsReceived.TrySetException(e);
                    }
                },
                                                            bufferSize : BufferCount,
                                                            userCredentials : TestCredentials.Root);
            }
예제 #7
0
            protected override async Task Given()
            {
                foreach (var @event in CreateTestEvents(10))
                {
                    await StreamsClient.AppendToStreamAsync("non-system-stream-" + Guid.NewGuid(),
                                                            StreamState.Any, new[] { @event });
                }

                await Client.CreateToAllAsync(Group, new PersistentSubscriptionSettings(startFrom : Position.End), TestCredentials.Root);

                _subscription = await Client.SubscribeToAllAsync(Group,
                                                                 (subscription, e, r, ct) => {
                    if (SystemStreams.IsSystemStream(e.OriginalStreamId))
                    {
                        return(Task.CompletedTask);
                    }
                    _firstNonSystemEventSource.TrySetResult(e);
                    return(Task.CompletedTask);
                }, (subscription, reason, ex) => {
                    if (reason != SubscriptionDroppedReason.Disposed)
                    {
                        _firstNonSystemEventSource.TrySetException(ex !);
                    }
                }, TestCredentials.Root);
            }
예제 #8
0
            protected override async Task Given()
            {
                await StreamsClient.AppendToStreamAsync(Stream, StreamState.NoStream, Events);

                await Client.CreateAsync(Stream, Group,
                                         new PersistentSubscriptionSettings(startFrom : StreamPosition.Start), TestCredentials.Root);

                _subscription = await Client.SubscribeAsync(Stream, Group,
                                                            async (subscription, e, r, ct) => {
                    if (r > 4)
                    {
                        _retryCountSource.TrySetResult(r.Value);
                        await subscription.Ack(e.Event.EventId);
                    }
                    else
                    {
                        await subscription.Nack(PersistentSubscriptionNakEventAction.Retry,
                                                "Not yet tried enough times", e);
                    }
                }, autoAck : false, subscriptionDropped : (subscription, reason, ex) => {
                    if (reason != SubscriptionDroppedReason.Disposed)
                    {
                        _retryCountSource.TrySetException(ex !);
                    }
                }, userCredentials : TestCredentials.TestUser1);
            }
        public void Remove(Guid peerId, Uri peerUri, Guid subscriptionId, Uri endpointUri, string messageName, string correlationId)
        {
            var subscription = new PersistentSubscription(_busUri, peerId, peerUri, subscriptionId, endpointUri, messageName,
                correlationId);

            _fiber.Add(() => Remove(subscription));
        }
        public void Add(PersistentSubscription subscription)
        {
            using (ISession session = _sessionFactory.OpenSession())
            using (ITransaction transaction = session.BeginTransaction())
            {
                PersistentSubscription existingSubscription = session.QueryOver<PersistentSubscription>()
                    .Where(x => x.BusUri == subscription.BusUri)
                    .Where(x => x.PeerId == subscription.PeerId)
                    .Where(x => x.SubscriptionId == subscription.SubscriptionId)
                    .SingleOrDefault();

                if (existingSubscription != null)
                {
                    _log.DebugFormat("Updating: {0}", existingSubscription);

                    existingSubscription.Updated = DateTime.UtcNow;
                    session.Update(existingSubscription);
                }
                else
                {
                    _log.DebugFormat("Adding: {0}", subscription);

                    session.Save(subscription);
                }

                transaction.Commit();
            }
        }
예제 #11
0
        public async Task PersistentSubscription_CanBeCreatedAndReceiveEventsMultipleEventHandler()
        {
            PersistentSubscriptionDetails      persistentSubscriptionDetails = new("$ce-test", "local-1");
            TestDomainEventHandler             eventHandler1 = new();
            TestDomainEventHandler             eventHandler2 = new();
            Mock <IDomainEventHandlerResolver> domainEventHandlerResolver = new Mock <IDomainEventHandlerResolver>();

            domainEventHandlerResolver.Setup(d => d.GetDomainEventHandlers(It.IsAny <IDomainEvent>())).Returns(new List <IDomainEventHandler>()
            {
                eventHandler1,
                eventHandler2
            });
            InMemoryPersistentSubscriptionsClient persistentSubscriptionsClient = new();
            CancellationToken cancellationToken = CancellationToken.None;

            var persistentSubscription =
                PersistentSubscription.Create(persistentSubscriptionsClient, persistentSubscriptionDetails, domainEventHandlerResolver.Object);

            await persistentSubscription.ConnectToSubscription(cancellationToken);

            persistentSubscription.Connected.ShouldBeTrue();

            String @event = "{\r\n  \"estateId\": \"4fc2692f-067a-443e-8006-335bf2732248\",\r\n  \"estateName\": \"Demo Estate\"\r\n}\t";

            //Manually add events.
            persistentSubscriptionsClient.WriteEvent(@event, "EstateCreatedEvent", cancellationToken);

            //Crude - but a decent start point
            eventHandler1.DomainEvents.Count.ShouldBe(1);
            eventHandler2.DomainEvents.Count.ShouldBe(1);
        }
        /// <summary>
        /// Event subscription return to execute
        /// </summary>
        /// <param name="ps">Persistent Subscription</param>
        /// <param name="vnt">Resolved Event</param>
        /// <param name="n">Event Number</param>
        /// <param name="ct">Cancellation Token</param>
        /// <returns>true if prime</returns>
        private Task <bool> SubscribeReturn(PersistentSubscription ps, ResolvedEvent vnt, int?n, CancellationToken ct)
        {
            var number = int.Parse(vnt.ToJson());

            return(IsPrime(number));

            //await ps.Ack(new[] { vnt.OriginalEvent.EventId });
        }
 public void Remove(PersistentSubscription subscription)
 {
     using (var session = InternalDocumentStore.OpenSession())
     {
         session.Delete(subscription);
         session.SaveChanges();
     }
 }
        public void Remove(PersistentSubscription subscription)
        {
            _fiber.Add(() =>
                {
                    _subscriptions.Remove(subscription);

                    _log.DebugFormat("SubscriptionStorage.Remove: {0} [{1}]", subscription, _subscriptions.Count);
                });
        }
        private async Task SubscribeReturn(PersistentSubscription ps, ResolvedEvent vnt, int?value, CancellationToken ct)
        {
            var json   = Encoding.UTF8.GetString(vnt.Event.Data.Span);
            var result = JsonSerializer.Deserialize <TestEvent>(json);

            _ = result.ImportantData;

            await ps.Ack(new[] { vnt.Event.EventId });
        }
예제 #16
0
        private async Task OnEvent(PersistentSubscription _, ResolvedEvent resolvedEvent, int?arg3, CancellationToken token)
        {
            if (resolvedEvent.Event.EventType.StartsWith("$"))
            {
                return;
            }

            var eventJson = Encoding.UTF8.GetString(resolvedEvent.Event.Data.ToArray());
            var eventType = Type.GetType($"EventSourced.Simple.Aggregate.Events.{resolvedEvent.Event.EventType}, EventSourced.Simple");
            var @event    = JsonConvert.DeserializeObject(eventJson, eventType);

            await projection.Handle(@event);
        }
예제 #17
0
 protected override async Task When()
 {
     _subscription = await Client.SubscribeAsync(Stream, Group,
                                                 (subscription, e, r, ct) => {
         _firstEventSource.TrySetResult(e);
         return(Task.CompletedTask);
     }, (subscription, reason, ex) => {
         if (reason != SubscriptionDroppedReason.Disposed)
         {
             _firstEventSource.TrySetException(ex !);
         }
     }, TestCredentials.TestUser1);
 }
            protected override async Task When()
            {
                // Force restart of the subscription
                await Client.UpdateAsync(Stream, Group, new PersistentSubscriptionSettings(), TestCredentials.Root);

                await _droppedSource.Task.WithTimeout();

                _secondSubscription = await Client.SubscribeAsync(Stream, Group,
                                                                  eventAppeared : (s, e, r, ct) => {
                    _resumedSource.TrySetResult(e);
                    return(Task.CompletedTask);
                },
                                                                  userCredentials : TestCredentials.Root);

                await StreamsClient.AppendToStreamAsync(Stream, StreamState.Any, CreateTestEvents(1));
            }
            protected override async Task Given()
            {
                await Client.CreateAsync(Stream, Group,
                                         new PersistentSubscriptionSettings(startFrom : new StreamPosition(2)), TestCredentials.Root);

                _subscription = await Client.SubscribeAsync(Stream, Group,
                                                            (subscription, e, r, ct) => {
                    _firstEventSource.TrySetResult(e);
                    return(Task.CompletedTask);
                }, (subscription, reason, ex) => {
                    if (reason != SubscriptionDroppedReason.Disposed)
                    {
                        _firstEventSource.TrySetException(ex !);
                    }
                }, TestCredentials.TestUser1);
            }
예제 #20
0
        public void live_subscription_with_pinned_by_correlation_pushes_events_with_metadata_with_valid_correlation_to_same_client_for_correlation_id()
        {
            var client1Envelope = new FakeEnvelope();
            var client2Envelope = new FakeEnvelope();
            var reader          = new FakeCheckpointReader();

            var sub = new PersistentSubscription(
                PersistentSubscriptionToStreamParamsBuilder.CreateFor("$ce-streamName", "groupName")
                .WithEventLoader(new FakeStreamReader())
                .WithCheckpointReader(reader)
                .WithCheckpointWriter(new FakeCheckpointWriter(x => { }))
                .WithMessageParker(new FakeMessageParker())
                .CustomConsumerStrategy(new PinnedByCorrelationPersistentSubscriptionConsumerStrategy(new XXHashUnsafe()))
                .StartFromCurrent());

            reader.Load(null);
            sub.AddClient(Guid.NewGuid(), Guid.NewGuid(), "connection-1", client1Envelope, 10, "foo", "bar");
            sub.AddClient(Guid.NewGuid(), Guid.NewGuid(), "connection-2", client2Envelope, 10, "foo", "bar");

            CorrelationIdPropertyContext.CorrelationIdProperty = "$correlationId2";

            var metaData1 = Encoding.UTF8.GetBytes(@"{ ""x"": ""x"", ""$correlationId2"": ""1234567890"", ""y"": ""y"" }");

            sub.NotifyLiveSubscriptionMessage(Helper.BuildFakeEventWithMetadata(Guid.NewGuid(), "type", "streamName-1", 0, metaData1));
            sub.NotifyLiveSubscriptionMessage(Helper.BuildFakeEventWithMetadata(Guid.NewGuid(), "type", "streamName-1", 1, metaData1));

            Assert.AreEqual(2, client1Envelope.Replies.Count);
            Assert.AreEqual(0, client2Envelope.Replies.Count);

            sub.NotifyLiveSubscriptionMessage(Helper.BuildFakeEventWithMetadata(Guid.NewGuid(), "type", "streamName-2", 2, metaData1));
            sub.NotifyLiveSubscriptionMessage(Helper.BuildFakeEventWithMetadata(Guid.NewGuid(), "type", "streamName-2", 3, metaData1));

            Assert.AreEqual(4, client1Envelope.Replies.Count);
            Assert.AreEqual(0, client2Envelope.Replies.Count);

            var metaData2 = Encoding.UTF8.GetBytes(@"{ ""$correlationId2"": ""1234567891"", ""y"": ""y"" }");

            sub.NotifyLiveSubscriptionMessage(Helper.BuildFakeEventWithMetadata(Guid.NewGuid(), "type", "streamName-1", 4, metaData2));

            Assert.AreEqual(4, client1Envelope.Replies.Count);
            Assert.AreEqual(1, client2Envelope.Replies.Count);

            sub.NotifyLiveSubscriptionMessage(Helper.BuildFakeEventWithMetadata(Guid.NewGuid(), "type", "streamName-3", 5, metaData2));

            Assert.AreEqual(4, client1Envelope.Replies.Count);
            Assert.AreEqual(2, client2Envelope.Replies.Count);
        }
예제 #21
0
        live_subscription_with_pinned_by_correlation_pushes_events_to_same_client_for_stream_id_for_metadata(byte[] metaData)
        {
            var client1Envelope = new FakeEnvelope();
            var client2Envelope = new FakeEnvelope();
            var reader          = new FakeCheckpointReader();

            var sub = new PersistentSubscription(
                PersistentSubscriptionToStreamParamsBuilder.CreateFor("$ce-streamName", "groupName")
                .WithEventLoader(new FakeStreamReader())
                .WithCheckpointReader(reader)
                .WithCheckpointWriter(new FakeCheckpointWriter(x => { }))
                .WithMessageParker(new FakeMessageParker())
                .CustomConsumerStrategy(new PinnedByCorrelationPersistentSubscriptionConsumerStrategy(new XXHashUnsafe()))
                .StartFromCurrent());

            reader.Load(null);
            sub.AddClient(Guid.NewGuid(), Guid.NewGuid(), "connection-1", client1Envelope, 10, "foo", "bar");
            sub.AddClient(Guid.NewGuid(), Guid.NewGuid(), "connection-2", client2Envelope, 10, "foo", "bar");

            sub.NotifyLiveSubscriptionMessage(
                Helper.BuildFakeEventWithMetadata(Guid.NewGuid(), "type", "streamName-1", 0, metaData));
            sub.NotifyLiveSubscriptionMessage(
                Helper.BuildFakeEventWithMetadata(Guid.NewGuid(), "type", "streamName-1", 1, metaData));

            Assert.AreEqual(2, client1Envelope.Replies.Count);
            Assert.AreEqual(0, client2Envelope.Replies.Count);

            sub.NotifyLiveSubscriptionMessage(
                Helper.BuildFakeEventWithMetadata(Guid.NewGuid(), "type", "streamName-2", 2, metaData));
            sub.NotifyLiveSubscriptionMessage(
                Helper.BuildFakeEventWithMetadata(Guid.NewGuid(), "type", "streamName-2", 3, metaData));

            Assert.AreEqual(2, client1Envelope.Replies.Count);
            Assert.AreEqual(2, client2Envelope.Replies.Count);

            sub.NotifyLiveSubscriptionMessage(
                Helper.BuildFakeEventWithMetadata(Guid.NewGuid(), "type", "streamName-1", 4, metaData));

            Assert.AreEqual(3, client1Envelope.Replies.Count);
            Assert.AreEqual(2, client2Envelope.Replies.Count);

            sub.NotifyLiveSubscriptionMessage(
                Helper.BuildFakeEventWithMetadata(Guid.NewGuid(), "type", "streamName-3", 5, metaData));

            Assert.AreEqual(4, client1Envelope.Replies.Count);
            Assert.AreEqual(2, client2Envelope.Replies.Count);
        }
            protected override async Task Given()
            {
                foreach (var e in _events)
                {
                    await StreamsClient.AppendToStreamAsync("test-" + Guid.NewGuid(), StreamState.Any, new[] { e });
                }

                await Client.CreateToAllAsync(Group,
                                              StreamFilter.Prefix("test"),
                                              new PersistentSubscriptionSettings(
                                                  minCheckPointCount : 5,
                                                  checkPointAfter : TimeSpan.FromSeconds(1),
                                                  startFrom : Position.Start),
                                              TestCredentials.Root);

                _checkPointSubscription = await StreamsClient.SubscribeToStreamAsync(_checkPointStream,
                                                                                     (s, e, ct) => {
                    if (_checkPoints.Count == 0)
                    {
                        _firstCheckPointSource.TrySetResult(e);
                    }
                    else
                    {
                        _secondCheckPointSource.TrySetResult(e);
                    }
                    _checkPoints.Add(e);
                    return(Task.CompletedTask);
                },
                                                                                     userCredentials : TestCredentials.Root);

                _subscription = await Client.SubscribeToAllAsync(Group,
                                                                 eventAppeared : (s, e, r, ct) => {
                    _appearedEvents.Add(e);

                    if (_appearedEvents.Count == _events.Length)
                    {
                        _appeared.TrySetResult(true);
                    }
                    return(Task.CompletedTask);
                },
                                                                 userCredentials : TestCredentials.Root);

                await Task.WhenAll(_appeared.Task, _firstCheckPointSource.Task).WithTimeout();

                FirstCheckPoint = _firstCheckPointSource.Task.Result.Event.Data.ParsePosition();
            }
예제 #23
0
 protected override async Task When()
 {
     _subscription = await Client.SubscribeToAllAsync(Group,
                                                      (subscription, e, r, ct) => {
         if (SystemStreams.IsSystemStream(e.OriginalStreamId))
         {
             return(Task.CompletedTask);
         }
         _firstNonSystemEventSource.TrySetResult(e);
         return(Task.CompletedTask);
     }, (subscription, reason, ex) => {
         if (reason != SubscriptionDroppedReason.Disposed)
         {
             _firstNonSystemEventSource.TrySetException(ex !);
         }
     }, TestCredentials.Root);
 }
예제 #24
0
            protected override async Task Given()
            {
                await StreamsClient.AppendToStreamAsync(Stream, StreamState.NoStream, Events.Take(10));

                await Client.CreateAsync(Stream, Group,
                                         new PersistentSubscriptionSettings(), TestCredentials.Root);

                _subscription = await Client.SubscribeAsync(Stream, Group,
                                                            (subscription, e, r, ct) => {
                    _firstEventSource.TrySetResult(e);
                    return(Task.CompletedTask);
                }, (subscription, reason, ex) => {
                    if (reason != SubscriptionDroppedReason.Disposed)
                    {
                        _firstEventSource.TrySetException(ex !);
                    }
                }, TestCredentials.TestUser1);
            }
예제 #25
0
            protected override async Task When()
            {
                // Force restart of the subscription
                await Client.UpdateToAllAsync(Group, new PersistentSubscriptionSettings(), TestCredentials.Root);

                await _droppedSource.Task.WithTimeout();

                _secondSubscription = await Client.SubscribeToAllAsync(Group,
                                                                       eventAppeared : (s, e, r, ct) => {
                    _resumedSource.TrySetResult(e);
                    return(Task.CompletedTask);
                },
                                                                       userCredentials : TestCredentials.Root);

                foreach (var e in _events)
                {
                    await StreamsClient.AppendToStreamAsync("test-" + Guid.NewGuid(), StreamState.Any, new[] { e });
                }
            }
        public void Remove(PersistentSubscription subscription)
        {
            using (ISession session = _sessionFactory.OpenSession())
            using (ITransaction transaction = session.BeginTransaction())
            {
                IList<PersistentSubscription> existingSubscription = session.QueryOver<PersistentSubscription>()
                    .Where(x => x.BusUri == subscription.BusUri)
                    .Where(x => x.PeerId == subscription.PeerId)
                    .Where(x => x.SubscriptionId == subscription.SubscriptionId)
                    .List();

                foreach (PersistentSubscription existing in existingSubscription)
                {
                    _log.DebugFormat("Removing: {0}", existing);

                    session.Delete(existing);
                }

                transaction.Commit();
            }
        }
예제 #27
0
        public void Remove(PersistentSubscription subscription)
        {
            using (ISession session = _sessionFactory.OpenSession())
                using (ITransaction transaction = session.BeginTransaction())
                {
                    IList <PersistentSubscription> existingSubscription = session.QueryOver <PersistentSubscription>()
                                                                          .Where(x => x.BusUri == subscription.BusUri)
                                                                          .Where(x => x.PeerId == subscription.PeerId)
                                                                          .Where(x => x.SubscriptionId == subscription.SubscriptionId)
                                                                          .List();

                    foreach (PersistentSubscription existing in existingSubscription)
                    {
                        _log.DebugFormat("Removing: {0}", existing);

                        session.Delete(existing);
                    }

                    transaction.Commit();
                }
        }
예제 #28
0
            protected override async Task Given()
            {
                foreach (var e in _events)
                {
                    await StreamsClient.AppendToStreamAsync("test-" + Guid.NewGuid(), StreamState.Any, new[] { e });
                }

                await Client.CreateToAllAsync(Group,
                                              new PersistentSubscriptionSettings(
                                                  minCheckPointCount : 5,
                                                  checkPointAfter : TimeSpan.FromSeconds(1),
                                                  startFrom : Position.Start),
                                              TestCredentials.Root);

                var checkPointStream = $"$persistentsubscription-$all::{Group}-checkpoint";

                _checkPointSubscription = await StreamsClient.SubscribeToStreamAsync(checkPointStream,
                                                                                     (s, e, ct) => {
                    _checkPointSource.TrySetResult(e);
                    return(Task.CompletedTask);
                },
                                                                                     userCredentials : TestCredentials.Root);

                _firstSubscription = await Client.SubscribeToAllAsync(Group,
                                                                      eventAppeared : (s, e, r, ct) => {
                    _appearedEvents.Add(e);

                    if (_appearedEvents.Count == _events.Length)
                    {
                        _appeared.TrySetResult(true);
                    }
                    return(Task.CompletedTask);
                },
                                                                      (subscription, reason, ex) => _droppedSource.TrySetResult((reason, ex)),
                                                                      TestCredentials.Root);

                await Task.WhenAll(_appeared.Task, _checkPointSource.Task).WithTimeout();

                CheckPoint = _checkPointSource.Task.Result.Event.Data.ParsePosition();
            }
예제 #29
0
            protected override async Task Given()
            {
                await Client.CreateAsync(Stream, Group,
                                         new PersistentSubscriptionSettings(startFrom : StreamPosition.End, resolveLinkTos : true),
                                         TestCredentials.Root);

                _subscription = await Client.SubscribeAsync(Stream, Group,
                                                            async (subscription, e, retryCount, ct) => {
                    await subscription.Ack(e);
                    if (Interlocked.Increment(ref _eventReceivedCount) == _events.Length)
                    {
                        _eventsReceived.TrySetResult(true);
                    }
                }, (s, r, e) => {
                    if (e != null)
                    {
                        _eventsReceived.TrySetException(e);
                    }
                }, autoAck : false,
                                                            bufferSize : BufferCount,
                                                            userCredentials : TestCredentials.Root);
            }
예제 #30
0
        public async Task SubscriptionWorker_CanBeCreatedAndReceiveEvents()
        {
            CancellationToken      cancellationToken = CancellationToken.None;
            TestDomainEventHandler eventHandler1     = new();
            Int32 inflight         = 200;
            Int32 pollingInSeconds = 60;

            this.domainEventHandlerResolver.Setup(d => d.GetDomainEventHandlers(It.IsAny <IDomainEvent>())).Returns(new List <IDomainEventHandler>()
            {
                eventHandler1
            });

            SubscriptionWorker sw = SubscriptionWorker.CreateConcurrentSubscriptionWorker(this.EventStoreConnectionString,
                                                                                          this.domainEventHandlerResolver.Object,
                                                                                          this.SubscriptionRepository,
                                                                                          inflight,
                                                                                          pollingInSeconds).UseInMemory();

            await sw.StartAsync(cancellationToken);

            //Give our service time to run
            await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);

            sw.IsRunning.ShouldBeTrue();

            PersistentSubscription ps = sw.GetPersistentSubscription()[0];

            String @event = "{\r\n  \"estateId\": \"4fc2692f-067a-443e-8006-335bf2732248\",\r\n  \"estateName\": \"Demo Estate\"\r\n}\t";

            ps.Connected.ShouldBeTrue();
            ps.PersistentSubscriptionDetails.InflightMessages.ShouldBe(inflight);

            //Manually add events.
            ((InMemoryPersistentSubscriptionsClient)ps.PersistentSubscriptionsClient).WriteEvent(@event, "EstateCreatedEvent", cancellationToken);

            eventHandler1.DomainEvents.Count.ShouldBe(1);
        }
예제 #31
0
        public async Task DisposeAsync()
        {
            await Client.DisposeAsync();

            await PersistentSubscription.DisposeAsync();
        }
예제 #32
0
 private Task OnEventAppeared(PersistentSubscription arg1, ResolvedEvent arg2, int?arg3, CancellationToken arg4)
 {
     EventsReceived += 1;
     return(Task.CompletedTask);
 }
예제 #33
0
 private void OnSubscriptionDropped(PersistentSubscription sub, SubscriptionDroppedReason reason, Exception?exc)
 {
 }
예제 #34
0
        public async Task Subscribe()
        {
            await EnsureSubscription();

            subscription = await client.SubscribeAsync(projection.Stream, projection.Name, OnEvent, OnSubscriptionDropped);
        }
예제 #35
0
 private async void OnSubscriptionDropped(PersistentSubscription _, SubscriptionDroppedReason arg2, Exception arg3)
 {
     await Subscribe();
 }
        void Remove(PersistentSubscription subscription)
        {
            try
            {
                if (_log.IsDebugEnabled)
                    _log.DebugFormat("SubscriptionRepository.Remove: {0}, {1}", subscription.MessageName,
                        subscription.SubscriptionId);

                _storage.Remove(subscription);
            }
            catch (Exception ex)
            {
                _log.Error("Failed to remove persistent subscription", ex);
            }
        }