Beispiel #1
0
        public Task Subscribe(CancellationToken cancelToken)
        {
            _cancelation = CancellationTokenSource.CreateLinkedTokenSource(cancelToken);
            var stream = $"$ce-{_endpoint}.{StreamTypes.Delayed}";
            var group  = $"{_endpoint}.{Assembly.GetEntryAssembly().GetName().Version}.{StreamTypes.Delayed}.ROUND";

            Task.Run(async() =>
            {
                while (Bus.OnMessage == null || Bus.OnError == null)
                {
                    Logger.Warn($"Could not find NSBs onMessage handler yet - if this persists there is a problem.");
                    await Task.Delay(1000, cancelToken).ConfigureAwait(false);
                }


                var settings = PersistentSubscriptionSettings.Create()
                               .StartFromBeginning()
                               .WithMaxRetriesOf(10)
                               .WithReadBatchOf(_readsize)
                               .WithLiveBufferSizeOf(_readsize * _readsize)
                               //.WithMessageTimeoutOf(TimeSpan.FromMilliseconds(int.MaxValue))
                               .WithMessageTimeoutOf(TimeSpan.FromMinutes(1))
                               .CheckPointAfter(TimeSpan.FromSeconds(30))
                               .MaximumCheckPointCountOf(_readsize * _readsize)
                               .ResolveLinkTos()
                               .WithNamedConsumerStrategy(SystemConsumerStrategies.Pinned);
                if (_extraStats)
                {
                    settings.WithExtraStatistics();
                }

                var clients = new DelayedClient[_clients.Count()];

                for (var i = 0; i < _clients.Count(); i++)
                {
                    var client = _clients.ElementAt(i);

                    var clientCancelSource = CancellationTokenSource.CreateLinkedTokenSource(_cancelation.Token);

                    client.Closed += (object s, ClientClosedEventArgs args) =>
                    {
                        Logger.Info($"Eventstore disconnected - shutting down delayed subscription");
                        clientCancelSource.Cancel();
                    };
                    try
                    {
                        await
                        client.CreatePersistentSubscriptionAsync(stream, group, settings,
                                                                 client.Settings.DefaultUserCredentials).ConfigureAwait(false);
                        Logger.Info($"Created ROUND ROBIN persistent subscription to stream [{stream}]");
                    }
                    catch (InvalidOperationException)
                    {
                    }

                    clients[i] = new DelayedClient(client, stream, group, _maxDelayed, clientCancelSource.Token);
                }
                _delayedThread = new Thread(Threaded)
                {
                    IsBackground = true, Name = $"Delayed Event Thread"
                };
                _delayedThread.Start(new ThreadParam {
                    Token = cancelToken, Clients = clients, JsonSettings = _settings, MaxRetry = _maxRetry
                });
            });

            return(Task.CompletedTask);
        }
Beispiel #2
0
 protected abstract Task CreatePersistentSubscription(
     PersistentSubscriptionSettings settings,
     CancellationToken cancellationToken
     );
 public Task UpdatePersistentSubscriptionAsync(string stream, string groupName, PersistentSubscriptionSettings settings, UserCredentials userCredentials = null)
 {
     Ensure.NotNullOrEmpty(stream, "stream");
     Ensure.NotNullOrEmpty(groupName, "groupName");
     Ensure.NotNull(settings, "settings");
     var source = new TaskCompletionSource<PersistentSubscriptionUpdateResult>();
     EnqueueOperation(new UpdatePersistentSubscriptionOperation(_settings.Log, source, stream, groupName, settings, userCredentials));
     return source.Task;
 }
