Exemple #1
0
        /// <summary>
        /// Invokes local filter using data from specified stream.
        /// </summary>
        /// <typeparam name="T">Event object type.</typeparam>
        /// <param name="stream">The stream.</param>
        /// <param name="listener">The listener.</param>
        /// <returns>Filter invocation result.</returns>
        private bool InvokeLocalFilter <T>(IPortableStream stream, IEventFilter <T> listener) where T : IEvent
        {
            var evt = EventReader.Read <T>(Marshaller.StartUnmarshal(stream));

            // No guid in local mode
            return(listener.Invoke(Guid.Empty, evt));
        }
        private void SubscribeToStream(Guid correlationId, IEnvelope envelope, Guid connectionId,
                                       string eventStreamId, bool resolveLinkTos, long lastIndexedPosition, long?lastEventNumber,
                                       IEventFilter eventFilter, int?checkpointInterval = null)
        {
            List <Subscription> subscribers;

            if (!_subscriptionTopics.TryGetValue(eventStreamId, out subscribers))
            {
                subscribers = new List <Subscription>();
                _subscriptionTopics.Add(eventStreamId, subscribers);
            }

            // if eventStreamId is null or empty -- subscription is to all streams
            var subscription = new Subscription(correlationId,
                                                envelope,
                                                connectionId,
                                                eventStreamId.IsEmptyString() ? AllStreamsSubscriptionId : eventStreamId,
                                                resolveLinkTos,
                                                lastIndexedPosition,
                                                lastEventNumber ?? -1,
                                                eventFilter,
                                                checkpointInterval);

            subscribers.Add(subscription);
            _subscriptionsById[correlationId] = subscription;
        }
Exemple #3
0
                public CatchupAllSubscription(Guid subscriptionId,
                                              IPublisher bus,
                                              Position position,
                                              bool resolveLinks,
                                              IEventFilter eventFilter,
                                              ClaimsPrincipal user,
                                              bool requiresLeader,
                                              IReadIndex readIndex,
                                              uint?maxWindowSize,
                                              uint checkpointIntervalMultiplier,
                                              Func <Position, Task> checkpointReached,
                                              CancellationToken cancellationToken)
                {
                    if (bus == null)
                    {
                        throw new ArgumentNullException(nameof(bus));
                    }

                    if (eventFilter == null)
                    {
                        throw new ArgumentNullException(nameof(eventFilter));
                    }

                    if (readIndex == null)
                    {
                        throw new ArgumentNullException(nameof(readIndex));
                    }

                    if (checkpointReached == null)
                    {
                        throw new ArgumentNullException(nameof(checkpointReached));
                    }

                    if (checkpointIntervalMultiplier == 0)
                    {
                        throw new ArgumentOutOfRangeException(nameof(checkpointIntervalMultiplier));
                    }

                    _subscriptionId = subscriptionId;
                    _bus            = bus;
                    _nextPosition   = position == Position.End
                                                ? Position.FromInt64(readIndex.LastIndexedPosition, readIndex.LastIndexedPosition)
                                                : position;
                    _startPosition       = position == Position.End ? Position.Start : position;
                    _resolveLinks        = resolveLinks;
                    _eventFilter         = eventFilter;
                    _user                = user;
                    _requiresLeader      = requiresLeader;
                    _checkpointReached   = checkpointReached;
                    _maxWindowSize       = maxWindowSize ?? ReadBatchSize;
                    _checkpointInterval  = checkpointIntervalMultiplier * _maxWindowSize;
                    _disposedTokenSource = new CancellationTokenSource();
                    _buffer              = new ConcurrentQueueWrapper <(ResolvedEvent, Position?)>();

                    _tokenRegistration         = cancellationToken.Register(_disposedTokenSource.Dispose);
                    _currentPosition           = _startPosition;
                    _checkpointIntervalCounter = 0;
                    Log.Information("Catch-up subscription {subscriptionId} to $all:{eventFilter} running...",
                                    _subscriptionId, _eventFilter);
                }
