示例#1
0
        /// <summary>
        /// Establish EventStore Cluster Connection via Gossip Seed IP address(es)
        /// </summary>
        /// <remarks>
        /// Connect to an EventStore cluster using gossip seed IP addresses.
        /// This supports both a single EventStore cluster node and a multi-node EventStore cluster.
        /// Note that a cluster of 1 is equivalent to a single instance.
        /// </remarks>
        /// <param name="credentials">UserCredentials: Username-Password used for authentication and authorization</param>
        /// <param name="gossipSeeds">Array of GossipSeeds: The TCP/IP addresses, port and header. Generated by the <see cref="StreamStoreConnectionSettings"/>.</param>
        /// <param name="useTlsConnection">bool: Use an encrypted TLS connection to EventStore server. (optional, defaults to false.)</param>
        /// <param name="tlsCertificateHostName">string: The host name of the server expected on the TLS certificate. (optional unless <see cref="useTlsConnection"/> is true.)</param>
        /// <param name="validateTlsCertificate">bool: Validate the server TLS certificate. (optional, defaults to false. Used if <see cref="useTlsConnection"/> is true.)</param>
        /// <param name="verboseLogging">bool: Verbose Logging True/False (optional, defaults to false)</param>
        private void Connect(
            UserCredentials credentials,
            GossipSeed[] gossipSeeds,
            bool useTlsConnection         = false,
            string tlsCertificateHostName = "",
            bool validateTlsCertificate   = false,
            bool verboseLogging           = false)
        {
            var settings = SetClientConnectionSettings(
                credentials,
                useTlsConnection,
                tlsCertificateHostName,
                validateTlsCertificate,
                verboseLogging);

            Connection = new EventStoreConnectionWrapper(
                EventStoreConnection.Create(settings,
                                            ClusterSettings.Create()
                                            .DiscoverClusterViaGossipSeeds()
                                            .SetGossipSeedEndPoints(gossipSeeds),
                                            "Gossip Seeds-Cluster Connection"));

            if (Connection != null)
            {
                return;
            }
            _log.Error($"EventStore Custer of {gossipSeeds.Length} Connection is null - Diagnostic Monitoring will be unavailable.");
        }
示例#2
0
 public CorrelatedStreamStoreRepository(
     IStreamNameBuilder streamNameBuilder,
     IStreamStoreConnection streamStoreConnection,
     IEventSerializer eventSerializer)
 {
     _repository = new StreamStoreRepository(streamNameBuilder, streamStoreConnection, eventSerializer);
 }
示例#3
0
        public void Bootstrap()
        {
            IEventStoreConnection esConnection = EventStoreConnection.Create("ConnectTo=tcp://admin:changeit@localhost:1113");

            conn = new EventStoreConnectionWrapper(esConnection);
            esConnection.Connected += (_, __) => Console.WriteLine("Connected");
            esConnection.ConnectAsync().Wait();
            IStreamNameBuilder namer = new PrefixedCamelCaseStreamNameBuilder();
            IEventSerializer   ser   = new JsonMessageSerializer();

            repo       = new StreamStoreRepository(namer, conn, ser);
            cmdHandler = new AccountCommandHandler(repo);
            AccountAggregate acct = null;

            try
            {
                var command = new CreateAccountCommand()
                {
                    AccountId  = _accountId,
                    HolderName = _holderName
                };
                cmdHandler.Handle(command);
            }
            catch (Exception e)
            {
            }
            listener   = new StreamListener("AccountAggregate", conn, namer, ser);
            _readModel = new BalanceReadModel(() => listener);
        }