Beispiel #4
0
        public Task UpdatePersistentSubscriptionAsync(string stream, string groupName, PersistentSubscriptionSettings settings,
                                                      UserCredentials credentials)
        {
            Ensure.NotNullOrEmpty(stream, "stream");
            Ensure.NotNullOrEmpty(groupName, "groupName");

            var source = new TaskCompletionSource <PersistentSubscriptionUpdateResult>(TaskCreationOptions.RunContinuationsAsynchronously);

            var envelope = new EmbeddedResponseEnvelope(new EmbeddedResponders.UpdatePersistentSubscription(source, stream, groupName));

            var corrId = Guid.NewGuid();

            _publisher.PublishWithAuthentication(_authenticationProvider, GetUserCredentials(_settings, credentials), source.SetException, user => new ClientMessage.UpdatePersistentSubscription(
                                                     corrId,
                                                     corrId,
                                                     envelope,
                                                     stream,
                                                     groupName,
                                                     settings.ResolveLinkTos,
                                                     settings.StartFrom,
                                                     (int)settings.MessageTimeout.TotalMilliseconds,
                                                     settings.ExtraStatistics,
                                                     settings.MaxRetryCount,
                                                     settings.HistoryBufferSize,
                                                     settings.LiveBufferSize,
                                                     settings.ReadBatchSize,
                                                     (int)settings.CheckPointAfter.TotalMilliseconds,
                                                     settings.MinCheckPointCount,
                                                     settings.MaxCheckPointCount,
                                                     settings.MaxSubscriberCount,
                                                     settings.NamedConsumerStrategy,
                                                     user,
                                                     credentials == null ? null : credentials.Username,
                                                     credentials == null ? null : credentials.Password));

            return(source.Task);
        }
        public async Task CreatePersistentSubscription([NotNull] string streamId, [NotNull] string group)
        {
            var persistentSubscriptionSettings = PersistentSubscriptionSettings.Create().DoNotResolveLinkTos().StartFromCurrent();

            await _eventStoreConnection.CreatePersistentSubscriptionAsync(streamId, group, persistentSubscriptionSettings, _eventStoreRepositoryConfiguration.UserCredentials);
        }
Beispiel #6
0
 public Task CreatePersistentSubscriptionAsync(string stream, string groupName, PersistentSubscriptionSettings settings,
                                               UserCredentials credentials)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        /// Creates the persistent connection.
        /// </summary>
        /// <param name="streamName">Name of the stream.</param>
        /// <param name="groupName">Name of the group.</param>
        /// <param name="persistentSubscriptionSettings">The persistent subscription settings.</param>
        /// <returns></returns>
        private async Task CreatePersistentSubscription(String streamName, String groupName, PersistentSubscriptionSettings persistentSubscriptionSettings)
        {
            Guard.ThrowIfNullOrEmpty(streamName, typeof(ArgumentNullException), "Stream Name cannot be null or empty when creating a Persistent Subscription");
            Guard.ThrowIfNullOrEmpty(groupName, typeof(ArgumentNullException), "Group Name cannot be null or empty when creating a Persistent Subscription");
            Guard.ThrowIfNull(persistentSubscriptionSettings, typeof(ArgumentNullException), "Persistent Subscription Settings cannot be null when creating a Persistent Subscription");

            // Get the connection
            IEventStoreConnection connection = await this.GetEventStoreConnection();

            // Attempt to create the subscription
            await connection.CreatePersistentSubscriptionAsync(streamName, groupName, persistentSubscriptionSettings, this.UserCredentials);
        }
 private static void CreateSubscription(IEventStoreConnection conn)
 {
     PersistentSubscriptionSettings settings = PersistentSubscriptionSettings.Create()
                                               .DoNotResolveLinkTos()
                                               .StartFromCurrent();
 }
Beispiel #9
0
 private async Task CreateSubscription()
 {
     await _subscriber.CreatePersistentSubscriptionAsync(_inputStream, _persistentSubscriptionGroup,
                                                         PersistentSubscriptionSettings.Create().StartFromBeginning().DoNotResolveLinkTos(),
                                                         _subscriberBuilder.Credentials);
 }
Beispiel #10
0
        private async Task Subscribe(string productStream, string queryGroup)
        {
            try
            {
                await _connection.CreatePersistentSubscriptionAsync(productStream, queryGroup, PersistentSubscriptionSettings.Create().ResolveLinkTos().StartFromBeginning(), new UserCredentials(_eventStoreSettings.UserName, _eventStoreSettings.Password));
            }
            catch (Exception e)
            {
            }

            async Task EventAppeared(EventStorePersistentSubscriptionBase s, ResolvedEvent e)
            {
                using (var scope = _serviceProvider.CreateScope())
                {
                    var mediator = scope.ServiceProvider.GetRequiredService <IMediator>();

                    var @event = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(e.Event.Data), new JsonSerializerSettings {
                        TypeNameHandling = TypeNameHandling.All
                    }) as INotification;
                    await mediator.Publish(@event);
                }
            };

            void SubscriptionDropped(EventStorePersistentSubscriptionBase e, SubscriptionDropReason s, Exception exc)
            {
                _subscriptions.TryTake(out e);
                _subscriptions.Add(_connection.ConnectToPersistentSubscriptionAsync(productStream, queryGroup, EventAppeared, SubscriptionDropped).Result);
            };

            _subscriptions.Add(await _connection.ConnectToPersistentSubscriptionAsync(productStream, queryGroup, EventAppeared, SubscriptionDropped));
        }
        public async Task when_they_do_not_exist_throws(bool useSsl)
        {
            var streamName = $"{GetStreamName()}_{useSsl}";
            var connection = _fixture.Connections[useSsl];

            await Assert.ThrowsAsync <InvalidOperationException>(() => connection.UpdatePersistentSubscriptionAsync(
                                                                     streamName, Group, PersistentSubscriptionSettings.Create(), DefaultUserCredentials.Admin))
            .WithTimeout();
        }