Exemple #4
0
 public void AddFilter(IEventFilter filter)
 {
     if (filter != null)
     {
         _filters.Add(filter);
     }
 }
Exemple #5
0
        /// <summary>
        /// Waits for the specified events.
        /// </summary>
        /// <typeparam name="T">Type of events.</typeparam>
        /// <param name="filter">Optional filtering predicate. Event wait will end as soon as it returns false.</param>
        /// <param name="handle">The filter handle, if applicable.</param>
        /// <param name="types">Types of the events to wait for.
        /// If not provided, all events will be passed to the filter.</param>
        /// <returns>Ignite event.</returns>
        private T WaitForLocal0 <T>(IEventFilter <T> filter, ref long handle, params int[] types) where T : IEvent
        {
            if (filter != null)
            {
                handle = Ignite.HandleRegistry.Allocate(new LocalEventFilter
                {
                    InvokeFunc = stream => InvokeLocalFilter(stream, filter)
                });
            }

            var hnd = handle;

            return(DoOutInOp((int)Op.WaitForLocal,
                             writer =>
            {
                if (filter != null)
                {
                    writer.WriteBoolean(true);
                    writer.WriteLong(hnd);
                }
                else
                {
                    writer.WriteBoolean(false);
                }

                WriteEventTypes(types, writer);
            },
                             reader => EventReader.Read <T>(Marshaller.StartUnmarshal(reader))));
        }
Exemple #6
0
 public void AddFilter(IEventFilter filter)
 {
     if (filter != null)
     {
         _filters.Add(filter);
     }
 }
Exemple #7
0
        /// <summary>
        /// Creates a user filter wrapper.
        /// </summary>
        /// <typeparam name="T">Event object type.</typeparam>
        /// <param name="listener">Listener.</param>
        /// <param name="type">Event type.</param>
        /// <returns>Created wrapper.</returns>
        private LocalHandledEventFilter CreateLocalFilter <T>(IEventFilter <T> listener, int type) where T : IEvent
        {
            var result = new LocalHandledEventFilter(
                stream => InvokeLocalFilter(stream, listener),
                unused =>
            {
                lock (_localFilters)
                {
                    Dictionary <int, LocalHandledEventFilter> filters;

                    if (_localFilters.TryGetValue(listener, out filters))
                    {
                        filters.Remove(type);

                        if (filters.Count == 0)
                        {
                            _localFilters.Remove(listener);
                        }
                    }
                }
            });

            result.Handle = Ignite.HandleRegistry.Allocate(result);

            return(result);
        }
        private Expression <Func <EventEntity, bool> > GetExpression(IEventFilter filter)
        {
            var predicate = PredicateBuilder.New <EventEntity>();

            predicate = filter.IsDeleted.HasValue ?
                        predicate.And(p => p.IsDeleted == filter.IsDeleted.Value) :
                        predicate.And(p => p.IsDeleted != true);

            if (filter.StartDate.HasValue)
            {
                predicate = predicate.And(p => p.StartDate >= filter.StartDate);
            }

            if (filter.EndDate.HasValue)
            {
                predicate = predicate.And(p => p.EndDate <= filter.EndDate);
            }

            if (!string.IsNullOrEmpty(filter.OrganizerId))
            {
                predicate = predicate.And(p => p.OrganizerId == filter.OrganizerId);
            }

            if (filter.EventType != null)
            {
                predicate = predicate.And(p => p.EventType == filter.EventType);
            }

            if (filter.RoomId.HasValue)
            {
                predicate = predicate.And(p => p.RoomId == filter.RoomId);
            }

            return(predicate);
        }