示例#4
0
        /// <summary>
        /// Connect to an EventStore server using DNS Discovery
        /// </summary>
        /// <remarks>
        /// Define a common DNS name relating it to all cluster node ID address(es).
        /// EventStore will process the DNS into gossip seeds for use in the connection.
        /// </remarks>
        /// <param name="credentials">UserCredentials: Username-Password used for authentication and authorization</param>
        /// <param name="clusterDns">string: Cluster DNS name representing all nodes in the EventStore cluster</param>
        /// <param name="networkPort">int: External HTTP port used for cluster gossip communication.</param>
        /// <param name="useTlsConnection">bool: Use an encrypted TLS connection to EventStore server. (optional, defaults to false.)</param>
        /// <param name="tlsCertificateHostName">string: The host name of the server expected on the TLS certificate. (optional unless <see cref="useTlsConnection"/> is true.)</param>
        /// <param name="validateTlsCertificate">bool: Validate the server TLS certificate. (optional, defaults to false. Used if <see cref="useTlsConnection"/> is true.)</param>
        /// <param name="verboseLogging">bool: Verbose Logging True/False (optional, defaults to false)</param>
        private void Connect(
            UserCredentials credentials,
            string clusterDns,
            int networkPort,
            bool useTlsConnection         = false,
            string tlsCertificateHostName = "",
            bool validateTlsCertificate   = false,
            bool verboseLogging           = false)
        {
            var settings = SetClientConnectionSettings(
                credentials,
                useTlsConnection,
                tlsCertificateHostName,
                validateTlsCertificate,
                verboseLogging);

            var esConn = EventStoreConnection.Create(settings,
                                                     ClusterSettings.Create()
                                                     .DiscoverClusterViaDns()
                                                     .SetClusterDns(clusterDns)
                                                     .SetClusterGossipPort(networkPort),
                                                     $"{clusterDns}-Cluster Connection");

            Connection = new EventStoreConnectionWrapper(esConn);

            if (Connection != null)
            {
                return;
            }
            _log.Error("EventStore Connection is null - Diagnostic Monitoring will be unavailable.");
        }
        public when_using_listener_start_with_custom_stream_synched_bus(StreamStoreConnectionFixture fixture)
        {
            conn = fixture.Connection;
            conn.Connect();

            // Build an origin stream from strings to which the the events are appended
            var originStreamName = $"testStream-{Guid.NewGuid():N}";

            var result = fixture.Connection.AppendToStream(
                originStreamName,
                ExpectedVersion.NoStream,
                null,
                _eventSerializer.Serialize(new TestEvent()));

            Assert.True(result.NextExpectedVersion == 0);

            // Wait for the stream to be written
            CommonHelpers.WaitForStream(conn, originStreamName);

            listener = new QueuedStreamListener(
                originStreamName,
                fixture.Connection,
                new PrefixedCamelCaseStreamNameBuilder(),
                _eventSerializer,
                "BUS_NAME",
                LiveProcessingStarted);
            SubscriptionDisposer = listener.EventStream.Subscribe(new AdHocHandler <Event>(Handle));
            listener.Start(originStreamName);
        }
示例#6
0
 /// <summary>Constructs state for EventStoreCatchUpSubscription.</summary>
 /// <param name="connection">The connection.</param>
 /// <param name="log">The <see cref="T:ReactiveDomain.ILogger" /> to use.</param>
 /// <param name="streamId">The stream name.</param>
 /// <param name="userCredentials">User credentials for the operations.</param>
 /// <param name="eventAppeared">Action invoked when events are received.</param>
 /// <param name="liveProcessingStarted">Action invoked when the read phase finishes.</param>
 /// <param name="subscriptionDropped">Action invoked if the subscription drops.</param>
 /// <param name="settings">Settings for this subscription.</param>
 protected CatchUpSubscription(
     IStreamStoreConnection connection,
     ILogger log,
     string streamId,
     UserCredentials userCredentials,
     Func <CatchUpSubscription, RecordedEvent, Task> eventAppeared,
     Action <CatchUpSubscription> liveProcessingStarted,
     Action <CatchUpSubscription, SubscriptionDropReason, Exception> subscriptionDropped,
     CatchUpSubscriptionSettings settings)
 {
     Ensure.NotNull(connection, nameof(connection));
     Ensure.NotNull(log, nameof(log));
     Ensure.NotNull(eventAppeared, nameof(eventAppeared));
     _connection            = connection;
     Log                    = log;
     StreamId               = string.IsNullOrEmpty(streamId) ? string.Empty : streamId;
     _userCredentials       = userCredentials;
     ReadBatchSize          = settings.ReadBatchSize;
     MaxPushQueueSize       = settings.MaxLiveQueueSize;
     EventAppeared          = eventAppeared;
     _liveProcessingStarted = liveProcessingStarted;
     _subscriptionDropped   = subscriptionDropped;
     Verbose                = settings.VerboseLogging;
     SubscriptionName       = settings.SubscriptionName ?? string.Empty;
 }
 private void AppendEvents(int numEventsToBeSent, IStreamStoreConnection conn, string streamName, int startNumber = 0)
 {
     for (int evtNumber = startNumber; evtNumber < numEventsToBeSent + startNumber; evtNumber++)
     {
         var evt = new SubscriptionTestEvent(evtNumber);
         conn.AppendToStream(streamName, ExpectedVersion.Any, null, _serializer.Serialize(evt));
     }
 }