Beispiel #12
0
        public async Task HandleAsync(ICommand _command)
        {
            var cmd = _command as I利用者を登録するCommand;

            if (cmd == null)
            {
                throw new ArgumentException(nameof(_command), "I利用者を登録するCommand型ではありません。");
            }

            using (var c = EventStoreConnection.Create(
                       ConnectionSettings.Create().SetDefaultUserCredentials(Connection.UserCredentials())
                       , Connection.EventStoreUri()))
            {
                try
                {
                    var id = 利用者のID.New();

                    await c.ConnectAsync();

                    await c.AppendToStreamAsync(
                        id.ID文字列,
                        ExpectedVersion.NoStream,
                        new EventData(
                            Guid.NewGuid(),
                            Domain.RentalSubDomain.Events.User.AddedUserVer100,
                            true,
                            JsonSerializer.Serialize(Domain.RentalSubDomain.Events.User.AddedUserDTOVer100.Create(id, cmd.苗字, cmd.前)),
                            new byte[] { }
                            ));

                    await c.CreatePersistentSubscriptionAsync(id.ID文字列, Domain.GeneralSubDomain.Aggregate.User, PersistentSubscriptionSettings.Create(), Connection.UserCredentials());
                }
                finally
                {
                    c.Close();
                }
            }
        }
