Exemplo n.º 1
0
 public static EventStoreSubscription GetLiveOnlyEventStoreSubscription(
     this IEventStoreConnection eventStoreConnection,
     Type typeofDomainObject,
     Action <EventStoreSubscription, ResolvedEvent> eventAppeared,
     Action <EventStoreSubscription, SubscriptionDropReason, Exception> subscriptionDropped = null,
     UserCredentials userCredentials = null,
     bool resolveLinkTos             = true,
     Guid aggregateId = default(Guid))
 {
     try
     {
         var streamName = typeofDomainObject.GetStreamNameBasedOnDomainObjectType(
             resolveLinkTos,
             aggregateId);
         return(eventStoreConnection.SubscribeToStreamAsync(
                    streamName,
                    resolveLinkTos,
                    eventAppeared,
                    subscriptionDropped,
                    userCredentials).Result);
     }
     catch (Exception ex)
     {
         // Unlike a stream catch-up subscription, a live only subscription will fail if EventStore is not running.
         Log.Error(ex.Message);
         throw;
     }
 }
Exemplo n.º 2
0
 protected async Task SubscribeToStream(string streamId, string login, string password)
 {
     using (await Connection.SubscribeToStreamAsync(streamId, false, (x, y) => Task.CompletedTask,
                                                    (x, y, z) => { },
                                                    login == null && password == null ? null : new UserCredentials(login, password))) {
     }
 }
        /// <summary>
        /// Creates the Subscription with EventStore.
        /// </summary>
        /// <param name="streamName">The name of the EventStore Stream we are subscribing to.</param>
        /// <param name="eventStoreStreamSequenceToken"></param>
        /// <returns>An EventStoreSubscription or EventStorePersistentSubscription.</returns>
        private object CreateEventStoreSubscription(string streamName, EventStoreStreamSequenceToken eventStoreStreamSequenceToken)
        {
            object subscription = null;

            if (eventStoreStreamSequenceToken == null || eventStoreStreamSequenceToken.EventNumber == int.MinValue)
            {
                var subscribeTask = m_EventStoreConnection.SubscribeToStreamAsync(streamName, true, EventAppeared,
                                                                                  SubscriptionDropped);
                Task.WaitAll(subscribeTask);
                if (subscribeTask.IsFaulted)
                {
                    throw subscribeTask.Exception;
                }

                subscription = subscribeTask.Result;
            }
            else
            {
                // If we have been provided with a StreamSequenceToken, we can call SubscribeFrom to get previous messages.
                subscription = m_EventStoreConnection.SubscribeToStreamFrom(streamName,
                                                                            eventStoreStreamSequenceToken.EventNumber, new CatchUpSubscriptionSettings(100, 20, false, true), EventAppeared);
            }

            m_Logger.Info($"Subscribed to Stream {streamName}");
            return(subscription);
        }
 protected void SubscribeToStream(string streamId, string login, string password)
 {
     using (Connection.SubscribeToStreamAsync(AdjustStreamId(streamId), false, (x, y) => { }, (x, y, z) => { },
                                              login == null && password == null ? null : new UserCredentials(login, password)).Result)
     {
     }
 }
Exemplo n.º 5
0
 private static void Subscribe(string room, Action <ChatMessage> onRecieved)
 {
     _connection.SubscribeToStreamAsync(
         room,
         false,
         OnRecieved(onRecieved));
     Console.WriteLine("_connecting to room " + room);
 }
Exemplo n.º 6
0
 public static void Subscribe(
     string room,
     Action <ChatMessage> onRecieved)
 {
     Connection.SubscribeToStreamAsync(
         room,
         false,
         OnRecieved(onRecieved));
 }
Exemplo n.º 7
0
        public void Start()
        {
            connection.ConnectAsync()
            .Wait();

            connection.SubscribeToStreamAsync(
                "Employee",
                true,
                (subscription, evt) => processor.ProcessEvent(evt))
            .Wait();
        }
Exemplo n.º 8
0
 public static async Task <EventStoreSubscription> SubscribeToStream(
     this IEventStoreConnection connection,
     string stream,
     Action <EventStoreSubscription, ResolvedEvent> processEvent)
 {
     return(await connection.SubscribeToStreamAsync(
                stream,
                false,
                processEvent,
                null,
                new UserCredentials("admin", "changeit")));
 }
        public void Start_ProcessesEventsFromStream()
        {
            sut.Start();

            A.CallTo(() => connection.ConnectAsync()).MustHaveHappened()
            .Then(A.CallTo(() => connection.SubscribeToStreamAsync(
                               "Employee",
                               true,
                               A <Func <EventStoreSubscription, ResolvedEvent, Task> > ._,
                               null,
                               null)).MustHaveHappened());
        }