Exemple #9
0
        public void AddEventHandler(object handler, IEventFilter filter = null)
        {
            Type commandHandlerType = handler.GetType();

            MethodInfo[] methods = commandHandlerType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            foreach (var method in methods)
            {
                var connectAttr    = method.GetCustomAttribute(typeof(Connect));
                var disconnectAttr = method.GetCustomAttribute(typeof(Disconnect));
                var commandAttr    = method.GetCustomAttribute(typeof(Command));

                if (connectAttr != null)
                {
                    AddConnectHandlerWithAttribute(handler, filter, method);
                }
                if (disconnectAttr != null)
                {
                    AddDisconnectHandlerWithAttribute(handler, filter, method);
                }
                if (commandAttr != null)
                {
                    AddCommandHandlerWithAttribute(handler, filter, method);
                }
            }
        }
Exemple #10
0
        /// <summary>
        /// Adds an event listener for local events.
        /// </summary>
        /// <typeparam name="T">Type of events.</typeparam>
        /// <param name="listener">Predicate that is called on each received event.</param>
        /// <param name="type">Event type for which this listener will be notified</param>
        private void LocalListen <T>(IEventFilter <T> listener, int type) where T : IEvent
        {
            lock (_localFilters)
            {
                Dictionary <int, LocalHandledEventFilter> filters;

                if (!_localFilters.TryGetValue(listener, out filters))
                {
                    filters = new Dictionary <int, LocalHandledEventFilter>();

                    _localFilters[listener] = filters;
                }

                LocalHandledEventFilter localFilter;

                if (!filters.TryGetValue(type, out localFilter))
                {
                    localFilter = CreateLocalFilter(listener, type);

                    filters[type] = localFilter;
                }

                UU.EventsLocalListen(Target, localFilter.Handle, type);
            }
        }
Exemple #11
0
        /// <summary>
        /// Extracts the event handler details such as event filter.
        /// </summary>
        /// <param name="eventHandler">The event handler delegate.</param>
        /// <param name="eventFilter">The event filter.</param>
        private void ExtractEventHandlerDetails(ref Delegate eventHandler, ref IEventFilter eventFilter)
        {
            if (eventHandler == null || eventHandler.Method == null)
            {
                return;
            }

            // handle attached event filters, if any
            if (eventHandler.Target is IFilteredEventHandler)
            {
                var filtered = eventHandler.Target as IFilteredEventHandler;
                eventHandler = filtered.EventHandler;
                eventFilter  = filtered.EventFilter;
            }

            // handle special case: session-bound events
            var parameters = eventHandler.Method.GetParameters();

            if (parameters.Length == 2 && typeof(SessionEventArgs).IsAssignableFrom(parameters[1].ParameterType))
            {
                // if SessionEventFilter is already attached, do not create a new filter
                if (eventFilter == null || !eventFilter.Contains <SessionEventFilter>())
                {
                    var sessionFilter = new SessionEventFilter(_sessionID);
                    eventFilter = sessionFilter.Combine(eventFilter);
                }
            }
        }
Exemple #12
0
        /** <inheritdoc /> */
        public override T WaitForLocal <T>(IEventFilter <T> filter, params int[] types)
        {
            _lastAsyncOp.Value = (int)Op.WaitForLocal;

            long hnd = 0;

            try
            {
                var result = WaitForLocal0(filter, ref hnd, types);

                if (filter != null)
                {
                    // Dispose handle as soon as future ends.
                    var fut = GetFuture <T>();

                    _curFut.Value = fut;

                    fut.Listen(() => Ignite.HandleRegistry.Release(hnd));
                }
                else
                {
                    _curFut.Value = null;
                }

                return(result);
            }
            catch (Exception)
            {
                Ignite.HandleRegistry.Release(hnd);
                throw;
            }
        }
        public void AddCommandHandler(object commandHandler, IEventFilter filter = null)
        {
            MethodInfo deserializerMethod = typeof(ISerializer).GetMethod(nameof(serializer.Deserialize));
            Type       commandHandlerType = commandHandler.GetType();

            MethodInfo[] methods = commandHandlerType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            foreach (var method in methods)
            {
                var connectAttr    = method.GetCustomAttribute(typeof(Connect));
                var disconnectAttr = method.GetCustomAttribute(typeof(Disconnect));
                var commandAttr    = method.GetCustomAttribute(typeof(Command));

                if (connectAttr != null)
                {
                    AddConnectHandler(commandHandler, filter, method);
                }
                if (disconnectAttr != null)
                {
                    AddDisconnectHandler(commandHandler, filter, method);
                }
                if (commandAttr != null)
                {
                    AddCommandHandler(commandHandler, filter, method, deserializerMethod);
                }
            }
        }