Beispiel #13
0
        public async Task <bool> ConnectRoundRobinPersistentSubscription(string stream, string group, CancellationToken token,
                                                                         Action <string, long, IFullEvent> callback, Func <Task> disconnected)
        {
            var clientsToken = CancellationTokenSource.CreateLinkedTokenSource(token);

            foreach (var client in _clients)
            {
                Logger.Write(LogLevel.Info,
                             () => $"Connecting to persistent subscription stream [{stream}] group [{group}] on client {client.Settings.GossipSeeds[0].EndPoint.Address}");


                var settings = PersistentSubscriptionSettings.Create()
                               .StartFromBeginning()
                               .WithMaxRetriesOf(10)
                               .WithReadBatchOf(_readSize)
                               .WithBufferSizeOf(_readSize * 3)
                               .WithLiveBufferSizeOf(_readSize)
                               .DontTimeoutMessages()
                               //.WithMessageTimeoutOf(TimeSpan.FromMinutes(2))
                               .CheckPointAfter(TimeSpan.FromSeconds(30))
                               .MaximumCheckPointCountOf(_readSize * 3)
                               .ResolveLinkTos()
                               .WithNamedConsumerStrategy(SystemConsumerStrategies.RoundRobin);
                if (_extraStats)
                {
                    settings.WithExtraStatistics();
                }

                try
                {
                    await client.CreatePersistentSubscriptionAsync(stream, group, settings,
                                                                   client.Settings.DefaultUserCredentials).ConfigureAwait(false);

                    Logger.Info($"Created ROUND ROBIN persistent subscription stream [{stream}] group [{group}]");
                }
                catch (InvalidOperationException)
                {
                    // Already created
                }


                try
                {
                    var subscription = await client.ConnectToPersistentSubscriptionAsync(stream, group,
                                                                                         eventAppeared : (sub, e) => EventAppeared(sub, e, clientsToken.Token, callback),
                                                                                         subscriptionDropped : (sub, reason, ex) => SubscriptionDropped(sub, reason, ex, disconnected, clientsToken.Token),
                                                                                         // Let us accept large number of unacknowledged events
                                                                                         bufferSize : _readSize,
                                                                                         autoAck : false).ConfigureAwait(false);

                    lock (_subLock) _persistentSubs.Add(subscription);
                    Logger.Write(LogLevel.Info,
                                 () => $"Connected to persistent subscription stream [{stream}] group [{group}] on client {client.Settings.GossipSeeds[0].EndPoint.Address}");
                }
                catch (OperationTimedOutException)
                {
                    return(false);
                }
            }
            return(true);
        }
        static async Task Main(string[] args)
        {
            var streamName      = "gRPC-person-stream";
            var groupName       = "gRPC-subscription-group";
            var userCredentials = new UserCredentials("admin", "changeit");

            var client = CreateEventStorePersistentSubscriptionsClient(userCredentials);


            var appeared = new TaskCompletionSource <StreamPosition>();
            var dropped  = new TaskCompletionSource <bool>();


            /*
             * IMPORTANT note.
             * in tcp client the methods for creating a persistent subscription
             *  is found on the same connection class (EventStoreConnection) as the connection for appending events,
             *
             * her in the gRpc client you can subscribe to a stream
             *  from the same client class as you use to append events
             *  but to create a persistent subscription (a group) you need to use the 'EventStorePersistentSubscriptionsClient'
             *
             * (I was a little confused before digging into the source code and the tests,
             * se further down where I stumbled and only found he non-persistent subscriber..)
             */

            /*
             * do not resolve linktos (todo: add explanation here. reference blog article.
             * start subscription from current position in stream,
             * - meaning only act on events coming in after this subscription is created.
             * - you can start from the beginning, StartFromBeginning, or any given position
             */
            var settings = new PersistentSubscriptionSettings(
                startFrom: StreamPosition.End,
                resolveLinkTos: false
                );


            /*
             * since a subscription might already have been created
             * we need to wrap the creation, catch the exception and "silence" it.
             */
            try
            {
                await client.CreateAsync(
                    streamName,
                    groupName,
                    settings,
                    userCredentials
                    );
            }

            /*
             * Note: in the tcp client we get a message on "InvalidOperationException"
             * but here we get a inner exception of type Grpc.Core.RpcException
             * with a StatusCode and Detail (i.e. error message)
             * this is nice, it makes it "easier" to do a catch-when directly on the StatusCode instead of on the message
             * perhaps catching on the string message is easier on the eye,
             *  but this is "more statically typed" and thus less prone of accidental typo-errors,
             */
            catch (InvalidOperationException e)
                when(e.InnerException != null && ((RpcException)e.InnerException).StatusCode == StatusCode.AlreadyExists)
                {
                    var temp = e.Message;

                    Console.WriteLine($"subscription {groupName} already exist, continuing");
                }

            /*
             * as long as the console is not closed the subscription will log new events
             */
            var _subscription = await client.SubscribeAsync(
                streamName : streamName,
                groupName : groupName,
                //eventAppeared: EventAppeared,
                eventAppeared : (subscription, resolvedEvent, number, cancellationToken) =>
            {
                Console.WriteLine("Received: " + Encoding.UTF8.GetString(resolvedEvent.Event.Data.ToArray()));

                //not sure why I should/would do this.. from test code in the client source.
                appeared.TrySetResult(resolvedEvent.OriginalEventNumber);
                return(Task.CompletedTask);
            },
                //subscriptionDropped: SubscriptionDropped,
                subscriptionDropped : (subscription, droppedReason, ex) =>
            {
                //not sure why I should/would do this.. from test code in the client source.
                Console.WriteLine($"dropped subscription '{droppedReason}'");
                dropped.TrySetResult(true);
            },
                userCredentials : userCredentials
                );


            Console.WriteLine($"waiting... new events in stream '{streamName}' will be logged to the console. press Enter to Quit");
            Console.Read();
        }
 public async Task should_be_able_to_create_the_persistent_subscription()
 {
     var groupId  = "group-" + Guid.NewGuid().ToString();
     var settings = PersistentSubscriptionSettings.Create().StartFrom(intMaxValue);
     await _store.CreatePersistentSubscriptionAsync(_streamId, groupId, settings, DefaultData.AdminCredentials);
 }
        static async Task Main(string[] args)
        {
            var connectionString = "esdb://localhost:2113?Tls=false";

            var settings = EventStoreClientSettings
                           .Create(connectionString);

            // Write some events to a random stream
            var writeClient = new EventStoreClient(settings);

            var          eventStoreStreamName = $"Test-{Uuid.NewUuid()}";
            const string eventStoreGroupName  = "EventStoreSubscriptionDrop";

            for (var i = 0; i < 1000; i++)
            {
                await writeClient.AppendToStreamAsync(
                    eventStoreStreamName,
                    StreamState.Any,
                    new []
                {
                    new EventData(Uuid.NewUuid(), "DummyEvent", new byte[] {})
                });
            }

            // create a subscription to the stream
            var subscriptionSettings = new PersistentSubscriptionSettings(
                messageTimeout: TimeSpan.FromSeconds(30),
                namedConsumerStrategy: SystemConsumerStrategies.RoundRobin,
                resolveLinkTos: true,
                startFrom: StreamPosition.Start);

            var subscriptionsClient = new EventStorePersistentSubscriptionsClient(settings);

            try
            {
                if (!subscriptionsClient.CreateAsync(
                        eventStoreStreamName,
                        eventStoreGroupName,
                        subscriptionSettings).Wait(TimeSpan.FromSeconds(10)))
                {
                    throw new Exception(
                              "Event Store subscription creation timed out.");
                }
            }
            catch (AggregateException e)
            {
                if (!(e.InnerException is InvalidOperationException oe))
                {
                    throw;
                }

                if (!Regex.IsMatch(oe.Message, "AlreadyExists"))
                {
                    throw;
                }
            }

            await subscriptionsClient.SubscribeAsync(
                eventStoreStreamName,
                eventStoreGroupName,
                (sub, @event, _, token) =>
            {
                sub.Ack(@event);
                return(Task.CompletedTask);
            },
                (sub, reason, e) =>
            {
                Console.WriteLine($"Sub dropped with {reason}. {e}");
            },
                autoAck : false);

            while (true)
            {
                await Task.Delay(1000);
            }
        }
 private PersistentSubscriptionSettings create_subscription()
 {
     return(PersistentSubscriptionSettings.Create()
            .DoNotResolveLinkTos()
            .StartFromBeginning());
 }
