Пример #1
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="agentInstanceContext">The agent instance context.</param>
        /// <param name="timeWindowViewFactory">for copying the view in a group-by</param>
        /// <param name="timeDeltaComputation">is the computation of number of milliseconds before events gets pushedout of the timeWindow as oldData in the Update method.</param>
        /// <param name="viewUpdatedCollection">is a collection the view must Update when receiving events</param>
        public TimeWindowView(
            AgentInstanceViewFactoryChainContext agentInstanceContext,
            TimeWindowViewFactory timeWindowViewFactory,
            ExprTimePeriodEvalDeltaConst timeDeltaComputation,
            ViewUpdatedCollection viewUpdatedCollection)
        {
            _agentInstanceContext  = agentInstanceContext;
            _timeWindowViewFactory = timeWindowViewFactory;
            _timeDeltaComputation  = timeDeltaComputation;
            _viewUpdatedCollection = viewUpdatedCollection;
            _scheduleSlot          = agentInstanceContext.StatementContext.ScheduleBucket.AllocateSlot();
            _timeWindow            = new TimeWindow(agentInstanceContext.IsRemoveStream);

            ScheduleHandleCallback callback = new ProxyScheduleHandleCallback
            {
                ProcScheduledTrigger = extensionServicesContext => Instrument.With(
                    i => i.QViewScheduledEval(this, timeWindowViewFactory.ViewName),
                    i => i.AViewScheduledEval(),
                    Expire)
            };

            _handle = new EPStatementHandleCallback(agentInstanceContext.EpStatementAgentInstanceHandle, callback);

            if (agentInstanceContext.StatementContext.ScheduleAdjustmentService != null)
            {
                agentInstanceContext.StatementContext.ScheduleAdjustmentService.AddCallback(this);
            }
            agentInstanceContext.AddTerminationCallback(Stop);
        }
Пример #2
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="timeBatchViewFactory">for copying this view in a group-by</param>
        /// <param name="agentInstanceContext">The agent instance context.</param>
        /// <param name="timeDeltaComputation">computes the number of milliseconds to batch events for</param>
        /// <param name="referencePoint">is the reference point onto which to base intervals, or null ifthere is no such reference point supplied</param>
        /// <param name="forceOutput">is true if the batch should produce empty output if there is no value to output following time intervals</param>
        /// <param name="isStartEager">is true for start-eager</param>
        /// <param name="viewUpdatedCollection">is a collection that the view must Update when receiving events</param>
        public TimeBatchView(TimeBatchViewFactory timeBatchViewFactory,
                             AgentInstanceViewFactoryChainContext agentInstanceContext,
                             ExprTimePeriodEvalDeltaConst timeDeltaComputation,
                             long?referencePoint,
                             bool forceOutput,
                             bool isStartEager,
                             ViewUpdatedCollection viewUpdatedCollection)
        {
            _agentInstanceContext  = agentInstanceContext;
            _timeBatchViewFactory  = timeBatchViewFactory;
            _timeDeltaComputation  = timeDeltaComputation;
            _initialReferencePoint = referencePoint;
            _isStartEager          = isStartEager;
            _viewUpdatedCollection = viewUpdatedCollection;
            _isForceOutput         = forceOutput;

            _scheduleSlot = agentInstanceContext.StatementContext.ScheduleBucket.AllocateSlot();

            // schedule the first callback
            if (isStartEager)
            {
                if (_currentReferencePoint == null)
                {
                    _currentReferencePoint = agentInstanceContext.StatementContext.SchedulingService.Time;
                }
                ScheduleCallback();
                _isCallbackScheduled = true;
            }

            agentInstanceContext.AddTerminationCallback(Stop);
        }
Пример #3
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="timeBatchViewFactory">for copying this view in a group-by</param>
        /// <param name="agentInstanceContext">The agent instance context.</param>
        /// <param name="timeDeltaComputation">The time delta computation.</param>
        public TimeAccumViewRStream(
            TimeAccumViewFactory timeBatchViewFactory,
            AgentInstanceViewFactoryChainContext agentInstanceContext,
            ExprTimePeriodEvalDeltaConst timeDeltaComputation)
        {
            _agentInstanceContext = agentInstanceContext;
            _factory = timeBatchViewFactory;
            _timeDeltaComputation = timeDeltaComputation;

            _scheduleSlot = agentInstanceContext.StatementContext.ScheduleBucket.AllocateSlot();

            ScheduleHandleCallback callback = new ProxyScheduleHandleCallback
            {
                ProcScheduledTrigger = extensionServicesContext =>
                {
                    using (Instrument.With(
                               i => i.QViewScheduledEval(this, _factory.ViewName),
                               i => i.AViewScheduledEval()))
                    {
                        SendRemoveStream();
                    }
                }
            };

            _handle = new EPStatementHandleCallback(agentInstanceContext.EpStatementAgentInstanceHandle, callback);
            agentInstanceContext.AddTerminationCallback(Stop);
        }
Пример #4
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="timeBatchViewFactory">for copying this view in a group-by</param>
        /// <param name="agentInstanceContext">The agent instance context.</param>
        /// <param name="timeDeltaComputation">is the number of milliseconds to batch events for</param>
        /// <param name="numberOfEvents">is the event count before the batch fires off</param>
        /// <param name="forceOutput">is true if the batch should produce empty output if there is no value to output following time intervals</param>
        /// <param name="isStartEager">is true for start-eager</param>
        /// <param name="viewUpdatedCollection">is a collection that the view must Update when receiving events</param>
        public TimeLengthBatchView(
            TimeLengthBatchViewFactory timeBatchViewFactory,
            AgentInstanceViewFactoryChainContext agentInstanceContext,
            ExprTimePeriodEvalDeltaConst timeDeltaComputation,
            long numberOfEvents,
            bool forceOutput,
            bool isStartEager,
            ViewUpdatedCollection viewUpdatedCollection)
        {
            _agentInstanceContext       = agentInstanceContext;
            _timeLengthBatchViewFactory = timeBatchViewFactory;
            _timeDeltaComputation       = timeDeltaComputation;
            _numberOfEvents             = numberOfEvents;
            _isStartEager          = isStartEager;
            _viewUpdatedCollection = viewUpdatedCollection;
            _isForceOutput         = forceOutput;

            _scheduleSlot = agentInstanceContext.StatementContext.ScheduleBucket.AllocateSlot();

            // schedule the first callback
            if (isStartEager)
            {
                ScheduleCallback(0);
            }

            agentInstanceContext.AddTerminationCallback(Stop);
        }