Exemple #14
0
 public StatsSubscriber(EventStoreClient eventStoreClient, string subscriptionId,
                        ICheckpointStore checkpointStore, IEventSerializer eventSerializer,
                        IEnumerable <IEventHandler> eventHandlers, ILoggerFactory loggerFactory = null,
                        IEventFilter eventFilter = null, SubscriptionGapMeasure measure = null) : base(eventStoreClient,
                                                                                                       subscriptionId, checkpointStore, eventSerializer, eventHandlers, loggerFactory, eventFilter, measure)
 {
 }
Exemple #15
0
        public Guid?RemoteListen <T>(int bufSize = 1, TimeSpan?interval = null, bool autoUnsubscribe = true,
                                     IEventFilter <T> localListener = null, IEventFilter <T> remoteFilter = null, params int[] types)
            where T : IEvent
        {
            IgniteArgumentCheck.Ensure(bufSize > 0, "bufSize", "should be > 0");
            IgniteArgumentCheck.Ensure(interval == null || interval.Value.TotalMilliseconds > 0, "interval", "should be null or >= 0");

            return(DoOutInOp((int)Op.RemoteListen,
                             writer =>
            {
                writer.WriteInt(bufSize);
                writer.WriteLong((long)(interval == null ? 0 : interval.Value.TotalMilliseconds));
                writer.WriteBoolean(autoUnsubscribe);

                writer.WriteBoolean(localListener != null);

                if (localListener != null)
                {
                    var listener = new RemoteListenEventFilter(Ignite, e => localListener.Invoke((T)e));
                    writer.WriteLong(Ignite.HandleRegistry.Allocate(listener));
                }

                writer.WriteBoolean(remoteFilter != null);

                if (remoteFilter != null)
                {
                    writer.Write(remoteFilter);
                }

                WriteEventTypes(types, writer);
            },
                             reader => Marshaller.StartUnmarshal(reader).ReadGuid()));
        }