Beispiel #18
0
        public Task Subscribe(CancellationToken cancelToken)
        {
            var stream           = $"{_endpoint}.{Assembly.GetEntryAssembly().GetName().Version}";
            var roundRobbinGroup = $"{_endpoint}.{Assembly.GetEntryAssembly().GetName().Version}.ROUND";
            var pinnedGroup      = $"{_endpoint}.{Assembly.GetEntryAssembly().GetName().Version}.PINNED";

            _cancelation = CancellationTokenSource.CreateLinkedTokenSource(cancelToken);


            Task.Run(async() =>
            {
                while (Bus.OnMessage == null || Bus.OnError == null)
                {
                    Logger.Warn($"Could not find NSBs onMessage handler yet - if this persists there is a problem.");
                    await Task.Delay(1000, cancelToken).ConfigureAwait(false);
                }


                var settings = PersistentSubscriptionSettings.Create()
                               .StartFromBeginning()
                               .WithMaxRetriesOf(10)
                               .WithReadBatchOf(_readsize)
                               .WithLiveBufferSizeOf(_readsize * _readsize)
                               //.WithMessageTimeoutOf(TimeSpan.FromMilliseconds(int.MaxValue))
                               .WithMessageTimeoutOf(TimeSpan.FromMinutes(1))
                               .CheckPointAfter(TimeSpan.FromSeconds(5))
                               .MaximumCheckPointCountOf(_readsize * _readsize)
                               .ResolveLinkTos();
                if (_extraStats)
                {
                    settings.WithExtraStatistics();
                }

                var clients = new PersistentClient[_clients.Count() * _concurrency * 2];

                for (var i = 0; i < _clients.Count(); i++)
                {
                    var client = _clients.ElementAt(i);

                    var clientCancelSource = CancellationTokenSource.CreateLinkedTokenSource(_cancelation.Token);

                    client.Closed += (object s, ClientClosedEventArgs args) =>
                    {
                        Logger.Info($"Eventstore disconnected - shutting down client subscription");
                        clientCancelSource.Cancel();
                    };

                    try
                    {
                        settings.WithNamedConsumerStrategy(SystemConsumerStrategies.Pinned);
                        await
                        client.CreatePersistentSubscriptionAsync($"{stream}.{StreamTypes.Domain}", pinnedGroup, settings,
                                                                 client.Settings.DefaultUserCredentials).ConfigureAwait(false);
                        Logger.Info($"Created PINNED persistent subscription to stream [{stream}]");
                    }
                    catch (InvalidOperationException)
                    {
                    }
                    try
                    {
                        settings.WithNamedConsumerStrategy(SystemConsumerStrategies.Pinned);
                        await
                        client.CreatePersistentSubscriptionAsync($"{stream}.{StreamTypes.OOB}", roundRobbinGroup, settings,
                                                                 client.Settings.DefaultUserCredentials).ConfigureAwait(false);
                        Logger.Info($"Created ROUND ROBIN persistent subscription to stream [{stream}]");
                    }
                    catch (InvalidOperationException)
                    {
                    }

                    for (var j = 0; j < _concurrency; j += 1)
                    {
                        // If multiple clients lay out clients array like so:  (assuming 2 clients with 4 concurrency)
                        //
                        //  ij
                        //  00 00 01 01 02 02 03 03
                        //  10 10 11 11 12 12 13 13
                        //
                        clients[2 * ((i * _concurrency) + j)]     = new PersistentClient(client, $"{stream}.{StreamTypes.Domain}", pinnedGroup, _readsize, j, clientCancelSource.Token);
                        clients[2 * ((i * _concurrency) + j) + 1] = new PersistentClient(client, $"{stream}.{StreamTypes.OOB}", roundRobbinGroup, _readsize, j, clientCancelSource.Token);
                    }
                }

                _pinnedThread = new Thread(Threaded)
                {
                    IsBackground = true, Name = $"Main Event Thread"
                };
                _pinnedThread.Start(new ThreadParam {
                    Token = cancelToken, Clients = clients, MessageMeta = _messageMeta, JsonSettings = _settings
                });
            });

            return(Task.CompletedTask);
        }
        public Task UpdatePersistentSubscriptionAsync(string stream, string groupName, PersistentSubscriptionSettings settings,
            UserCredentials userCredentials)
        {
            Ensure.NotNullOrEmpty(stream, "stream");
            Ensure.NotNullOrEmpty(groupName, "groupName");

            var source = new TaskCompletionSource<PersistentSubscriptionUpdateResult>();

            var envelope = new EmbeddedResponseEnvelope(new EmbeddedResponders.UpdatePersistentSubscription(source, stream, groupName));

            var corrId = Guid.NewGuid();

            _publisher.PublishWithAuthentication(_authenticationProvider, GetUserCredentials(_settings, userCredentials), source.SetException, user => new ClientMessage.UpdatePersistentSubscription(
                corrId,
                corrId,
                envelope,
                stream,
                groupName,
                settings.ResolveLinkTos,
                settings.StartFrom,
                (int) settings.MessageTimeout.TotalMilliseconds,
                settings.ExtraStatistics,
                settings.MaxRetryCount,
                settings.HistoryBufferSize,
                settings.LiveBufferSize,
                settings.ReadBatchSize,
                (int) settings.CheckPointAfter.TotalMilliseconds,
                settings.MinCheckPointCount,
                settings.MaxCheckPointCount,
                settings.MaxSubscriberCount,
                settings.NamedConsumerStrategy,
                user,
                userCredentials == null ? null : userCredentials.Username,
                userCredentials == null ? null : userCredentials.Password));

            return source.Task;
        }