示例#8
0
 public ConfiguredConnection(
     IStreamStoreConnection conn,
     IStreamNameBuilder namer,
     IEventSerializer serializer)
 {
     Connection  = conn;
     StreamNamer = namer;
     Serializer  = serializer;
 }
示例#9
0
        public AccountTest()
        {
            _mockStore           = new InMemoryEventStore();
            _mockStoreConnection = _mockStore.Connect("Accounts");
            var eventSerializer = new JsonEventSerializer();

            _repo    = new StreamStoreRepository(new PrefixedCamelCaseStreamNameBuilder(), _mockStoreConnection, eventSerializer);
            _service = new AccountHandler(_repo);
        }
 public StreamStoreRepository(
     IStreamNameBuilder streamNameBuilder,
     IStreamStoreConnection eventStoreConnection,
     IEventSerializer eventSerializer)
 {
     _streamNameBuilder     = streamNameBuilder;
     _streamStoreConnection = eventStoreConnection;
     _eventSerializer       = eventSerializer;
 }
示例#11
0
        public when_using_snapshot_read_model(StreamStoreConnectionFixture fixture)
        {
            _conn = fixture.Connection;
            _conn.Connect();

            _aggId  = Guid.NewGuid();
            _stream = _namer.GenerateForAggregate(typeof(SnapReadModelTestAggregate), _aggId);

            AppendEvents(10, _conn, _stream, 2);
        }
        internal StreamCatchUpSubscription(IStreamStoreConnection connection, ILogger log, string streamId, long?fromEventNumberExclusive, UserCredentials userCredentials, Func <CatchUpSubscription, RecordedEvent, Task> eventAppeared, Action <CatchUpSubscription> liveProcessingStarted, Action <CatchUpSubscription, SubscriptionDropReason, Exception> subscriptionDropped, CatchUpSubscriptionSettings settings)
            : base(connection, log, streamId, userCredentials, eventAppeared, liveProcessingStarted, subscriptionDropped, settings)
        {
            Ensure.NotNullOrEmpty(streamId, nameof(streamId));
            long?nullable = fromEventNumberExclusive;

            _lastProcessedEventNumber = nullable ?? -1L;
            nullable             = fromEventNumberExclusive;
            _nextReadEventNumber = nullable ?? 0L;
        }
        private void AppendEvents(int numEventsToBeSent, IStreamStoreConnection conn, string streamName)
        {
            _toh.WriteLine(
                $"Appending {numEventsToBeSent} events to stream \"{streamName}\" with connection {conn.ConnectionName}");

            for (int evtNumber = 0; evtNumber < numEventsToBeSent; evtNumber++)
            {
                var evt = new ReadTestEvent(evtNumber);
                conn.AppendToStream(streamName, ExpectedVersion.Any, null, _serializer.Serialize(evt));
            }
        }
示例#14
0
 public QueuedStreamListener(
     string name,
     IStreamStoreConnection connection,
     IStreamNameBuilder streamNameBuilder,
     IEventSerializer serializer,
     string busName = null,
     Action <Unit> liveProcessingStarted = null,
     Action <SubscriptionDropReason, Exception> subscriptionDropped = null) :
     base(name, connection, streamNameBuilder, serializer, busName, liveProcessingStarted, subscriptionDropped)
 {
     SyncQueue = new QueuedHandler(this, "SyncListenerQueue");
 }
 public CorrelatedStreamStoreRepository(
     IStreamNameBuilder streamNameBuilder,
     IStreamStoreConnection streamStoreConnection,
     IEventSerializer eventSerializer,
     Func <IRepository, IAggregateCache> cacheFactory = null)
 {
     _repository = new StreamStoreRepository(streamNameBuilder, streamStoreConnection, eventSerializer);
     if (cacheFactory != null)
     {
         _cache = cacheFactory(_repository);
     }
 }