Exemplo n.º 10
0
 public EventStoreBusConnector(
     IGeneralBus bus,
     IEventStoreConnection es,
     string stream,
     string name)
 {
     _es     = es;
     _stream = stream;
     _bus    = new BusAdapter(bus);
     _name   = name;
     _bus.Subscribe(this);
     _es.SubscribeToStreamAsync(stream, true, EventAppeared, SubscriptionDropped);
 }
 /// <summary>
 /// Asynchronously subscribes to a single event stream. New events
 /// written to the stream while the subscription is active will be
 /// pushed to the client.
 /// </summary>
 /// <param name="target">The connection to subscribe to</param>
 /// <param name="stream">The stream to subscribe to</param>
 /// <param name="resolveLinkTos">Whether to resolve Link events automatically</param>
 /// <param name="eventAppeared">An action invoked when a new event is received over the subscription</param>
 /// <param name="subscriptionDropped">An action invoked if the subscription is dropped</param>
 /// <param name="userCredentials">User credentials to use for the operation</param>
 /// <returns>An <see cref="EventStoreSubscription"/> representing the subscription</returns>
 public static Task <EventStoreSubscription> SubscribeToStreamAsync(
     this IEventStoreConnection target,
     string stream,
     bool resolveLinkTos,
     Action <EventStoreSubscription, ResolvedEvent> eventAppeared,
     Action <EventStoreSubscription, SubscriptionDropReason, Exception> subscriptionDropped = null,
     UserCredentials userCredentials = null) =>
 target.SubscribeToStreamAsync(
     stream,
     resolveLinkTos,
     ToTask(eventAppeared),
     subscriptionDropped,
     userCredentials
     );
Exemplo n.º 12
0
        public void SubscribeToFutureEvents()
        {
            var thread = new Thread(() =>
            {
                eventStoreConnection.SubscribeToStreamAsync(streamName, true,
                                                            (sub, evt) =>
                {
                    UpdateOrderState(evt, context);
                })
                .Wait();
            });

            thread.Start();
        }
        public async Task SubscribeToOrderTypeStream()
        {
            string streamId = "$et-EventSourceDemo.OrderCompleted";
            // Subscribe to the OrderCompleted type stream. This requires the event type projection to be running
            await _connection.SubscribeToStreamAsync(streamId, true, (sub, evnt) =>
            {
                var @event = (OrderCompleted)Helper.ConstructEvent(evnt);
                Console.WriteLine($"Received Order for {@event.UserId} {@event.CartId}");
            },
                                                     (sub, reason, ex) => {
                Console.WriteLine($"Subscription dropped because {reason}. Exception: {ex}");
            }, _credentials);

            Console.WriteLine($"Subscribed to order type stream {streamId}");
        }
        private async Task Connect()
        {
            _connection = _connectionProvider.GetConnection();
            await _connection.ConnectAsync();


            Func <EventStoreCatchUpSubscription, ResolvedEvent, Task> processEvent = (subscriptionBase, resolvedEvent) => {
                return(HandleEvent(resolvedEvent));
            };

            Func <ESSubscription, ResolvedEvent, Task> processEventAlt = (subscriptionBase, resolvedEvent) => {
                return(HandleEvent(resolvedEvent));
            };

            var streamId = _streamId == null ? $"$ce-{_aggregateType.ToUpper()}" : _streamId.Id;

            if (_startPosition == StreamPosition.End)
            {
                _subscriptionBase = await _connection.SubscribeToStreamAsync(
                    streamId,
                    true,
                    processEventAlt,
                    subscriptionDropped : SubscriptionDropped);

                _connected = true;
                _status    = SubscriptionConnectionStatus.Connected;
            }
            else
            {
                _catchUpSubscriptionBase = _connection.SubscribeToStreamFrom(
                    streamId,
                    0,
                    new CatchUpSubscriptionSettings(
                        CatchUpSubscriptionSettings.Default.MaxLiveQueueSize,
                        CatchUpSubscriptionSettings.Default.ReadBatchSize,
                        false,
                        true,
                        CatchUpSubscriptionSettings.Default.SubscriptionName),
                    processEvent,
                    subscriptionDropped: SubscriptionDropped);
                _connected = true;
                _status    = SubscriptionConnectionStatus.Connected;
            }
        }
Exemplo n.º 15
0
 public void StartListening()
 {
     //
     // This can also be done with competing consumers for load balancing
     // the workload across many of the same adapter. In order to use
     // competing consumers you would use ConnectToPersistentSubscription
     // and first create a named persistent subscription to connect to
     //
     // *note that the code from competing branch is not yet merged to master
     //
     // Also note that this is currently using an admin user for subscribing
     // in most systems a specific user would be prefered as opposed to using
     // an admin user for this behaviour.
     _subscription = _connection.SubscribeToStreamAsync(_incomingStream,
                                                        false,
                                                        EventAppeared,
                                                        SubscriptionDropped,
                                                        _credentials).Result;
 }
        /// <summary>
        /// Start the subscriber.
        /// </summary>
        /// <param name="restart">Starting from a restart.</param>
        public void Start(bool restart = false)
        {
            if (_usingHeartbeats)
            {
                SendHeartbeat();
                _heartbeatTimer.Start();
            }

            lock (_subscriptionLock)
            {
                KillSubscription();

                if (_liveOnly)
                {
                    _subscription = _connection.SubscribeToStreamAsync(_streamName, true, (s, e) => EventAppeared(e), SubscriptionDropped).Result;
                }
                else
                {
                    var catchUpSettings = new CatchUpSubscriptionSettings(_maxLiveQueueSize, _catchupPageSize, true, true);
                    _subscription = _connection.SubscribeToStreamFrom(_streamName, _startingPosition, catchUpSettings, (s, e) => EventAppeared(e), LiveProcessingStarted, SubscriptionDropped);
                }
            }

            if (restart)
            {
                return;
            }

            if (_usingHeartbeats)
            {
                _connection.SetStreamMetadataAsync(_heartbeatStreamName, ExpectedVersion.Any, StreamMetadata.Create(2));
            }

            var processor = new Thread(ProcessEvents)
            {
                IsBackground = true
            };

            processor.Start();
        }