Beispiel #20
0
        public static async Task <bool> CreatePersistentSubscriptionAsyncIfRequired(string stream, string groupName, PersistentSubscriptionSettings settings, UserCredentials credentials, Func <IEventStoreConnection> connectionFactory)
        {
            Ensure.That(stream, nameof(stream)).IsNotNullOrWhiteSpace();
            Ensure.That(groupName, nameof(groupName)).IsNotNullOrWhiteSpace();
            Ensure.That(settings, nameof(settings)).IsNotNull();
            Ensure.That(connectionFactory, nameof(connectionFactory)).IsNotNull();

            using (var connection = connectionFactory())
            {
                await connection.ConnectAsync();

                var createSubscription = await ShouldCreateSubscription(stream, groupName, credentials, new Uri("http://127.0.0.1:2113"));

                if (createSubscription)
                {
                    await connection.CreatePersistentSubscriptionAsync(stream, groupName, settings, credentials).ConfigureAwait(false);
                }

                return(createSubscription);
            }
        }
Beispiel #21
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Connecting to EventStore...");
            IEventStoreConnection conn = await GetEventStoreConnection();

            Console.WriteLine("Connected!");

            //foreach (string f in Directory.GetFiles("../../../../sample-data/", "shoppingCart-*"))
            //{
            //    var streamName = Path.GetFileNameWithoutExtension(f);

            //    var step3EventData = JsonConvert.DeserializeObject<List<EventDataWrapper>>(File.ReadAllText(f)).Select(x => x.ToEventData());
            //    var eventData = step3EventData.ToArray();
            //    await conn.AppendToStreamAsync(streamName, ExpectedVersion.Any, eventData);
            //}

            do
            {
                Console.Write("Want to write (w), read (r) or subscribe(s)? ");
                string option = Console.ReadLine();

                if (option == "w")
                {
                    Console.Write("value: ");
                    string value = Console.ReadLine();

                    Console.WriteLine("Writting new event...");
                    await WriteEvent(conn, value);

                    Console.WriteLine("Event written!");
                }
                else if (option == "r")
                {
                    //var readResult = await esConnection.ReadEventAsync("entity-1", 0, true);
                    //Console.WriteLine(Encoding.UTF8.GetString(readResult.Event.Value.Event.Data));

                    var readEvents = await conn.ReadStreamEventsForwardAsync("entity-1", 0, 10, true);

                    foreach (var evt in readEvents.Events)
                    {
                        Console.WriteLine(evt.Event.EventType + " - " + Encoding.UTF8.GetString(evt.Event.Data));
                    }
                }
                else
                {
                    var settings = PersistentSubscriptionSettings.Create().DoNotResolveLinkTos().StartFromCurrent();
                    try
                    {
                        await conn.CreatePersistentSubscriptionAsync("entity-1", "gr1", settings, new UserCredentials("admin", "changeit"));
                    }
                    catch (Exception)
                    {
                    }
                    EventStorePersistentSubscriptionBase subscription = await conn.ConnectToPersistentSubscriptionAsync(
                        "entity-1", "gr1", (_, evt) =>
                    {
                        Console.WriteLine("Received: " + Encoding.UTF8.GetString(evt.Event.Data));
                    });

                    Console.Clear();
                    Console.WriteLine("Listening to subscription...");
                    Console.ReadKey();
                }

                Console.WriteLine("--------------------------");
                Console.WriteLine("");
            } while (true);
        }