Пример #5
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="viewUpdatedCollection">is a collection that the view must update when receiving events</param>
        /// <param name="timeBatchViewFactory">fr copying this view in a group-by</param>
        /// <param name="agentInstanceContext">is required view services</param>
        /// <param name="timeDeltaComputation">delta computation</param>
        public TimeAccumView(
            TimeAccumViewFactory timeBatchViewFactory,
            AgentInstanceViewFactoryChainContext agentInstanceContext,
            ExprTimePeriodEvalDeltaConst timeDeltaComputation,
            ViewUpdatedCollection viewUpdatedCollection)
        {
            _agentInstanceContext = agentInstanceContext;
            _factory = timeBatchViewFactory;
            _timeDeltaComputation  = timeDeltaComputation;
            _viewUpdatedCollection = viewUpdatedCollection;

            _scheduleSlot = agentInstanceContext.StatementContext.ScheduleBucket.AllocateSlot();

            var callback = new ProxyScheduleHandleCallback
            {
                ProcScheduledTrigger = extensionServicesContext =>
                {
                    if (InstrumentationHelper.ENABLED)
                    {
                        InstrumentationHelper.Get().QViewScheduledEval(this, _factory.ViewName);
                    }
                    SendRemoveStream();
                    if (InstrumentationHelper.ENABLED)
                    {
                        InstrumentationHelper.Get().AViewScheduledEval();
                    }
                }
            };

            _handle = new EPStatementHandleCallback(agentInstanceContext.EpStatementAgentInstanceHandle, callback);
            agentInstanceContext.AddTerminationCallback(this);
        }
Пример #6
0
        /// <summary>
        /// Ctor.
        /// </summary>
        /// <param name="agentInstanceContext">The agent instance context.</param>
        /// <param name="viewFactory">for copying this view in a group-by</param>
        /// <param name="timestampExpr">the property name of the event supplying timestamp values</param>
        /// <param name="timestampEvaluator">The timestamp evaluator.</param>
        /// <param name="timeDeltaComputation">The time delta computation.</param>
        /// <param name="optionalSortedRandomAccess">is the friend class handling the random access, if required byexpressions</param>
        public TimeOrderView(
            AgentInstanceViewFactoryChainContext agentInstanceContext,
            ViewFactory viewFactory,
            ExprNode timestampExpr,
            ExprEvaluator timestampEvaluator,
            ExprTimePeriodEvalDeltaConst timeDeltaComputation,
            IStreamSortRankRandomAccess optionalSortedRandomAccess)
        {
            _agentInstanceContext       = agentInstanceContext;
            _viewFactory                = viewFactory;
            _timestampExpression        = timestampExpr;
            _timestampEvaluator         = timestampEvaluator;
            _timeDeltaComputation       = timeDeltaComputation;
            _optionalSortedRandomAccess = optionalSortedRandomAccess;
            _scheduleSlot               = agentInstanceContext.StatementContext.ScheduleBucket.AllocateSlot();

            _sortedEvents = new OrderedDictionary <Object, Object>();

            ScheduleHandleCallback callback = new ProxyScheduleHandleCallback
            {
                ProcScheduledTrigger = extensionServicesContext => Instrument.With(
                    i => i.QViewScheduledEval(this, _viewFactory.ViewName),
                    i => i.AViewScheduledEval(),
                    Expire)
            };

            _handle = new EPStatementHandleCallback(agentInstanceContext.EpStatementAgentInstanceHandle, callback);
            agentInstanceContext.AddTerminationCallback(Stop);
        }
Пример #7
0
        public void Attach(EventType parentEventType, StatementContext statementContext, ViewFactory optionalParentFactory, IList <ViewFactory> parentViewFactories)
        {
            String windowName = ViewName;

            ExprNode[] validated = ViewFactorySupport.Validate(windowName, parentEventType, statementContext, _viewParameters, true);
            if (_viewParameters.Count < 2 || _viewParameters.Count > 3)
            {
                throw new ViewParameterException(ViewParamMessage);
            }

            // validate first parameter: timestamp expression
            if (!validated[0].ExprEvaluator.ReturnType.IsNumeric())
            {
                throw new ViewParameterException(ViewParamMessage);
            }
            TimestampExpression     = validated[0];
            TimestampExpressionEval = TimestampExpression.ExprEvaluator;
            ViewFactorySupport.AssertReturnsNonConstant(windowName, validated[0], 0);

            TimeDeltaComputation = ViewFactoryTimePeriodHelper.ValidateAndEvaluateTimeDelta(ViewName, statementContext, _viewParameters[1], ViewParamMessage, 1);

            // validate optional parameters
            if (validated.Length == 3)
            {
                Object constant = ViewFactorySupport.ValidateAndEvaluate(windowName, statementContext, validated[2]);
                if ((!constant.IsNumber()) || (TypeHelper.IsFloatingPointNumber(constant)))
                {
                    throw new ViewParameterException("Externally-timed batch view requires a Long-typed reference point in msec as a third parameter");
                }
                OptionalReferencePoint = constant.AsLong();
            }

            this._eventType = parentEventType;
        }
Пример #8
0
 public void SetViewParameters(ViewFactoryContext viewFactoryContext, IList <ExprNode> expressionParameters)
 {
     if (expressionParameters.Count != 1)
     {
         throw new ViewParameterException(ViewParamMessage);
     }
     _timeDeltaComputation = ViewFactoryTimePeriodHelper.ValidateAndEvaluateTimeDelta(ViewName, viewFactoryContext.StatementContext, expressionParameters[0], ViewParamMessage, 0);
 }