示例#16
0
 private void AppendEvents(
     int numEventsToBeSent,
     IStreamStoreConnection conn,
     string streamName,
     int value)
 {
     for (int evtNumber = 0; evtNumber < numEventsToBeSent; evtNumber++)
     {
         var evt = new ReadModelTestEvent(evtNumber, value);
         conn.AppendToStream(streamName, ExpectedVersion.Any, null, Serializer.Serialize(evt));
     }
 }
示例#17
0
 /// <summary>
 /// Create a stream Reader
 /// </summary>
 /// <param name="name">Name of the reader</param>
 /// <param name="streamStoreConnection">The stream store to subscribe to</param>
 /// <param name="streamNameBuilder">The source for correct stream names based on aggregates and events</param>
 /// <param name="serializer">the serializer to apply to the evenets in the stream</param>
 /// <param name="busName">The name to use for the internal bus (helpful in debugging)</param>
 public StreamReader(
     string name,
     IStreamStoreConnection streamStoreConnection,
     IStreamNameBuilder streamNameBuilder,
     IEventSerializer serializer,
     string busName = null)
 {
     ReaderName             = name ?? nameof(StreamReader);
     _streamStoreConnection = streamStoreConnection ?? throw new ArgumentNullException(nameof(streamStoreConnection));
     _streamNameBuilder     = streamNameBuilder ?? throw new ArgumentNullException(nameof(streamNameBuilder));
     Serializer             = serializer ?? throw new ArgumentNullException(nameof(serializer));
     Bus = new InMemoryBus(busName ?? $"{ReaderName} {nameof(EventStream)}");
 }
示例#18
0
 protected with_message_logging_enabled(IStreamStoreConnection connection)
 {
     Connection        = connection;
     Bus               = new Dispatcher(nameof(with_message_logging_enabled));
     StreamNameBuilder = new PrefixedCamelCaseStreamNameBuilder("UnitTest");
     EventSerializer   = new JsonMessageSerializer();
     Repo              = new StreamStoreRepository(StreamNameBuilder, Connection, new JsonMessageSerializer());
     // instantiate Logger class that inherits from QueuedSubscriber
     Logging = new EventStoreMessageLogger(Bus,
                                           Connection,
                                           StreamName,
                                           true);
 }
        private async Task ReadEventsInternalAsync(IStreamStoreConnection connection, UserCredentials userCredentials, long?lastEventNumber)
        {
            StreamEventsSlice slice;

            do
            {
                slice = connection.ReadStreamForward(
                    StreamId,
                    _nextReadEventNumber,
                    ReadBatchSize,
                    userCredentials);
            }while (!await ReadEventsCallbackAsync(slice, lastEventNumber).ConfigureAwait(false));
        }