Beispiel #22
0
        /*
         *
         *      public EventStorePersistentSubscription ConnectToPersistentSubscriptionForAll(
         *          string groupName,
         *          Action<EventStorePersistentSubscription, ResolvedEvent> eventAppeared,
         *          Action<EventStorePersistentSubscription, SubscriptionDropReason, Exception> subscriptionDropped = null,
         *          UserCredentials userCredentials = null,
         *          int? bufferSize = null,
         *          bool autoAck = true)
         *      {
         *          return ConnectToPersistentSubscription(groupName,
         *              SystemStreams.AllStream,
         *              eventAppeared,
         *              subscriptionDropped,
         *              userCredentials,
         *              bufferSize,
         *              autoAck);
         *      }
         */


        public Task CreatePersistentSubscriptionAsync(string stream, string groupName, PersistentSubscriptionSettings settings, UserCredentials credentials = null)
        {
            Ensure.NotNullOrEmpty(stream, "stream");
            Ensure.NotNullOrEmpty(groupName, "groupName");
            Ensure.NotNull(settings, "settings");
            var source = new TaskCompletionSource <PersistentSubscriptionCreateResult>(TaskCreationOptions.RunContinuationsAsynchronously);

            EnqueueOperation(new CreatePersistentSubscriptionOperation(Settings.Log, source, stream, groupName, settings, credentials));
            return(source.Task);
        }
 public void the_build_fails_with_argument_exception()
 {
     Assert.Throws <ArgumentException>(() =>
                                       PersistentSubscriptionSettings.Create().CheckPointAfter(TimeSpan.FromDays(25 * 365)).Build());
 }
        public async Task UpdatePersistentSubscriptionAsync(string stream, string groupName, PersistentSubscriptionSettings settings, UserCredentials credentials = null)
        {
            Ensure.NotNullOrEmpty(stream, "stream");
            Ensure.NotNullOrEmpty(groupName, "groupName");
            Ensure.NotNull(settings, "settings");
            var source    = new TaskCompletionSource <PersistentSubscriptionUpdateResult>(TaskCreationOptions.RunContinuationsAsynchronously);
            var operation = new UpdatePersistentSubscriptionOperation(Settings.Log, source, stream, groupName, settings, credentials);

            await EnqueueOperation(operation).ConfigureAwait(false);

            await source.Task.ConfigureAwait(false);
        }
        public Task UpdatePersistentSubscriptionAsync(string stream, string groupName, PersistentSubscriptionSettings settings, UserCredentials userCredentials = null)
        {
            Ensure.NotNullOrEmpty(stream, "stream");
            Ensure.NotNullOrEmpty(groupName, "groupName");
            Ensure.NotNull(settings, "settings");
            var source = new TaskCompletionSource <PersistentSubscriptionUpdateResult>();

            EnqueueOperation(new UpdatePersistentSubscriptionOperation(_settings.Log, source, stream, groupName, settings, userCredentials));
            return(source.Task);
        }
        public async Task HandleAsync(ICommand _command)
        {
            var cmd = _command as I本を登録するCommand;

            if (cmd == null)
            {
                throw new ArgumentException(nameof(_command), "I本を登録するCommand型ではありません。");
            }

            var _書籍のID = 書籍のID.New();
            var _本のID  = 本のID.New();

            var 書籍のEventData =
                new EventData(
                    Guid.NewGuid(),
                    Domain.RentalSubDomain.Events.BookInfo.AddedBookInfoVer100,
                    true,
                    JsonSerializer.Serialize(Domain.RentalSubDomain.Events.BookInfo.AddedBookInfoDTOVer100.Create(_書籍のID.ID文字列, cmd.タイトル.タイトル, cmd.ISBN.ISBN)),
                    new byte[] { }
                    );

            var 本のEventData =
                new EventData(
                    Guid.NewGuid(),
                    Domain.RentalSubDomain.Events.Book.AddedBookVer100,
                    true,
                    JsonSerializer.Serialize(Domain.RentalSubDomain.Events.Book.AddedBookDTOVer100.Create(_本のID.ID文字列, _書籍のID.ID文字列)),
                    new byte[] { }
                    );

            using (var c = EventStoreConnection.Create(
                       ConnectionSettings.Create().SetDefaultUserCredentials(Connection.UserCredentials())
                       , Connection.EventStoreUri()))
            {
                try
                {
                    await c.ConnectAsync();

                    ConditionalWriteResult 書籍Result = await c.ConditionalAppendToStreamAsync(_書籍のID.ID文字列, ExpectedVersion.NoStream, new [] { 書籍のEventData });

                    ConditionalWriteResult 本Result = await c.ConditionalAppendToStreamAsync(_本のID.ID文字列, ExpectedVersion.NoStream, new [] { 本のEventData });

                    if (ConditionalWriteStatus.Succeeded.Equals(書籍Result.Status) &&
                        ConditionalWriteStatus.Succeeded.Equals(本Result.Status))
                    {
                        await c.AppendToStreamAsync(_書籍のID.ID文字列, ExpectedVersion.NoStream, 書籍のEventData);

                        await c.AppendToStreamAsync(_本のID.ID文字列, ExpectedVersion.NoStream, 本のEventData);

                        await c.CreatePersistentSubscriptionAsync(_書籍のID.ID文字列, Domain.GeneralSubDomain.Aggregate.BookInfo, PersistentSubscriptionSettings.Create(), Connection.UserCredentials());

                        await c.CreatePersistentSubscriptionAsync(_本のID.ID文字列, Domain.GeneralSubDomain.Aggregate.Book, PersistentSubscriptionSettings.Create(), Connection.UserCredentials());

                        MessageBroker.Publish <I本が登録されたEvent>(本が登録されたEvent.Create(_書籍のID));
                    }
                    else
                    {
                        Logger.LogError($"書籍Result.Status = {Enum.GetName(typeof(ConditionalWriteStatus), 書籍Result.Status)}, 本Result.Status = {Enum.GetName(typeof(ConditionalWriteStatus), 本Result.Status)}");
                    }
                }
                finally
                {
                    c.Close();
                }
            }
        }