Exemple #16
0
        private static ReadReq.Types.Options.Types.FilterOptions GetFilterOptions(IEventFilter filter)
        {
            if (filter == null)
            {
                return(null);
            }

            var options = filter switch {
                StreamFilter _ => new ReadReq.Types.Options.Types.FilterOptions {
                    StreamName = (filter.Prefixes, filter.Regex) switch {
                        (PrefixFilterExpression[] _, RegularFilterExpression _)
                        when(filter.Prefixes?.Length ?? 0) == 0 &&
                        filter.Regex != RegularFilterExpression.None =>
                        new ReadReq.Types.Options.Types.FilterOptions.Types.Expression
                        {
                            Regex = filter.Regex
                        },
                        (PrefixFilterExpression[] _, RegularFilterExpression _)
                        when(filter.Prefixes?.Length ?? 0) != 0 &&
                        filter.Regex == RegularFilterExpression.None =>
                        new ReadReq.Types.Options.Types.FilterOptions.Types.Expression
                        {
                            Prefix = { Array.ConvertAll(filter.Prefixes, e => (string)e) }
                        },
                        _ => throw new InvalidOperationException()
                    }
                },
Exemple #17
0
        /** <inheritDoc /> */
        public Task <T> WaitForLocalAsync <T>(IEventFilter <T> filter, params int[] types) where T : IEvent
        {
            var hnd = GetFilterHandle(filter);

            try
            {
                var task = DoOutOpAsync((int)Op.WaitForLocalAsync, writer =>
                {
                    writer.WriteObject(hnd);
                    WriteEventTypes(types, writer);
                }, convertFunc: EventReader.Read <T>);

                if (hnd != null)
                {
                    // Dispose handle as soon as future ends.
                    task.ContinueWith(x => Ignite.HandleRegistry.Release(hnd.Value));
                }

                return(task);
            }
            catch (Exception)
            {
                if (hnd != null)
                {
                    Ignite.HandleRegistry.Release(hnd.Value);
                }

                throw;
            }
        }
Exemple #18
0
            public AllSubscriptionFiltered(IPublisher bus,
                                           Position?startPosition,
                                           bool resolveLinks,
                                           IEventFilter eventFilter,
                                           ClaimsPrincipal user,
                                           bool requiresLeader,
                                           IReadIndex readIndex,
                                           uint?maxSearchWindow,
                                           uint checkpointIntervalMultiplier,
                                           Func <Position, Task> checkpointReached,
                                           CancellationToken cancellationToken)
            {
                if (bus == null)
                {
                    throw new ArgumentNullException(nameof(bus));
                }

                if (eventFilter == null)
                {
                    throw new ArgumentNullException(nameof(eventFilter));
                }

                if (readIndex == null)
                {
                    throw new ArgumentNullException(nameof(readIndex));
                }

                if (checkpointReached == null)
                {
                    throw new ArgumentNullException(nameof(checkpointReached));
                }

                if (checkpointIntervalMultiplier == 0)
                {
                    throw new ArgumentOutOfRangeException(nameof(checkpointIntervalMultiplier));
                }

                _subscriptionId  = Guid.NewGuid();
                _bus             = bus;
                _resolveLinks    = resolveLinks;
                _eventFilter     = eventFilter;
                _user            = user;
                _requiresLeader  = requiresLeader;
                _readIndex       = readIndex;
                _maxSearchWindow = maxSearchWindow;
                _checkpointIntervalMultiplier = checkpointIntervalMultiplier;
                _checkpointReached            = checkpointReached;
                _cancellationToken            = cancellationToken;
                _subscriptionStarted          = new TaskCompletionSource <bool>();
                _subscriptionStarted.SetResult(true);

                _inner = startPosition == Position.End
                                        ? (IStreamSubscription) new LiveStreamSubscription(_subscriptionId, _bus,
                                                                                           Position.FromInt64(_readIndex.LastIndexedPosition, _readIndex.LastIndexedPosition),
                                                                                           _resolveLinks, _eventFilter, _user, _requiresLeader, _maxSearchWindow,
                                                                                           _checkpointIntervalMultiplier, checkpointReached, _cancellationToken)
                                        : new CatchupAllSubscription(_subscriptionId, bus, startPosition ?? Position.Start, resolveLinks,
                                                                     _eventFilter, user, _requiresLeader, readIndex, _maxSearchWindow, _checkpointIntervalMultiplier, checkpointReached,
                                                                     cancellationToken);
            }
Exemple #19
0
        /** <inheritDoc /> */
        public Task <T> WaitForLocalAsync <T>(IEventFilter <T> filter, params int[] types) where T : IEvent
        {
            long hnd = 0;

            try
            {
                AsyncInstance.WaitForLocal0(filter, ref hnd, types);

                // ReSharper disable once RedundantTypeArgumentsOfMethod (won't compile in VS2010)
                var fut = GetFuture <T>((futId, futTyp) => UU.TargetListenFutureForOperation(AsyncInstance.Target, futId,
                                                                                             futTyp, (int)Op.WaitForLocal), convertFunc: reader => (T)EventReader.Read <IEvent>(reader));

                if (filter != null)
                {
                    // Dispose handle as soon as future ends.
                    fut.Task.ContinueWith(x => Ignite.HandleRegistry.Release(hnd));
                }

                return(fut.Task);
            }
            catch (Exception)
            {
                Ignite.HandleRegistry.Release(hnd);
                throw;
            }
        }
Exemple #20
0
        private Guid SubscribeCore(IEventFilter filter,
                                   DataReceiveEventHandler receiveEventHandler,
                                   out IReceiverChannel channel)
        {
            Guid cookie;

            // создаем канал ответа (интегральный)
            var localChannel = UnitySingleton.Resolve <ITransport>().CreateIntegralChannel();

            channel = (IReceiverChannel)localChannel;

            // создаем кук
            cookie = Guid.NewGuid();

            // подписываемся на событие прихода данных по каналу
            if (receiveEventHandler != null)
            {
                channel.DataReceived += receiveEventHandler;
            }

            // посылаем команду в Blackboard
            _localBlackboard.Subscribe(filter, localChannel as ISenderChannel, cookie);

            return(cookie);
        }
Exemple #21
0
 /// <summary>
 /// Initializes a new instance of the <see cref='ConsoleTraceListener'/> class.
 /// </summary>
 /// <param name="name">The name.</param>
 /// <param name="filter">The filter.</param>
 /// <param name="showEventType">A value indicating whether to show the event type.</param>
 /// <param name="showEventId">A value indicating whether to show the event id.</param>
 public ConsoleTraceListener(
     string name,
     IEventFilter filter,
     bool showEventType,
     bool showEventId)
     : base(name, filter, showEventType, showEventId)
 {
 }
Exemple #22
0
        /** <inheritdoc /> */
        public override Guid RemoteListen <T>(int bufSize = 1, TimeSpan?interval = null, bool autoUnsubscribe = true,
                                              IEventFilter <T> localListener = null, IEventFilter <T> remoteFilter = null, params int[] types)
        {
            _lastAsyncOp.Value = (int)Op.RemoteListen;
            _curFut.Value      = null;

            return(base.RemoteListen(bufSize, interval, autoUnsubscribe, localListener, remoteFilter, types));
        }
 /// <summary>
 /// Asynchronously reads all events in the node forward (e.g. beginning to end).
 /// </summary>
 /// <param name="direction">The direction in which to read. <see cref="Direction"/></param>
 /// <param name="position">The position to start reading from.</param>
 /// <param name="maxCount">The maximum count to read.</param>
 /// <param name="resolveLinkTos">Whether to resolve LinkTo events automatically.</param>
 /// <param name="filter">The optional <see cref="IEventFilter"/> to apply.</param>
 /// <param name="userCredentials">The optional user credentials to perform operation with.</param>
 /// <param name="cancellationToken">The optional <see cref="System.Threading.CancellationToken"/>.</param>
 /// <returns></returns>
 public IAsyncEnumerable <ResolvedEvent> ReadAllAsync(
     Direction direction,
     Position position,
     ulong maxCount,
     bool resolveLinkTos                 = false,
     IEventFilter filter                 = null,
     UserCredentials userCredentials     = default,
     CancellationToken cancellationToken = default) => ReadInternal(new ReadReq {
 public CallistoJaegerEventListener(ITracer tracer, IEventFilter eventFilter, IOptions <CallistoTracerOptions> options)
 {
     _tracer        = tracer;
     _eventFilter   = eventFilter;
     _events        = options.Value.TracedDbOperations;
     _maxPacketSize = ConfigureMaxPacketSize(options.Value);
     _spanCache     = new ConcurrentDictionary <int, ISpan>();
 }
Exemple #25
0
        /// <summary>
        /// Метод подписки на события журнала.
        /// </summary>
        /// <param name="filter">Фильтр событий.</param>
        /// <param name="channel">Канал передачи событий.</param>
        /// <param name="cookie">Идентификатор подписки.</param>
        void ISrvcBlackboard.Subscribe(IEventFilter filter, ChannelDescription channel, Guid cookie)
        {
            Logger.Debug("ISrvcBlackboard.Subscribe: подписался {0}", cookie);
            // создаем канал
            ISenderChannel ch = channel != null?UnitySingleton.Resolve <ITransport>().CreateSenderChannel(channel) : null;

            _subsribeTask.Run(() => (this as IBlackboard).Subscribe(filter, ch, cookie));
        }
Exemple #26
0
        /** <inheritDoc /> */
        public Task <ICollection <T> > RemoteQueryAsync <T>(IEventFilter <T> filter, TimeSpan?timeout = null,
                                                            params int[] types) where T : IEvent
        {
            AsyncInstance.RemoteQuery(filter, timeout, types);

            // ReSharper disable once RedundantTypeArgumentsOfMethod (won't compile in VS2010)
            return(GetFuture <ICollection <T> >((futId, futTyp) => UU.TargetListenFutureForOperation(AsyncInstance.Target,
                                                                                                     futId, futTyp, (int)Op.RemoteQuery), convertFunc: ReadEvents <T>).Task);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="FilteredSystemEventHandler"/> class.
        /// </summary>
        /// <param name="eventHandler">The event handler.</param>
        /// <param name="eventFilter">The event filter.</param>
        /// <param name="filterLocally">Whether the filter should also work when used locally.</param>
        public FilteredSystemEventHandler(EventHandler eventHandler, IEventFilter eventFilter, bool filterLocally)
        {
            IEventFilter sourceFilter;
            ExtractSourceHandler(eventHandler, out eventHandler, out sourceFilter);

            EventHandler = eventHandler;
            EventFilter = eventFilter.Combine(sourceFilter);
            FilterLocally = filterLocally;
        }
Exemple #28
0
 /// <summary>
 /// Метод подписки на события журнала.
 /// </summary>
 /// <param name="filter">Фильтр событий.</param>
 /// <param name="channel">Канал передачи событий.</param>
 /// <param name="cookie">Идентификатор подписки.</param>
 void IBlackboard.Subscribe(IEventFilter filter, ISenderChannel channel, Guid cookie)
 {
     // локальный подписчик
     if (filter.Host == UnitySingleton.Resolve <ITransport>().HostID)
     {
         // добавляем нового подписчика в карту
         _localEventsSubscribers.Add(cookie, filter, channel);
     }
 }
Exemple #29
0
 /// <summary>
 /// Subscribes to all events. Use this when you have no checkpoint.
 /// </summary>
 /// <param name="eventAppeared">A Task invoked and awaited when a new event is received over the subscription.</param>
 /// <param name="resolveLinkTos">Whether to resolve LinkTo events automatically.</param>
 /// <param name="subscriptionDropped">An action invoked if the subscription is dropped.</param>
 /// <param name="filter">The optional <see cref="IEventFilter"/> to apply.</param>
 /// <param name="userCredentials">The optional user credentials to perform operation with.</param>
 /// <param name="cancellationToken">The optional <see cref="System.Threading.CancellationToken"/>.</param>
 /// <returns></returns>
 public StreamSubscription SubscribeToAll(
     Func <StreamSubscription, ResolvedEvent, CancellationToken, Task> eventAppeared,
     bool resolveLinkTos = false,
     Action <StreamSubscription, SubscriptionDroppedReason, Exception> subscriptionDropped = default,
     IEventFilter filter                 = null,
     UserCredentials userCredentials     = default,
     CancellationToken cancellationToken = default) => SubscribeToAll(eventAppeared,
                                                                      _settings.OperationOptions.Clone(), resolveLinkTos, subscriptionDropped, filter, userCredentials,
                                                                      cancellationToken);
Exemple #30
0
        /** <inheritDoc /> */
        public ICollection <T> RemoteQuery <T>(IEventFilter <T> filter, TimeSpan?timeout = null, params int[] types)
            where T : IEvent
        {
            IgniteArgumentCheck.NotNull(filter, "filter");

            return(DoOutInOp((int)Op.RemoteQuery,
                             writer => WriteRemoteQuery(filter, timeout, types, writer),
                             reader => ReadEvents <T>(reader)));
        }
Exemple #31
0
        /** <inheritDoc /> */
        public Task <ICollection <T> > RemoteQueryAsync <T>(IEventFilter <T> filter, TimeSpan?timeout = null,
                                                            params int[] types) where T : IEvent
        {
            IgniteArgumentCheck.NotNull(filter, "filter");

            // ReSharper disable once RedundantTypeArgumentsOfMethod (won't compile in VS2010)
            return(DoOutOpAsync <ICollection <T> >((int)Op.RemoteQueryAsync,
                                                   w => WriteRemoteQuery(filter, timeout, types, w), convertFunc: ReadEvents <T>));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="FilteredSystemEventHandler"/> class.
        /// </summary>
        /// <param name="eventHandler">The event handler.</param>
        /// <param name="eventFilter">The event filter.</param>
        /// <param name="filterLocally">Whether the filter should also work when used locally.</param>
        public FilteredSystemEventHandler(EventHandler eventHandler, IEventFilter eventFilter, bool filterLocally)
        {
            IEventFilter sourceFilter;

            ExtractSourceHandler(eventHandler, out eventHandler, out sourceFilter);

            EventHandler  = eventHandler;
            EventFilter   = eventFilter.Combine(sourceFilter);
            FilterLocally = filterLocally;
        }
        private void ExtractSourceHandler(EventHandler eventHandler, out EventHandler sourceHandler, out IEventFilter sourceFilter)
        {
            sourceHandler = eventHandler;
            sourceFilter = default(IEventFilter);

            while (sourceHandler.Target is IFilteredEventHandler)
            {
                var filtered = sourceHandler.Target as IFilteredEventHandler;
                sourceHandler = filtered.EventHandler as EventHandler;
                sourceFilter = filtered.EventFilter.Combine(sourceFilter);
            }
        }
Exemple #34
0
 public Logger(string loggerName, IEventFilter filter, Logger parentLogger, ManualResetEvent queueEnabledEvent)
 {
     CodeContract.Requires(!string.IsNullOrEmpty(loggerName));
     _queueEnabledEvent = queueEnabledEvent;
     LoggerName = loggerName;
     if (filter != null)
     {
         _traceLevelFilter = filter;
         _filters.Add(filter);
     }
     if (parentLogger == null)
     {
         _bAsync = true;
         _queue = new BlockingQueue<LoggerEvent>();
         ThreadUtils.StartBackgroundThread(MonitorQueue);
     }
     else
     {
         _parentLogger = parentLogger;
         _queue = _parentLogger._queue;
     }
 }
Exemple #35
0
        /// <summary>
        /// Extracts the event handler details such as event filter.
        /// </summary>
        /// <param name="eventHandler">The event handler delegate.</param>
        /// <param name="eventFilter">The event filter.</param>
        private void ExtractEventHandlerDetails(ref Delegate eventHandler, ref IEventFilter eventFilter)
        {
            if (eventHandler == null || eventHandler.Method == null)
            {
                return;
            }

            // handle attached event filters, if any
            if (eventHandler.Target is IFilteredEventHandler)
            {
                var filtered = eventHandler.Target as IFilteredEventHandler;
                eventHandler = filtered.EventHandler;
                eventFilter = filtered.EventFilter;
            }

            // handle special case: session-bound events
            var parameters = eventHandler.Method.GetParameters();
            if (parameters.Length == 2 && typeof(SessionEventArgs).IsAssignableFrom(parameters[1].ParameterType))
            {
                // if SessionEventFilter is already attached, do not create a new filter
                if (eventFilter == null || !eventFilter.Contains<SessionEventFilter>())
                {
                    var sessionFilter = new SessionEventFilter(_sessionID);
                    eventFilter = sessionFilter.Combine(eventFilter);
                }
            }
        }
Exemple #36
0
 /// <summary>
 /// Sets the "EventFilter" attached property
 /// </summary>
 /// <param name="obj"></param>
 /// <param name="value"></param>
 public static void SetEventFilter(DependencyObject obj, IEventFilter value)
 {
     obj.SetValue(EventFilterProperty, value);
 }
Exemple #37
0
 private void RemoveFilter(IEventFilter filter)
 {
     _filters.Remove(filter);
 }
Exemple #38
0
 private void AddFilter(IEventFilter filter)
 {
     _filters.Add(filter);
 }