Exemplo n.º 17
0
 public IDisposable Subscribe(IObserver <T> observer)
 {
     _observer     = observer;
     _subscription = _connection.SubscribeToStreamAsync(_streamName, _resolveLinkTos, EventAppeared, SubscriptionDropped).Result;
     return(Disposable.Create(Stop));
 }
Exemplo n.º 18
0
 public void SubscribeToStream(string streamName, Action <EventstoreEvent> eventHandler)
 {
     _connection.SubscribeToStreamAsync(streamName, false,
                                        (subscription, resolvedEvent) => eventHandler(MapEventstoreEvent(resolvedEvent)),
                                        (subscription, reason, arg3) => SubscriptionDropped(reason, streamName, eventHandler));
 }
Exemplo n.º 19
0
 private void SubscriptionDropped(EventStoreSubscription arg1, SubscriptionDropReason arg2, Exception arg3)
 {
     _es.SubscribeToStreamAsync(_stream, true, EventAppeared, SubscriptionDropped);
 }
Exemplo n.º 20
0
        private async Task SubscribeService(AppFunc chain, string stream, bool liveOnlySubscriptions, string subscriptionKey, IDictionary <string, object> environment)
        {
            environment.Log("Subscribing to stream: {0}", LogLevel.Debug, stream);

            while (true)
            {
                if (!running)
                {
                    return;
                }

                try
                {
                    if (_serviceSubscriptions.ContainsKey(subscriptionKey))
                    {
                        _serviceSubscriptions[subscriptionKey].Close();
                        _serviceSubscriptions.Remove(subscriptionKey);
                    }

                    if (liveOnlySubscriptions)
                    {
                        //TODO:Handle retries on error
                        var eventstoreSubscription = await _eventStoreConnection.SubscribeToStreamAsync(stream, true,
                                                                                                        async (subscription, evnt) => await PushEventToService(chain, stream, _eventSerialization.DeSerialize(evnt), false, environment,
                                                                                                                                                               x => environment.Log("Successfully handled event: {0} on stream: {1}", LogLevel.Debug, x.EventId, stream),
                                                                                                                                                               (x, exception) => environment.Log(exception, "Failed handling event: {0} on stream: {1}", LogLevel.Error, x.EventId, stream)).ConfigureAwait(false),
                                                                                                        async (subscription, reason, exception) => await SubscriptionDropped(chain, stream, true, subscriptionKey, reason, exception, environment).ConfigureAwait(false)).ConfigureAwait(false);

                        _serviceSubscriptions[subscriptionKey] = new LiveOnlyServiceSubscription(eventstoreSubscription);
                    }
                    else
                    {
                        var eventstoreSubscription = _eventStoreConnection.ConnectToPersistentSubscription(stream, subscriptionKey,
                                                                                                           async(subscription, evnt) => await PushEventToService(chain, stream, _eventSerialization.DeSerialize(evnt), true, environment,
                                                                                                                                                                 x =>
                        {
                            environment.Log("Successfully handled event: {0} on stream: {1}", LogLevel.Debug, x.EventId, stream);

                            subscription.Acknowledge(x.OriginalEvent);
                        }, (x, exception) =>
                        {
                            environment.Log(exception, "Failed handling event: {0} on stream: {1}", LogLevel.Error, x.EventId, stream);

                            subscription.Fail(x.OriginalEvent, PersistentSubscriptionNakEventAction.Unknown, exception.Message);
                        }).ConfigureAwait(false), async(subscription, reason, exception) => await SubscriptionDropped(chain, stream, false, subscriptionKey, reason, exception, environment).ConfigureAwait(false), autoAck: false);

                        _serviceSubscriptions[subscriptionKey] = new PersistentServiceSubscription(eventstoreSubscription);
                    }

                    return;
                }
                catch (Exception ex)
                {
                    if (!running)
                    {
                        return;
                    }

                    environment.Log(ex, "Couldn't subscribe to stream: {0}. Retrying in 5 seconds.", LogLevel.Warn, stream);

                    await Task.Delay(TimeSpan.FromSeconds(5)).ConfigureAwait(false);
                }
            }
        }