Пример #9
0
 public View MakeView(AgentInstanceViewFactoryChainContext agentInstanceViewFactoryContext)
 {
     ExprTimePeriodEvalDeltaConst timeDeltaComputation = _timeDeltaComputationFactory.Make(
         ViewName, "view", agentInstanceViewFactoryContext.AgentInstanceContext);
     ViewUpdatedCollection randomAccess =
         agentInstanceViewFactoryContext.StatementContext.ViewServicePreviousFactory
             .GetOptPreviousExprRandomAccess(agentInstanceViewFactoryContext);
     return new TimeWindowView(agentInstanceViewFactoryContext, this, timeDeltaComputation, randomAccess);
 }
 public bool EqualsTimePeriod(ExprTimePeriodEvalDeltaConst otherComputation)
 {
     if (otherComputation is ExprTimePeriodEvalDeltaConstGivenDelta)
     {
         var other = (ExprTimePeriodEvalDeltaConstGivenDelta)otherComputation;
         return(other._timeDelta == _timeDelta);
     }
     return(false);
 }
Пример #11
0
 public void SetDistinctExpressions(
     IList<ExprNode> distinctExpressions,
     ExprTimePeriodEvalDeltaConst timeDeltaComputation,
     ExprNode expiryTimeExp)
 {
     _distinctExpressions = distinctExpressions;
     _timeDeltaComputation = timeDeltaComputation;
     _expiryTimeExp = expiryTimeExp;
 }
 public bool EqualsTimePeriod(ExprTimePeriodEvalDeltaConst otherComputation)
 {
     if (otherComputation is ExprTimePeriodEvalDeltaConstMsec)
     {
         ExprTimePeriodEvalDeltaConstMsec other = (ExprTimePeriodEvalDeltaConstMsec)otherComputation;
         return(other._msec == _msec);
     }
     return(false);
 }
Пример #13
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="timeFirstViewFactory">For copying this view in a group-by</param>
        /// <param name="agentInstanceContext">The agent instance context.</param>
        /// <param name="timeDeltaComputation">The time delta computation.</param>
        public FirstTimeView(
            FirstTimeViewFactory timeFirstViewFactory,
            AgentInstanceViewFactoryChainContext agentInstanceContext,
            ExprTimePeriodEvalDeltaConst timeDeltaComputation)
        {
            AgentInstanceContext  = agentInstanceContext;
            _timeFirstViewFactory = timeFirstViewFactory;
            _timeDeltaComputation = timeDeltaComputation;

            _scheduleSlot = agentInstanceContext.StatementContext.ScheduleBucket.AllocateSlot();

            ScheduleCallback();

            agentInstanceContext.AddTerminationCallback(Stop);
        }
Пример #14
0
        public bool CanReuse(View view, AgentInstanceContext agentInstanceContext)
        {
            if (!(view is FirstTimeView))
            {
                return false;
            }

            var myView = (FirstTimeView) view;
            ExprTimePeriodEvalDeltaConst delta = _timeDeltaComputationFactory.Make(
                ViewName, "view", agentInstanceContext);
            if (!delta.EqualsTimePeriod(myView.TimeDeltaComputation))
            {
                return false;
            }
            return myView.IsEmpty();
        }
Пример #15
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="factory">for copying this view in a group-by</param>
 /// <param name="timestampExpression">is the field name containing a long timestamp valuethat should be in ascending order for the natural order of events and is intended to reflect
 /// System.currentTimeInMillis but does not necessarily have to.
 /// out of the window as oldData in the update method. The view compares
 /// each events timestamp against the newest event timestamp and those with a delta
 /// greater then secondsBeforeExpiry are pushed out of the window.</param>
 /// <param name="timestampExpressionEval">The timestamp expression eval.</param>
 /// <param name="timeDeltaComputation">The time delta computation.</param>
 /// <param name="optionalReferencePoint">The optional reference point.</param>
 /// <param name="viewUpdatedCollection">is a collection that the view must update when receiving events</param>
 /// <param name="agentInstanceViewFactoryContext">context for expression evalauation</param>
 public ExternallyTimedBatchView(ExternallyTimedBatchViewFactory factory,
                                 ExprNode timestampExpression,
                                 ExprEvaluator timestampExpressionEval,
                                 ExprTimePeriodEvalDeltaConst timeDeltaComputation,
                                 long?optionalReferencePoint,
                                 ViewUpdatedCollection viewUpdatedCollection,
                                 AgentInstanceViewFactoryChainContext agentInstanceViewFactoryContext)
 {
     _factory                        = factory;
     _timestampExpression            = timestampExpression;
     _timestampExpressionEval        = timestampExpressionEval;
     _timeDeltaComputation           = timeDeltaComputation;
     ViewUpdatedCollection           = viewUpdatedCollection;
     AgentInstanceViewFactoryContext = agentInstanceViewFactoryContext;
     ReferenceTimestamp              = optionalReferencePoint;
 }
Пример #16
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="externallyTimedWindowViewFactory">for copying this view in a group-by</param>
 /// <param name="timestampExpression">is the field name containing a long timestamp valuethat should be in ascending order for the natural order of
 /// events and is intended to reflect
 /// System.currentTimeInMillis but does not necessarily have to.
 /// out of the window as oldData in the update method. The view compares
 /// each events timestamp against the newest event timestamp and those with a delta
 /// greater then secondsBeforeExpiry are pushed out of the window.</param>
 /// <param name="timestampExpressionEval">The timestamp expression eval.</param>
 /// <param name="timeDeltaComputation">The time delta computation.</param>
 /// <param name="viewUpdatedCollection">is a collection that the view must update when receiving events</param>
 /// <param name="agentInstanceViewFactoryContext">context for expression evalauation</param>
 public ExternallyTimedWindowView(
     ExternallyTimedWindowViewFactory externallyTimedWindowViewFactory,
     ExprNode timestampExpression,
     ExprEvaluator timestampExpressionEval,
     ExprTimePeriodEvalDeltaConst timeDeltaComputation,
     ViewUpdatedCollection viewUpdatedCollection,
     AgentInstanceViewFactoryChainContext agentInstanceViewFactoryContext)
 {
     _externallyTimedWindowViewFactory = externallyTimedWindowViewFactory;
     _timestampExpression     = timestampExpression;
     _timestampExpressionEval = timestampExpressionEval;
     _timeDeltaComputation    = timeDeltaComputation;
     _viewUpdatedCollection   = viewUpdatedCollection;
     _timeWindow = new TimeWindow(agentInstanceViewFactoryContext.IsRemoveStream);
     AgentInstanceViewFactoryContext = agentInstanceViewFactoryContext;
 }