示例#20
0
 /// <summary>
 /// Create a stream Reader
 /// </summary>
 /// <param name="name">Name of the reader</param>
 /// <param name="streamStoreConnection">The stream store to subscribe to</param>
 /// <param name="streamNameBuilder">The source for correct stream names based on aggregates and events</param>
 /// <param name="serializer">the serializer to apply to the events in the stream</param>
 /// <param name="handle">The target handle that read events are passed to</param>
 public StreamReader(
     string name,
     IStreamStoreConnection streamStoreConnection,
     IStreamNameBuilder streamNameBuilder,
     IEventSerializer serializer,
     Action <IMessage> handle)
 {
     ReaderName             = name ?? nameof(StreamReader);
     _streamStoreConnection = streamStoreConnection ?? throw new ArgumentNullException(nameof(streamStoreConnection));
     _streamNameBuilder     = streamNameBuilder ?? throw new ArgumentNullException(nameof(streamNameBuilder));
     Serializer             = serializer ?? throw new ArgumentNullException(nameof(serializer));
     Handle = handle;
 }
        /// <summary>
        /// For listening to generic streams
        /// </summary>
        /// <param name="listenerName"></param>
        /// <param name="eventStoreConnection">The event store to subscribe to</param>
        /// <param name="streamNameBuilder">The source for correct stream names based on aggregates and events</param>
        /// <param name="serializer"></param>
        /// <param name="busName">The name to use for the internal bus (helpful in debugging)</param>
        public StreamListener(
            string listenerName,
            IStreamStoreConnection eventStoreConnection,
            IStreamNameBuilder streamNameBuilder,
            IEventSerializer serializer,
            string busName = null)
        {
            _bus = new InMemoryBus(busName ?? "Stream Listener");
            _eventStoreConnection = eventStoreConnection ?? throw new ArgumentNullException(nameof(eventStoreConnection));

            ListenerName       = listenerName;
            _streamNameBuilder = streamNameBuilder;
            _serializer        = serializer;
        }
        private void AppendEventArray(int numEventsToBeSent, IStreamStoreConnection conn, string streamName)
        {
            _toh.WriteLine(
                $"Appending {numEventsToBeSent} events to stream \"{streamName}\" with connection {conn.ConnectionName}");

            var events = new IMessage[numEventsToBeSent];

            for (int evtNumber = 0; evtNumber < numEventsToBeSent; evtNumber++)
            {
                events[evtNumber] = new ReadTestEvent(evtNumber);
            }

            conn.AppendToStream(streamName, ExpectedVersion.Any, null,
                                events.Select(x => _serializer.Serialize(x)).ToArray());
        }
 public SynchronizableStreamListener(
     string name,
     IStreamStoreConnection connection,
     IStreamNameBuilder streamNameBuilder,
     IEventSerializer serializer,
     bool sync      = false,
     string busName = null) :
     base(name, connection, streamNameBuilder, serializer, busName)
 {
     Sync = sync;
     if (Sync)
     {
         SyncQueue = new QueuedHandler(this, "SyncListenerQueue");
     }
 }
示例#24
0
        public when_using_read_model_base(StreamStoreConnectionFixture fixture)
            : base(nameof(when_using_read_model_base), GetListener)
        {
            //_conn = new MockStreamStoreConnection("mockStore");
            _conn = fixture.Connection;
            _conn.Connect();

            // ReSharper disable once RedundantTypeArgumentsOfMethod
            EventStream.Subscribe <ReadModelTestEvent>(this);

            _stream1 = Namer.GenerateForAggregate(typeof(TestAggregate), Guid.NewGuid());
            _stream2 = Namer.GenerateForAggregate(typeof(TestAggregate), Guid.NewGuid());

            AppendEvents(10, _conn, _stream1, 2);
            AppendEvents(10, _conn, _stream2, 3);
        }
        public void Bootstrap()
        {
            IEventStoreConnection esConnection = EventStoreConnection.Create("ConnectTo=tcp://admin:changeit@localhost:1113");

            conn = new EventStoreConnectionWrapper(esConnection);
            esConnection.Connected += (_, __) => Console.WriteLine("Connected");
            esConnection.ConnectAsync().Wait();
            IStreamNameBuilder namer = new PrefixedCamelCaseStreamNameBuilder();
            IEventSerializer   ser   = new JsonMessageSerializer();

            repo = new StreamStoreRepository(namer, conn, ser);
            OrderAggregate order = null;

            IListener listener = new StreamListener("Order", conn, namer, ser);

            _readModel = new OrderReadModel(() => listener);
        }