Пример #17
0
        public View MakeView(AgentInstanceViewFactoryChainContext agentInstanceViewFactoryContext)
        {
            ExprTimePeriodEvalDeltaConst timeDeltaComputation = _timeDeltaComputationFactory.Make(
                ViewName, "view", agentInstanceViewFactoryContext.AgentInstanceContext);
            ViewUpdatedCollection randomAccess =
                agentInstanceViewFactoryContext.StatementContext.ViewServicePreviousFactory
                .GetOptPreviousExprRandomAccess(agentInstanceViewFactoryContext);

            if (agentInstanceViewFactoryContext.IsRemoveStream)
            {
                return(new TimeAccumViewRStream(this, agentInstanceViewFactoryContext, timeDeltaComputation));
            }
            else
            {
                return(new TimeAccumView(this, agentInstanceViewFactoryContext, timeDeltaComputation, randomAccess));
            }
        }
Пример #18
0
        public bool CanReuse(View view, AgentInstanceContext agentInstanceContext)
        {
            if (!(view is TimeAccumView))
            {
                return(false);
            }

            var myView = (TimeAccumView)view;
            ExprTimePeriodEvalDeltaConst timeDeltaComputation = _timeDeltaComputationFactory.Make(
                ViewName, "view", agentInstanceContext);

            if (!timeDeltaComputation.EqualsTimePeriod(myView.TimeDeltaComputation))
            {
                return(false);
            }

            return(myView.IsEmpty);
        }
Пример #19
0
        /// <summary>
        /// Returns the number of milliseconds.
        /// </summary>
        /// <returns></returns>
        public long GetScheduleBackwardDelta(long fromTime, AgentInstanceContext agentInstanceContext)
        {
            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.Get().QRegIntervalValue(TimePeriodExpr);
            }
            if (_timeDeltaComputation == null)
            {
                _timeDeltaComputation = TimePeriodExpr.ConstEvaluator(new ExprEvaluatorContextStatement(agentInstanceContext.StatementContext, false));
            }
            long result = _timeDeltaComputation.DeltaMillisecondsSubtract(fromTime);

            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.Get().ARegIntervalValue(result);
            }
            return(result);
        }
Пример #20
0
        public bool CanReuse(View view, AgentInstanceContext agentInstanceContext)
        {
            if (!(view is TimeWindowView))
            {
                return false;
            }

            var myView = (TimeWindowView) view;
            ExprTimePeriodEvalDeltaConst delta = _timeDeltaComputationFactory.Make(
                ViewName, "view", agentInstanceContext);
            if (!delta.EqualsTimePeriod(myView.TimeDeltaComputation))
            {
                return false;
            }

            // For reuse of the time window it doesn't matter if it provides random access or not
            return myView.IsEmpty();
        }
Пример #21
0
        public void Attach(EventType parentEventType, StatementContext statementContext, ViewFactory optionalParentFactory, IList <ViewFactory> parentViewFactories)
        {
            ExprNode[] validated = ViewFactorySupport.Validate(ViewName, parentEventType, statementContext, _viewParameters, true);
            if (_viewParameters.Count != 2)
            {
                throw new ViewParameterException(ViewParamMessage);
            }

            if (!validated[0].ExprEvaluator.ReturnType.IsNumeric())
            {
                throw new ViewParameterException(ViewParamMessage);
            }
            TimestampExpression     = validated[0];
            TimestampExpressionEval = TimestampExpression.ExprEvaluator;
            ViewFactorySupport.AssertReturnsNonConstant(ViewName, validated[0], 0);

            TimeDeltaComputation = ViewFactoryTimePeriodHelper.ValidateAndEvaluateTimeDelta(ViewName, statementContext, _viewParameters[1], ViewParamMessage, 1);
            _eventType           = parentEventType;
        }
Пример #22
0
        public bool CanReuse(View view, AgentInstanceContext agentInstanceContext)
        {
            if (!(view is TimeBatchView))
            {
                return(false);
            }

            TimeBatchView myView = (TimeBatchView)view;
            ExprTimePeriodEvalDeltaConst timeDeltaComputation = timeDeltaComputationFactory.Make(
                ViewName, "view", agentInstanceContext);

            if (!timeDeltaComputation.EqualsTimePeriod(myView.TimeDeltaComputation))
            {
                return(false);
            }

            if ((myView.InitialReferencePoint != null) && (_optionalReferencePoint != null))
            {
                if (!myView.InitialReferencePoint.Equals(_optionalReferencePoint.Value))
                {
                    return(false);
                }
            }
            if (((myView.InitialReferencePoint == null) && (_optionalReferencePoint != null)) ||
                ((myView.InitialReferencePoint != null) && (_optionalReferencePoint == null)))
            {
                return(false);
            }

            if (myView.IsForceOutput != IsForceUpdate)
            {
                return(false);
            }

            if (myView.IsStartEager)
            {
                // since it's already started
                return(false);
            }

            return(myView.IsEmpty());
        }
 public bool EqualsTimePeriod(ExprTimePeriodEvalDeltaConst otherComputation)
 {
     if (otherComputation is ExprTimePeriodEvalDeltaConstGivenDtxAdd)
     {
         var other = (ExprTimePeriodEvalDeltaConstGivenDtxAdd)otherComputation;
         if (other._adders.Length != _adders.Length)
         {
             return(false);
         }
         for (int i = 0; i < _adders.Length; i++)
         {
             if (_added[i] != other._added[i] || _adders[i].GetType() != other._adders[i].GetType())
             {
                 return(false);
             }
         }
         return(true);
     }
     return(false);
 }
Пример #24
0
        public View MakeView(AgentInstanceViewFactoryChainContext agentInstanceViewFactoryContext)
        {
            ExprTimePeriodEvalDeltaConst timeDeltaComputation = timeDeltaComputationFactory.Make(
                ViewName, "view", agentInstanceViewFactoryContext.AgentInstanceContext);
            ViewUpdatedCollection viewUpdatedCollection =
                agentInstanceViewFactoryContext.StatementContext.ViewServicePreviousFactory
                .GetOptPreviousExprRelativeAccess(agentInstanceViewFactoryContext);

            if (agentInstanceViewFactoryContext.IsRemoveStream)
            {
                return(new TimeBatchViewRStream(
                           this, agentInstanceViewFactoryContext, timeDeltaComputation, _optionalReferencePoint, IsForceUpdate,
                           IsStartEager));
            }
            else
            {
                return(new TimeBatchView(
                           this, agentInstanceViewFactoryContext, timeDeltaComputation, _optionalReferencePoint, IsForceUpdate,
                           IsStartEager, viewUpdatedCollection));
            }
        }
Пример #25
0
 public View MakeView(AgentInstanceViewFactoryChainContext agentInstanceViewFactoryContext)
 {
     ExprTimePeriodEvalDeltaConst timeDeltaComputation = _timeDeltaComputationFactory.Make(
         ViewName, "view", agentInstanceViewFactoryContext.AgentInstanceContext);
     return new FirstTimeView(this, agentInstanceViewFactoryContext, timeDeltaComputation);
 }
Пример #26
0
        private static void RecursiveCompile(
            EvalFactoryNode evalNode,
            StatementContext context,
            ExprEvaluatorContext evaluatorContext,
            ICollection <string> eventTypeReferences,
            bool isInsertInto,
            MatchEventSpec tags,
            Deque <int> subexpressionIdStack,
            Stack <EvalFactoryNode> parentNodeStack,
            ICollection <string> allTagNamesOrdered)
        {
            var counter = 0;

            parentNodeStack.Push(evalNode);
            foreach (var child in evalNode.ChildNodes)
            {
                subexpressionIdStack.AddLast(counter++);
                RecursiveCompile(
                    child, context, evaluatorContext, eventTypeReferences, isInsertInto, tags, subexpressionIdStack,
                    parentNodeStack, allTagNamesOrdered);
                subexpressionIdStack.RemoveLast();
            }
            parentNodeStack.Pop();

            LinkedHashMap <string, Pair <EventType, string> > newTaggedEventTypes = null;
            LinkedHashMap <string, Pair <EventType, string> > newArrayEventTypes  = null;

            if (evalNode is EvalFilterFactoryNode)
            {
                var filterNode = (EvalFilterFactoryNode)evalNode;
                var eventName  = filterNode.RawFilterSpec.EventTypeName;
                if (context.TableService.GetTableMetadata(eventName) != null)
                {
                    throw new ExprValidationException("Tables cannot be used in pattern filter atoms");
                }

                var resolvedEventType = FilterStreamSpecRaw.ResolveType(
                    context.EngineURI, eventName, context.EventAdapterService, context.PlugInTypeResolutionURIs);
                var finalEventType       = resolvedEventType;
                var optionalTag          = filterNode.EventAsName;
                var isPropertyEvaluation = false;
                var isParentMatchUntil   = IsParentMatchUntil(evalNode, parentNodeStack);

                // obtain property event type, if final event type is properties
                if (filterNode.RawFilterSpec.OptionalPropertyEvalSpec != null)
                {
                    var optionalPropertyEvaluator =
                        PropertyEvaluatorFactory.MakeEvaluator(
                            context.Container,
                            filterNode.RawFilterSpec.OptionalPropertyEvalSpec,
                            resolvedEventType,
                            filterNode.EventAsName,
                            context.EventAdapterService,
                            context.EngineImportService,
                            context.SchedulingService,
                            context.VariableService,
                            context.ScriptingService,
                            context.TableService,
                            context.EngineURI,
                            context.StatementId,
                            context.StatementName,
                            context.Annotations,
                            subexpressionIdStack,
                            context.ConfigSnapshot,
                            context.NamedWindowMgmtService,
                            context.StatementExtensionServicesContext);
                    finalEventType       = optionalPropertyEvaluator.FragmentEventType;
                    isPropertyEvaluation = true;
                }

                if (finalEventType is EventTypeSPI)
                {
                    eventTypeReferences.Add(((EventTypeSPI)finalEventType).Metadata.PrimaryName);
                }

                // If a tag was supplied for the type, the tags must stay with this type, i.e. a=BeanA -> b=BeanA -> a=BeanB is a no
                if (optionalTag != null)
                {
                    var       pair         = tags.TaggedEventTypes.Get(optionalTag);
                    EventType existingType = null;
                    if (pair != null)
                    {
                        existingType = pair.First;
                    }
                    if (existingType == null)
                    {
                        pair = tags.ArrayEventTypes.Get(optionalTag);
                        if (pair != null)
                        {
                            throw new ExprValidationException(
                                      "Tag '" + optionalTag + "' for event '" + eventName +
                                      "' used in the repeat-until operator cannot also appear in other filter expressions");
                        }
                    }
                    if ((existingType != null) && (existingType != finalEventType))
                    {
                        throw new ExprValidationException(
                                  "Tag '" + optionalTag + "' for event '" + eventName +
                                  "' has already been declared for events of type " + existingType.UnderlyingType.FullName);
                    }
                    pair = new Pair <EventType, string>(finalEventType, eventName);

                    // add tagged type
                    if (isPropertyEvaluation || isParentMatchUntil)
                    {
                        newArrayEventTypes = new LinkedHashMap <string, Pair <EventType, string> >();
                        newArrayEventTypes.Put(optionalTag, pair);
                    }
                    else
                    {
                        newTaggedEventTypes = new LinkedHashMap <string, Pair <EventType, string> >();
                        newTaggedEventTypes.Put(optionalTag, pair);
                    }
                }

                // For this filter, filter types are all known tags at this time,
                // and additionally stream 0 (self) is our event type.
                // Stream type service allows resolution by property name event if that name appears in other tags.
                // by defaulting to stream zero.
                // Stream zero is always the current event type, all others follow the order of the map (stream 1 to N).
                var selfStreamName = optionalTag;
                if (selfStreamName == null)
                {
                    selfStreamName = "s_" + UuidGenerator.Generate();
                }
                var filterTypes = new LinkedHashMap <string, Pair <EventType, string> >();
                var typePair    = new Pair <EventType, string>(finalEventType, eventName);
                filterTypes.Put(selfStreamName, typePair);
                filterTypes.PutAll(tags.TaggedEventTypes);

                // for the filter, specify all tags used
                var filterTaggedEventTypes = new LinkedHashMap <string, Pair <EventType, string> >(tags.TaggedEventTypes);
                filterTaggedEventTypes.Remove(optionalTag);

                // handle array tags (match-until clause)
                LinkedHashMap <string, Pair <EventType, string> > arrayCompositeEventTypes = null;
                if (tags.ArrayEventTypes != null && !tags.ArrayEventTypes.IsEmpty())
                {
                    arrayCompositeEventTypes = new LinkedHashMap <string, Pair <EventType, string> >();
                    var patternSubexEventType = GetPatternSubexEventType(
                        context.StatementId, "pattern", subexpressionIdStack);

                    foreach (var entry in tags.ArrayEventTypes)
                    {
                        var specificArrayType = new LinkedHashMap <string, Pair <EventType, string> >();
                        specificArrayType.Put(entry.Key, entry.Value);
                        var arrayTagCompositeEventType =
                            context.EventAdapterService.CreateSemiAnonymousMapType(
                                patternSubexEventType, Collections.GetEmptyMap <string, Pair <EventType, string> >(),
                                specificArrayType, isInsertInto);
                        context.StatementSemiAnonymousTypeRegistry.Register(arrayTagCompositeEventType);

                        var tag = entry.Key;
                        if (!filterTypes.ContainsKey(tag))
                        {
                            var pair = new Pair <EventType, string>(arrayTagCompositeEventType, tag);
                            filterTypes.Put(tag, pair);
                            arrayCompositeEventTypes.Put(tag, pair);
                        }
                    }
                }

                StreamTypeService streamTypeService = new StreamTypeServiceImpl(
                    filterTypes, context.EngineURI, true, false);
                var exprNodes = filterNode.RawFilterSpec.FilterExpressions;

                var spec = FilterSpecCompiler.MakeFilterSpec(
                    resolvedEventType, eventName, exprNodes,
                    filterNode.RawFilterSpec.OptionalPropertyEvalSpec,
                    filterTaggedEventTypes,
                    arrayCompositeEventTypes,
                    streamTypeService,
                    null, context, subexpressionIdStack);
                filterNode.FilterSpec = spec;
            }
            else if (evalNode is EvalObserverFactoryNode)
            {
                var observerNode = (EvalObserverFactoryNode)evalNode;
                try
                {
                    var observerFactory = context.PatternResolutionService.Create(observerNode.PatternObserverSpec);

                    var streamTypeService = GetStreamTypeService(
                        context.EngineURI, context.StatementId, context.EventAdapterService, tags.TaggedEventTypes,
                        tags.ArrayEventTypes, subexpressionIdStack, "observer", context);
                    var validationContext = new ExprValidationContext(
                        context.Container,
                        streamTypeService,
                        context.EngineImportService,
                        context.StatementExtensionServicesContext, null,
                        context.SchedulingService,
                        context.VariableService,
                        context.TableService, evaluatorContext,
                        context.EventAdapterService,
                        context.StatementName,
                        context.StatementId,
                        context.Annotations,
                        context.ContextDescriptor,
                        context.ScriptingService,
                        false, false, false, false, null, false);
                    var validated = ValidateExpressions(
                        ExprNodeOrigin.PATTERNOBSERVER, observerNode.PatternObserverSpec.ObjectParameters,
                        validationContext);

                    MatchedEventConvertor convertor = new MatchedEventConvertorImpl(
                        tags.TaggedEventTypes, tags.ArrayEventTypes, allTagNamesOrdered, context.EventAdapterService);

                    observerNode.ObserverFactory = observerFactory;
                    observerFactory.SetObserverParameters(validated, convertor, validationContext);
                }
                catch (ObserverParameterException e)
                {
                    throw new ExprValidationException(
                              "Invalid parameter for pattern observer '" + observerNode.ToPrecedenceFreeEPL() + "': " +
                              e.Message, e);
                }
                catch (PatternObjectException e)
                {
                    throw new ExprValidationException(
                              "Failed to resolve pattern observer '" + observerNode.ToPrecedenceFreeEPL() + "': " + e.Message,
                              e);
                }
            }
            else if (evalNode is EvalGuardFactoryNode)
            {
                var guardNode = (EvalGuardFactoryNode)evalNode;
                try
                {
                    var guardFactory = context.PatternResolutionService.Create(guardNode.PatternGuardSpec);

                    var streamTypeService = GetStreamTypeService(
                        context.EngineURI, context.StatementId, context.EventAdapterService, tags.TaggedEventTypes,
                        tags.ArrayEventTypes, subexpressionIdStack, "guard", context);
                    var validationContext = new ExprValidationContext(
                        context.Container,
                        streamTypeService,
                        context.EngineImportService,
                        context.StatementExtensionServicesContext, null,
                        context.SchedulingService,
                        context.VariableService,
                        context.TableService, evaluatorContext,
                        context.EventAdapterService,
                        context.StatementName,
                        context.StatementId,
                        context.Annotations,
                        context.ContextDescriptor,
                        context.ScriptingService,
                        false, false, false, false, null, false);
                    var validated = ValidateExpressions(
                        ExprNodeOrigin.PATTERNGUARD, guardNode.PatternGuardSpec.ObjectParameters, validationContext);

                    MatchedEventConvertor convertor = new MatchedEventConvertorImpl(
                        tags.TaggedEventTypes, tags.ArrayEventTypes, allTagNamesOrdered, context.EventAdapterService);

                    guardNode.GuardFactory = guardFactory;
                    guardFactory.SetGuardParameters(validated, convertor);
                }
                catch (GuardParameterException e)
                {
                    throw new ExprValidationException(
                              "Invalid parameter for pattern guard '" + guardNode.ToPrecedenceFreeEPL() + "': " + e.Message, e);
                }
                catch (PatternObjectException e)
                {
                    throw new ExprValidationException(
                              "Failed to resolve pattern guard '" + guardNode.ToPrecedenceFreeEPL() + "': " + e.Message, e);
                }
            }
            else if (evalNode is EvalEveryDistinctFactoryNode)
            {
                var distinctNode             = (EvalEveryDistinctFactoryNode)evalNode;
                var matchEventFromChildNodes = AnalyzeMatchEvent(distinctNode);
                var streamTypeService        = GetStreamTypeService(
                    context.EngineURI, context.StatementId, context.EventAdapterService,
                    matchEventFromChildNodes.TaggedEventTypes, matchEventFromChildNodes.ArrayEventTypes,
                    subexpressionIdStack, "every-distinct", context);
                var validationContext = new ExprValidationContext(
                    context.Container,
                    streamTypeService,
                    context.EngineImportService,
                    context.StatementExtensionServicesContext, null,
                    context.SchedulingService,
                    context.VariableService,
                    context.TableService, evaluatorContext,
                    context.EventAdapterService,
                    context.StatementName,
                    context.StatementId,
                    context.Annotations,
                    context.ContextDescriptor,
                    context.ScriptingService,
                    false, false, false, false, null, false);
                IList <ExprNode> validated;
                try
                {
                    validated = ValidateExpressions(
                        ExprNodeOrigin.PATTERNEVERYDISTINCT, distinctNode.Expressions, validationContext);
                }
                catch (ExprValidationPropertyException ex)
                {
                    throw new ExprValidationPropertyException(
                              ex.Message +
                              ", every-distinct requires that all properties resolve from sub-expressions to the every-distinct",
                              ex.InnerException);
                }

                MatchedEventConvertor convertor =
                    new MatchedEventConvertorImpl(
                        matchEventFromChildNodes.TaggedEventTypes, matchEventFromChildNodes.ArrayEventTypes,
                        allTagNamesOrdered, context.EventAdapterService);

                distinctNode.Convertor = convertor;

                // Determine whether some expressions are constants or time period
                IList <ExprNode>             distinctExpressions  = new List <ExprNode>();
                ExprTimePeriodEvalDeltaConst timeDeltaComputation = null;
                ExprNode expiryTimeExp = null;
                var      count         = -1;
                var      last          = validated.Count - 1;
                foreach (var expr in validated)
                {
                    count++;
                    if (count == last && expr is ExprTimePeriod)
                    {
                        expiryTimeExp = expr;
                        var timePeriodExpr = (ExprTimePeriod)expiryTimeExp;
                        timeDeltaComputation =
                            timePeriodExpr.ConstEvaluator(new ExprEvaluatorContextStatement(context, false));
                    }
                    else if (expr.IsConstantResult)
                    {
                        if (count == last)
                        {
                            var evaluateParams = new EvaluateParams(null, true, evaluatorContext);
                            var value          = expr.ExprEvaluator.Evaluate(evaluateParams);
                            if (!(value.IsNumber()))
                            {
                                throw new ExprValidationException(
                                          "Invalid parameter for every-distinct, expected number of seconds constant (constant not considered for distinct)");
                            }

                            var secondsExpire = expr.ExprEvaluator.Evaluate(evaluateParams);

                            long?timeExpire;
                            if (secondsExpire == null)
                            {
                                timeExpire = null;
                            }
                            else
                            {
                                timeExpire = context.TimeAbacus.DeltaForSecondsNumber(secondsExpire);
                            }

                            if (timeExpire != null && timeExpire > 0)
                            {
                                timeDeltaComputation = new ExprTimePeriodEvalDeltaConstGivenDelta(timeExpire.Value);
                                expiryTimeExp        = expr;
                            }
                            else
                            {
                                Log.Warn("Invalid seconds-expire " + timeExpire + " for " + ExprNodeUtility.ToExpressionStringMinPrecedenceSafe(expr));
                            }
                        }
                        else
                        {
                            Log.Warn(
                                "Every-distinct node utilizes an expression returning a constant value, please check expression '{0}', not adding expression to distinct-value expression list",
                                expr.ToExpressionStringMinPrecedenceSafe());
                        }
                    }
                    else
                    {
                        distinctExpressions.Add(expr);
                    }
                }
                if (distinctExpressions.IsEmpty())
                {
                    throw new ExprValidationException(
                              "Every-distinct node requires one or more distinct-value expressions that each return non-constant result values");
                }
                distinctNode.SetDistinctExpressions(distinctExpressions, timeDeltaComputation, expiryTimeExp);
            }
            else if (evalNode is EvalMatchUntilFactoryNode)
            {
                var matchUntilNode = (EvalMatchUntilFactoryNode)evalNode;

                // compile bounds expressions, if any
                var untilMatchEventSpec = new MatchEventSpec(tags.TaggedEventTypes, tags.ArrayEventTypes);
                var streamTypeService   = GetStreamTypeService(
                    context.EngineURI, context.StatementId, context.EventAdapterService,
                    untilMatchEventSpec.TaggedEventTypes, untilMatchEventSpec.ArrayEventTypes, subexpressionIdStack,
                    "until", context);
                var validationContext = new ExprValidationContext(
                    context.Container,
                    streamTypeService,
                    context.EngineImportService,
                    context.StatementExtensionServicesContext, null,
                    context.SchedulingService,
                    context.VariableService,
                    context.TableService, evaluatorContext,
                    context.EventAdapterService,
                    context.StatementName,
                    context.StatementId,
                    context.Annotations,
                    context.ContextDescriptor,
                    context.ScriptingService,
                    false, false, false, false, null, false);

                var lower = ValidateBounds(matchUntilNode.LowerBounds, validationContext);
                matchUntilNode.LowerBounds = lower;

                var upper = ValidateBounds(matchUntilNode.UpperBounds, validationContext);
                matchUntilNode.UpperBounds = upper;

                var single = ValidateBounds(matchUntilNode.SingleBound, validationContext);
                matchUntilNode.SingleBound = single;

                var convertor = new MatchedEventConvertorImpl(
                    untilMatchEventSpec.TaggedEventTypes, untilMatchEventSpec.ArrayEventTypes, allTagNamesOrdered,
                    context.EventAdapterService);
                matchUntilNode.Convertor = convertor;

                // compile new tag lists
                ISet <string> arrayTags = null;
                var           matchUntilAnalysisResult = EvalNodeUtil.RecursiveAnalyzeChildNodes(matchUntilNode.ChildNodes[0]);
                foreach (var filterNode in matchUntilAnalysisResult.FilterNodes)
                {
                    var optionalTag = filterNode.EventAsName;
                    if (optionalTag != null)
                    {
                        if (arrayTags == null)
                        {
                            arrayTags = new HashSet <string>();
                        }
                        arrayTags.Add(optionalTag);
                    }
                }

                if (arrayTags != null)
                {
                    foreach (var arrayTag in arrayTags)
                    {
                        if (!tags.ArrayEventTypes.ContainsKey(arrayTag))
                        {
                            tags.ArrayEventTypes.Put(arrayTag, tags.TaggedEventTypes.Get(arrayTag));
                            tags.TaggedEventTypes.Remove(arrayTag);
                        }
                    }
                }
                matchUntilNode.TagsArrayed = GetIndexesForTags(allTagNamesOrdered, arrayTags);
            }
            else if (evalNode is EvalFollowedByFactoryNode)
            {
                var followedByNode = (EvalFollowedByFactoryNode)evalNode;
                StreamTypeService streamTypeService = new StreamTypeServiceImpl(context.EngineURI, false);
                var validationContext = new ExprValidationContext(
                    context.Container,
                    streamTypeService,
                    context.EngineImportService,
                    context.StatementExtensionServicesContext, null,
                    context.SchedulingService,
                    context.VariableService,
                    context.TableService,
                    evaluatorContext,
                    context.EventAdapterService,
                    context.StatementName,
                    context.StatementId,
                    context.Annotations,
                    context.ContextDescriptor,
                    context.ScriptingService,
                    false, false, false, false, null, false);

                if (followedByNode.OptionalMaxExpressions != null)
                {
                    IList <ExprNode> validated = new List <ExprNode>();
                    foreach (var maxExpr in followedByNode.OptionalMaxExpressions)
                    {
                        if (maxExpr == null)
                        {
                            validated.Add(null);
                        }
                        else
                        {
                            var visitor = new ExprNodeSummaryVisitor();
                            maxExpr.Accept(visitor);
                            if (!visitor.IsPlain)
                            {
                                var errorMessage = "Invalid maximum expression in followed-by, " + visitor.GetMessage() +
                                                   " are not allowed within the expression";
                                Log.Error(errorMessage);
                                throw new ExprValidationException(errorMessage);
                            }

                            var validatedExpr = ExprNodeUtility.GetValidatedSubtree(
                                ExprNodeOrigin.FOLLOWEDBYMAX, maxExpr, validationContext);
                            validated.Add(validatedExpr);
                            if ((validatedExpr.ExprEvaluator.ReturnType == null) ||
                                (!validatedExpr.ExprEvaluator.ReturnType.IsNumeric()))
                            {
                                var message = "Invalid maximum expression in followed-by, the expression must return an integer value";
                                throw new ExprValidationException(message);
                            }
                        }
                    }
                    followedByNode.OptionalMaxExpressions = validated;
                }
            }

            if (newTaggedEventTypes != null)
            {
                tags.TaggedEventTypes.PutAll(newTaggedEventTypes);
            }
            if (newArrayEventTypes != null)
            {
                tags.ArrayEventTypes.PutAll(newArrayEventTypes);
            }
        }
 public bool EqualsTimePeriod(ExprTimePeriodEvalDeltaConst otherComputation)
 {
     return otherComputation is ExprTimePeriodEvalDeltaConstZero;
 }