示例#26
0
 internal static void WaitForStream(IStreamStoreConnection conn, string streamName)
 {
     //wait for the category projection to be written
     AssertEx.IsOrBecomesTrue(
         () =>
     {
         try
         {
             return(conn.ReadStreamForward(streamName, 0, 1) != null);
         }
         catch
         {
             return(false);
         }
     },
         2000,
         $"Stream '{streamName}' not created");
 }
 /// <summary>
 /// For listening to generic streams
 /// </summary>
 /// <param name="listenerName"></param>
 /// <param name="streamStoreConnection">The event store to subscribe to</param>
 /// <param name="streamNameBuilder">The source for correct stream names based on aggregates and events</param>
 /// <param name="serializer"></param>
 /// <param name="busName">The name to use for the internal bus (helpful in debugging)</param>
 /// <param name="liveProcessingStarted"></param>
 /// <param name="subscriptionDropped"></param>
 public StreamListener(
     string listenerName,
     IStreamStoreConnection streamStoreConnection,
     IStreamNameBuilder streamNameBuilder,
     IEventSerializer serializer,
     string busName = null,
     Action <Unit> liveProcessingStarted = null,
     Action <SubscriptionDropReason, Exception> subscriptionDropped = null)
 {
     Bus = new InMemoryBus(busName ?? "Stream Listener");
     _streamStoreConnection = streamStoreConnection ?? throw new ArgumentNullException(nameof(streamStoreConnection));
     Settings               = CatchUpSubscriptionSettings.Default;
     ListenerName           = listenerName;
     _streamNameBuilder     = streamNameBuilder;
     Serializer             = serializer;
     _liveProcessingStarted = liveProcessingStarted;
     _subscriptionDropped   = subscriptionDropped;
 }
示例#28
0
        public when_using_read_model_base_with_reader(StreamStoreConnectionFixture fixture)
            : base(nameof(when_using_read_model_base),
                   new ConfiguredConnection(fixture.Connection, Namer, Serializer))
        {
            _conn = fixture.Connection;
            _conn.Connect();

            // ReSharper disable once RedundantTypeArgumentsOfMethod
            EventStream.Subscribe <ReadModelTestEvent>(this);

            _stream1 = Namer.GenerateForAggregate(typeof(TestAggregate), Guid.NewGuid());
            _stream2 = Namer.GenerateForAggregate(typeof(TestAggregate), Guid.NewGuid());

            AppendEvents(10, _conn, _stream1, 2);
            AppendEvents(10, _conn, _stream2, 3);
            _conn.TryConfirmStream(_stream1, 10);
            _conn.TryConfirmStream(_stream2, 10);
            _conn.TryConfirmStream(Namer.GenerateForCategory(typeof(TestAggregate)), 20);
        }
示例#29
0
        private void ConnectToLiveES()
        {
            var userCredentials = new ReactiveDomain.UserCredentials(username: "******", password: "******");

            var eventStoreLoader = new EventStoreLoader();

            eventStoreLoader.Connect(
                credentials: userCredentials,
                server: IPAddress.Parse("127.0.0.1"),
                tcpPort: 1113);

            Connection = eventStoreLoader.Connection;

            // ReSharper disable once PossibleNullReferenceException
            _connection = (IEventStoreConnection)typeof(EventStoreConnectionWrapper)
                          .GetField("_conn", BindingFlags.NonPublic | BindingFlags.Instance)
                          .GetValue(eventStoreLoader.Connection);

            log.Info("Connected to ES");
        }
示例#30
0
        public void Connect(
            UserCredentials credentials,
            IPAddress server,
            int tcpPort)
        {
            var tcpEndpoint = new IPEndPoint(server, tcpPort);

            var settings = ConnectionSettings.Create()
                           .SetDefaultUserCredentials(new global::EventStore.ClientAPI.SystemData.UserCredentials(credentials.Username, credentials.Password))
                           .KeepReconnecting()
                           .KeepRetrying()
                           .UseConsoleLogger()
                           //.EnableVerboseLogging()
                           .Build();

            Connection = new EventStoreConnectionWrapper(EventStoreConnection.Create(settings, tcpEndpoint, "Default Connection"));

            if (Connection == null)
            {
                _log.Error("EventStore Connection is null - Diagnostic Monitoring will be unavailable.");
                TeardownEventStore(false);
                return;
            }
            Connection.Connect();
            int retry = 8;
            int count = 0;

            do
            {
                try {
                    Connection.ReadStreamForward("by_event_type", 0, 1);
                    return;
                }
                catch {
                    //ignore
                }
                Thread.Sleep(100);
                count++;
            } while (count < retry);
            throw new Exception("Unable to start Eventstore");
        }