Пример #28
0
 private static ExprOptionalConstant GetExprOrConstant(ExprNode exprNode, TimeAbacus timeAbacus)
 {
     if (exprNode is ExprTimePeriod)
     {
         var timePeriod = (ExprTimePeriod)exprNode;
         if (!timePeriod.HasMonth && !timePeriod.HasYear)
         {
             // no-month and constant
             if (exprNode.IsConstantResult)
             {
                 var sec = timePeriod.EvaluateAsSeconds(null, true, null);
                 var l   = timeAbacus.DeltaForSecondsDouble(sec);
                 IntervalDeltaExprEvaluator eval = new ProxyIntervalDeltaExprEvaluator
                 {
                     ProcEvaluate = (reference, eventsPerStream, isNewData, context) => l,
                 };
                 return(new ExprOptionalConstant(eval, l));
             }
             // no-month and not constant
             else
             {
                 IntervalDeltaExprEvaluator eval = new ProxyIntervalDeltaExprEvaluator
                 {
                     ProcEvaluate = (reference, eventsPerStream, isNewData, context) =>
                     {
                         double sec = timePeriod.EvaluateAsSeconds(eventsPerStream, isNewData, context);
                         return(timeAbacus.DeltaForSecondsDouble(sec));
                     },
                 };
                 return(new ExprOptionalConstant(eval, null));
             }
         }
         // has-month
         else
         {
             // has-month and constant
             if (exprNode.IsConstantResult)
             {
                 ExprTimePeriodEvalDeltaConst timerPeriodConst = timePeriod.ConstEvaluator(null);
                 IntervalDeltaExprEvaluator   eval             = new ProxyIntervalDeltaExprEvaluator
                 {
                     ProcEvaluate = (reference, eventsPerStream, isNewData, context) =>
                     {
                         return(timerPeriodConst.DeltaAdd(reference));
                     },
                 };
                 return(new ExprOptionalConstant(eval, null));
             }
             // has-month and not constant
             else
             {
                 ExprTimePeriodEvalDeltaNonConst timerPeriodNonConst = timePeriod.NonconstEvaluator();
                 IntervalDeltaExprEvaluator      eval = new ProxyIntervalDeltaExprEvaluator
                 {
                     ProcEvaluate = (reference, eventsPerStream, isNewData, context) => timerPeriodNonConst.DeltaAdd(
                         reference, eventsPerStream, isNewData, context),
                 };
                 return(new ExprOptionalConstant(eval, null));
             }
         }
     }
     else if (ExprNodeUtility.IsConstantValueExpr(exprNode))
     {
         var  constantNode = (ExprConstantNode)exprNode;
         long l            = constantNode.GetConstantValue(null).AsLong();
         IntervalDeltaExprEvaluator eval = new ProxyIntervalDeltaExprEvaluator
         {
             ProcEvaluate = (reference, eventsPerStream, isNewData, context) => l,
         };
         return(new ExprOptionalConstant(eval, l));
     }
     else
     {
         var evaluator = exprNode.ExprEvaluator;
         IntervalDeltaExprEvaluator eval = new ProxyIntervalDeltaExprEvaluator
         {
             ProcEvaluate = (reference, eventsPerStream, isNewData, context) => evaluator.Evaluate(
                 new EvaluateParams(eventsPerStream, isNewData, context)).AsLong(),
         };
         return(new ExprOptionalConstant(eval, null));
     }
 }