public AccessSafely AfterCompleting <TState, TSource>(int times)
        {
            _access = AccessSafely.AfterCompleting(times);

            _access
            .WritingWith <int>("confirmDispatchedResultedIn", increment => _confirmDispatchedResultedIn.AddAndGet(increment))
            .ReadingWith("confirmDispatchedResultedIn", () => _confirmDispatchedResultedIn.Get())

            .WritingWith <StoreData <TSource> >("writeStoreData", data =>
            {
                _writeObjectResultedIn.AddAndGet(data.ResultedIn);
                _objectWriteResult.Set(data.Result);
                _objectWriteAccumulatedResults.Enqueue(data.Result);
                _objectState.Set(data.State);
                data.Sources.ForEach(source => _sources.Enqueue(source));
                _metadataHolder.Set(data.Metadata);
                if (data.ErrorCauses != null)
                {
                    _errorCauses.Enqueue(data.ErrorCauses);
                }
            })
            .WritingWith <StoreData <TSource> >("readStoreData", data =>
            {
                _readObjectResultedIn.AddAndGet(data.ResultedIn);
                _objectReadResult.Set(data.Result);
                _objectWriteAccumulatedResults.Enqueue(data.Result);
                _objectState.Set(data.State);
                data.Sources.ForEach(source => _sources.Enqueue(source));
                _metadataHolder.Set(data.Metadata);
                if (data.ErrorCauses != null)
                {
                    _errorCauses.Enqueue(data.ErrorCauses);
                }
            })
            .ReadingWith("readObjectResultedIn", () => _readObjectResultedIn.Get())
            .ReadingWith("objectReadResult", () => _objectReadResult.Get())
            .ReadingWith("objectWriteResult", () => _objectWriteResult.Get())
            .ReadingWith("objectWriteAccumulatedResults", () =>
            {
                _objectWriteAccumulatedResults.TryDequeue(out var result);
                return(result);
            })
            .ReadingWith("objectWriteAccumulatedResultsCount", () => _objectWriteAccumulatedResults.Count)
            .ReadingWith("metadataHolder", () => _metadataHolder.Get())
            .ReadingWith("objectState", () => (TState)_objectState.Get())
            .ReadingWith("sources", () =>
            {
                _sources.TryDequeue(out var result);
                return(result);
            })
            .ReadingWith("errorCauses", () =>
            {
                _errorCauses.TryDequeue(out var result);
                return(result);
            })
            .ReadingWith("errorCausesCount", () => _errorCauses.Count)
            .ReadingWith("writeObjectResultedIn", () => _writeObjectResultedIn.Get());

            return(_access);
        }
 internal virtual void SetErrorState(Exception t)
 {
     CheckErrorState();
     Log.Error("Worker " + name + " failed.", t);
     state.Set(TestAppendSnapshotTruncate.Worker.State.Error);
     thrown = t;
 }
 /// <inheritdoc />
 public void ReadResultedIn <TState>(IOutcome <StorageException, Result> outcome, string?id, TState state, int stateVersion, Metadata?metadata, object? @object)
 {
     outcome.AndThen(result =>
     {
         _readBundles.Add(new TypedStateBundle(id, state, stateVersion, metadata));
         return(result);
     })
     .Otherwise(cause =>
     {
         _readOutcome.Set(outcome);
         _success.Set(false);
         return(cause.Result);
     });
 }
 public void Run()
 {
     while (running)
     {
         try
         {
             Thread.Sleep(reloadInterval);
         }
         catch (Exception)
         {
         }
         //NOP
         if (running && NeedsReload())
         {
             try
             {
                 trustManagerRef.Set(LoadTrustManager());
             }
             catch (Exception ex)
             {
                 Log.Warn("Could not load truststore (keep using existing one) : " + ex.ToString()
                          , ex);
             }
         }
     }
 }
Пример #5
0
        public AccessSafely AfterCompleting(int times)
        {
            Access = AccessSafely.AfterCompleting(times);

            Access
            .WritingWith <int>("confirmDispatched", i => _confirmDispatchedResultedIn.IncrementAndGet())
            .WritingWith <int>("readTextResultedIn", i => _readTextResultedIn.IncrementAndGet())
            .WritingWith <int>("writeTextResultedIn", i => _writeTextResultedIn.IncrementAndGet())
            .WritingWith <Result>("textReadResult", i => _textReadResult.Set(i))
            .WritingWith <Result>("textWriteResult", i => _textWriteResult.Set(i))
            .WritingWith <object>("stateHolder", i => _stateHolder.Set(i))
            .WritingWith <Result>("textWriteAccumulatedResults", i => _textWriteAccumulatedResults.Enqueue(i))
            .WritingWith <Metadata>("metadataHolder", i => _metadataHolder.Set(i))
            .WritingWith <StorageException>("errorCauses", i => _errorCauses.Enqueue(i))
            .ReadingWith("confirmDispatched", () => _confirmDispatchedResultedIn.Get())
            .ReadingWith("readTextResultedIn", () => _readTextResultedIn.IncrementAndGet())
            .ReadingWith("writeTextResultedIn", () => _writeTextResultedIn.IncrementAndGet())
            .ReadingWith("textReadResult", () => _textReadResult.Get())
            .ReadingWith("textWriteResult", () => _textWriteResult.Get())
            .ReadingWith("stateHolder", () => _stateHolder.Get())
            .ReadingWith("textWriteAccumulatedResults", () =>
            {
                _textWriteAccumulatedResults.TryDequeue(out var writeResult);
                return(writeResult);
            })
            .ReadingWith("metadataHolder", () => _metadataHolder.Get())
            .ReadingWith("errorCauses", () =>
            {
                _errorCauses.TryDequeue(out var exception);
                return(exception);
            });

            return(Access);
        }
Пример #6
0
 /// <summary>Initialize a reference to an on-disk object directory.</summary>
 /// <remarks>Initialize a reference to an on-disk object directory.</remarks>
 /// <param name="cfg">configuration this directory consults for write settings.</param>
 /// <param name="dir">the location of the <code>objects</code> directory.</param>
 /// <param name="alternatePaths">a list of alternate object directories</param>
 /// <param name="fs">
 /// the file system abstraction which will be necessary to perform
 /// certain file system operations.
 /// </param>
 /// <exception cref="System.IO.IOException">an alternate object cannot be opened.</exception>
 public ObjectDirectory(Config cfg, FilePath dir, FilePath[] alternatePaths, FS fs
                        )
 {
     config              = cfg;
     objects             = dir;
     infoDirectory       = new FilePath(objects, "info");
     packDirectory       = new FilePath(objects, "pack");
     alternatesFile      = new FilePath(infoDirectory, "alternates");
     cachedPacksFile     = new FilePath(infoDirectory, "cached-packs");
     packList            = new AtomicReference <ObjectDirectory.PackList>(NO_PACKS);
     cachedPacks         = new AtomicReference <ObjectDirectory.CachedPackList>();
     unpackedObjectCache = new UnpackedObjectCache();
     this.fs             = fs;
     alternates          = new AtomicReference <FileObjectDatabase.AlternateHandle[]>();
     if (alternatePaths != null)
     {
         FileObjectDatabase.AlternateHandle[] alt;
         alt = new FileObjectDatabase.AlternateHandle[alternatePaths.Length];
         for (int i = 0; i < alternatePaths.Length; i++)
         {
             alt[i] = OpenAlternate(alternatePaths[i]);
         }
         alternates.Set(alt);
     }
 }
Пример #7
0
        public virtual void TestCloseTwice()
        {
            DistributedFileSystem fs  = cluster.GetFileSystem();
            FSDataOutputStream    os  = fs.Create(new Path("/test"));
            DFSOutputStream       dos = (DFSOutputStream)Whitebox.GetInternalState(os, "wrappedStream"
                                                                                   );
            AtomicReference <IOException> ex = (AtomicReference <IOException>)Whitebox.GetInternalState
                                                   (dos, "lastException");

            NUnit.Framework.Assert.AreEqual(null, ex.Get());
            dos.Close();
            IOException dummy = new IOException("dummy");

            ex.Set(dummy);
            try
            {
                dos.Close();
            }
            catch (IOException e)
            {
                NUnit.Framework.Assert.AreEqual(e, dummy);
            }
            NUnit.Framework.Assert.AreEqual(null, ex.Get());
            dos.Close();
        }
Пример #8
0
        public void Refresh()
        {
            try
            {
                Counters <Item> itemPreferenceCounts = new Counters <Item>();
                lock (this)
                {
                    int numUsers = 0;
                    foreach (User user in dataModel.GetUsers())
                    {
                        Preference[] prefs = user.GetPreferencesAsArray();
                        foreach (Preference preference in prefs)
                        {
                            itemPreferenceCounts.Increment(preference.Item);
                        }
                        numUsers++;
                    }
                    Dictionary <Item, double> newIufFactors =
                        new Dictionary <Item, double>(1 + (4 * itemPreferenceCounts.Count) / 3);
                    double logFactor = Math.Log(logBase);
                    foreach (KeyValuePair <Item, MutableInteger> entry in itemPreferenceCounts.Map)
                    {
                        int count = entry.Value.Value;
                        newIufFactors.Add(entry.Key,
                                          Math.Log((double)numUsers / (double)count) / logFactor);
                    }

                    iufFactors.Set(newIufFactors /* readonly */);
                }
            }
            catch (TasteException dme)
            {
                log.Warn("Unable to refresh", dme);
            }
        }
Пример #9
0
 public override void Read(AtomicReference <ReaderWriterState <T> > state, Action <T> dataCallback)
 {
     dataStorage.Read(data =>
     {
         dataCallback?.Invoke(data);
         state.Set(new DataWasReceivedState <T>(dataStorage));
     });
 }
Пример #10
0
 /// <summary>
 /// Clears all recorded values.
 /// </summary>
 public void Clear()
 {
     sample.Clear();
     count.Set(0);
     max.Set(Int64.MinValue);
     min.Set(Int64.MaxValue);
     sum.Set(0);
     variance.Set(new double[] { -1, 0 });
 }
Пример #11
0
        public virtual void TestDatanodeDetect()
        {
            AtomicReference <DatanodeProtocolProtos.BlockReportRequestProto> request = new AtomicReference
                                                                                       <DatanodeProtocolProtos.BlockReportRequestProto>();
            // just capture the outgoing PB
            DatanodeProtocolPB mockProxy = Org.Mockito.Mockito.Mock <DatanodeProtocolPB>();

            Org.Mockito.Mockito.DoAnswer(new _Answer_205(request)).When(mockProxy).BlockReport
                (Matchers.Any <RpcController>(), Matchers.Any <DatanodeProtocolProtos.BlockReportRequestProto
                                                               >());
            DatanodeProtocolClientSideTranslatorPB nn = new DatanodeProtocolClientSideTranslatorPB
                                                            (mockProxy);
            DatanodeRegistration reg    = DFSTestUtil.GetLocalDatanodeRegistration();
            NamespaceInfo        nsInfo = new NamespaceInfo(1, "cluster", "bp", 1);

            reg.SetNamespaceInfo(nsInfo);
            Replica          r       = new FinalizedReplica(new Block(1, 2, 3), null, null);
            BlockListAsLongs bbl     = BlockListAsLongs.Encode(Sharpen.Collections.Singleton(r));
            DatanodeStorage  storage = new DatanodeStorage("s1");

            StorageBlockReport[] sbr = new StorageBlockReport[] { new StorageBlockReport(storage
                                                                                         , bbl) };
            // check DN sends new-style BR
            request.Set(null);
            nsInfo.SetCapabilities(NamespaceInfo.Capability.StorageBlockReportBuffers.GetMask
                                       ());
            nn.BlockReport(reg, "pool", sbr, new BlockReportContext(1, 0, Runtime.NanoTime())
                           );
            DatanodeProtocolProtos.BlockReportRequestProto proto = request.Get();
            NUnit.Framework.Assert.IsNotNull(proto);
            NUnit.Framework.Assert.IsTrue(proto.GetReports(0).GetBlocksList().IsEmpty());
            NUnit.Framework.Assert.IsFalse(proto.GetReports(0).GetBlocksBuffersList().IsEmpty
                                               ());
            // back up to prior version and check DN sends old-style BR
            request.Set(null);
            nsInfo.SetCapabilities(NamespaceInfo.Capability.Unknown.GetMask());
            nn.BlockReport(reg, "pool", sbr, new BlockReportContext(1, 0, Runtime.NanoTime())
                           );
            proto = request.Get();
            NUnit.Framework.Assert.IsNotNull(proto);
            NUnit.Framework.Assert.IsFalse(proto.GetReports(0).GetBlocksList().IsEmpty());
            NUnit.Framework.Assert.IsTrue(proto.GetReports(0).GetBlocksBuffersList().IsEmpty(
                                              ));
        }
 /// <summary>Creates a reloadable trustmanager.</summary>
 /// <remarks>
 /// Creates a reloadable trustmanager. The trustmanager reloads itself
 /// if the underlying trustore file has changed.
 /// </remarks>
 /// <param name="type">type of truststore file, typically 'jks'.</param>
 /// <param name="location">local path to the truststore file.</param>
 /// <param name="password">password of the truststore file.</param>
 /// <param name="reloadInterval">
 /// interval to check if the truststore file has
 /// changed, in milliseconds.
 /// </param>
 /// <exception cref="System.IO.IOException">
 /// thrown if the truststore could not be initialized due
 /// to an IO error.
 /// </exception>
 /// <exception cref="GeneralSecurityException">
 /// thrown if the truststore could not be
 /// initialized due to a security error.
 /// </exception>
 public ReloadingX509TrustManager(string type, string location, string password, long
                                  reloadInterval)
 {
     this.type       = type;
     file            = new FilePath(location);
     this.password   = password;
     trustManagerRef = new AtomicReference <X509TrustManager>();
     trustManagerRef.Set(LoadTrustManager());
     this.reloadInterval = reloadInterval;
 }
Пример #13
0
 public UDTSender(UDTSession session, UDPEndPoint endpoint)
 {
     if (!session.isReady())
     {
         Log.Write(this.ToString(), "UDTSession is not ready.");
     }
     this.endpoint         = endpoint;
     this.session          = session;
     statistics            = session.getStatistics();
     senderLossList        = new SenderLossList();
     sendBuffer            = new Dictionary <long, DataPacket>(session.getFlowWindowSize());
     sendQueue             = new Queue <DataPacket>(1000);
     lastAckSequenceNumber = (int)session.getInitialSequenceNumber();
     currentSequenceNumber = (int)session.getInitialSequenceNumber() - 1;
     waitForAckLatch.Set(new CountDownLatch(1));
     waitForSeqAckLatch.Set(new CountDownLatch(1));
     storeStatistics = false;       //Boolean.getBoolean("udt.sender.storeStatistics");
     initMetrics();
     doStart();
 }
Пример #14
0
 public override void Close()
 {
     unpackedObjectCache.Clear();
     ObjectDirectory.PackList packs = packList.Get();
     packList.Set(NO_PACKS);
     foreach (PackFile p in packs.packs)
     {
         p.Close();
     }
     // Fully close all loaded alternates and clear the alternate list.
     FileObjectDatabase.AlternateHandle[] alt = alternates.Get();
     if (alt != null)
     {
         alternates.Set(null);
         foreach (FileObjectDatabase.AlternateHandle od in alt)
         {
             od.Close();
         }
     }
 }
Пример #15
0
 public MockCompletes(int times)
     : base((Scheduler)null)
 {
     _safely = AccessSafely.AfterCompleting(times)
               .WritingWith <T>("outcome", val =>
     {
         _outcome.Set(val);
         _withCount.IncrementAndGet();
     })
               .ReadingWith("outcome", _outcome.Get)
               .ReadingWith("count", _withCount.Get);
 }
Пример #16
0
        public ClientClusterService(HazelcastClient client)
        {
            _membersRef.Set(new Dictionary <Address, IMember>());
            _client = client;

            var networkConfig    = GetClientConfig().GetNetworkConfig();
            var connAttemptLimit = networkConfig.GetConnectionAttemptLimit();

            _connectionAttemptPeriod = networkConfig.GetConnectionAttemptPeriod();
            _connectionAttemptLimit  = connAttemptLimit == 0 ? int.MaxValue : connAttemptLimit;
            _shuffleMemberList       = EnvironmentUtil.ReadBool("hazelcast.client.shuffle.member.list") ?? false;

            var listenerConfigs = client.GetClientConfig().GetListenerConfigs();

            foreach (var listenerConfig in listenerConfigs)
            {
                var listener = listenerConfig.GetImplementation();
                if (listener == null)
                {
                    try
                    {
                        var className = listenerConfig.GetClassName();
                        var type      = Type.GetType(className);
                        if (type != null)
                        {
                            listener = Activator.CreateInstance(type) as IEventListener;
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.Severe(e);
                    }
                }
                var membershipListener = listener as IMembershipListener;
                if (membershipListener != null)
                {
                    AddMembershipListenerWithoutInit(membershipListener);
                }
            }
        }
        public IUnlaunchDataStore GetDataStore()
        {
            if (_refreshableUnlaunchFetcherRef.Get() != null)
            {
                return(_refreshableUnlaunchFetcherRef.Get());
            }

            var dataStore = new UnlaunchHttpDataStore(_restWrapper, _s3BucketClient, _initialDownloadDoneEvent, _downloadSuccessful, _dataStoreRefreshDelay);

            _refreshableUnlaunchFetcherRef.Set(dataStore);

            return(dataStore);
        }
        public virtual int AddToIndex(E o)
        {
            int index = item2Index[o];

            if (index != null)
            {
                return(index);
            }
            Lock.Lock();
            try
            {
                // Recheck state
                if (item2Index.Contains(o))
                {
                    return(item2Index[o]);
                }
                else
                {
                    int      newIndex = indexSize++;
                    object[] arr      = index2Item.Get();
                    System.Diagnostics.Debug.Assert(newIndex <= arr.Length);
                    if (newIndex == arr.Length)
                    {
                        // Increase size of array if necessary
                        object[] newArr = new object[2 * newIndex];
                        System.Array.Copy(arr, 0, newArr, 0, arr.Length);
                        arr = newArr;
                    }
                    arr[newIndex] = o;
                    index2Item.Set(arr);
                    item2Index[o] = newIndex;
                    return(newIndex);
                }
            }
            finally
            {
                Lock.Unlock();
            }
        }
Пример #19
0
        /// <summary>Update the scheduleCache to match current conditions in callCounts.</summary>
        private void RecomputeScheduleCache()
        {
            IDictionary <object, int> nextCache = new Dictionary <object, int>();

            foreach (KeyValuePair <object, AtomicLong> entry in callCounts)
            {
                object     id            = entry.Key;
                AtomicLong value         = entry.Value;
                long       snapshot      = value.Get();
                int        computedLevel = ComputePriorityLevel(snapshot);
                nextCache[id] = computedLevel;
            }
            // Swap in to activate
            scheduleCacheRef.Set(Collections.UnmodifiableMap(nextCache));
        }
Пример #20
0
 private void AppendConsidering <TSource, TSnapshotState>(IOutcome <StorageException, Result> outcome)
 {
     outcome
     .AndThen(result =>
     {
         if (result == Result.Success)
         {
             Appended();
         }
         return(result);
     })
     .Otherwise(ex =>
     {
         _exception.Set(ex);
         return(outcome.GetOrNull());
     });
 }
Пример #21
0
        private void InitFeatureStore(Data data)
        {
            _projectNameRef.Set(data.projectName);
            _environmentNameRef.Set(data.envName);

            var featureFlags = FlagMapper.GetFeatureFlags(data.flags);
            var flagMap      = featureFlags.ToDictionary(x => x.Key);

            _flagMapReference.Set(flagMap);

            if (!_downloadSuccessful.Get())
            {
                _downloadSuccessful.Set(true);
            }

            if (!_initialDownloadDoneEvent.IsSet)
            {
                _initialDownloadDoneEvent.Signal();
            }
        }
Пример #22
0
 /// <summary>
 /// Replaces active queue with the newly requested one and transfers
 /// all calls to the newQ before returning.
 /// </summary>
 public virtual void SwapQueue(Type queueClassToUse, int maxSize, string ns, Configuration
                               conf)
 {
     lock (this)
     {
         BlockingQueue <E> newQ = CreateCallQueueInstance(queueClassToUse, maxSize, ns, conf
                                                          );
         // Our current queue becomes the old queue
         BlockingQueue <E> oldQ = putRef.Get();
         // Swap putRef first: allow blocked puts() to be unblocked
         putRef.Set(newQ);
         // Wait for handlers to drain the oldQ
         while (!QueueIsReallyEmpty(oldQ))
         {
         }
         // Swap takeRef to handle new calls
         takeRef.Set(newQ);
         Log.Info("Old Queue: " + StringRepr(oldQ) + ", " + "Replacement: " + StringRepr(newQ
                                                                                         ));
     }
 }
        private static void FindValueExpr(
            ExprNode child,
            ExprNode parent,
            AtomicReference<IList<ExprNodeWithParentPair>> pairsRef)
        {
            var valueVisitor = new FilterSpecExprNodeVisitorValueLimitedExpr();
            child.Accept(valueVisitor);

            // not by itself a value expression, but itself it may decompose into some value expressions
            if (!valueVisitor.IsLimited) {
                FindValueExpressionsDeepRecursive(child, pairsRef);
                return;
            }

            // add value expression, don't traverse child
            IList<ExprNodeWithParentPair> pairs = pairsRef.Get();
            if (pairs == null) {
                pairs = new List<ExprNodeWithParentPair>(2);
                pairsRef.Set(pairs);
            }

            pairs.Add(new ExprNodeWithParentPair(child, parent));
        }
Пример #24
0
 /// <summary>
 /// Set up writer and reader of state.
 /// </summary>
 private void SetUpWriteRead()
 {
     Access
     .WritingWith <object>("reference", value => reference.Set(value))
     .ReadingWith("reference", () => reference.Get());
 }
Пример #25
0
		/// <summary>Initialize a reference to an on-disk object directory.</summary>
		/// <remarks>Initialize a reference to an on-disk object directory.</remarks>
		/// <param name="cfg">configuration this directory consults for write settings.</param>
		/// <param name="dir">the location of the <code>objects</code> directory.</param>
		/// <param name="alternatePaths">a list of alternate object directories</param>
		/// <param name="fs">
		/// the file system abstraction which will be necessary to perform
		/// certain file system operations.
		/// </param>
		/// <exception cref="System.IO.IOException">an alternate object cannot be opened.</exception>
		public ObjectDirectory(Config cfg, FilePath dir, FilePath[] alternatePaths, FS fs
			)
		{
			config = cfg;
			objects = dir;
			infoDirectory = new FilePath(objects, "info");
			packDirectory = new FilePath(objects, "pack");
			alternatesFile = new FilePath(infoDirectory, "alternates");
			cachedPacksFile = new FilePath(infoDirectory, "cached-packs");
			packList = new AtomicReference<ObjectDirectory.PackList>(NO_PACKS);
			cachedPacks = new AtomicReference<ObjectDirectory.CachedPackList>();
			unpackedObjectCache = new UnpackedObjectCache();
			this.fs = fs;
			alternates = new AtomicReference<FileObjectDatabase.AlternateHandle[]>();
			if (alternatePaths != null)
			{
				FileObjectDatabase.AlternateHandle[] alt;
				alt = new FileObjectDatabase.AlternateHandle[alternatePaths.Length];
				for (int i = 0; i < alternatePaths.Length; i++)
				{
					alt[i] = OpenAlternate(alternatePaths[i]);
				}
				alternates.Set(alt);
			}
		}
Пример #26
0
 static FnExpr()
 {
     _baseClassMapRef.Set(_baseClassMapRef.Get().assoc(typeof(RestFn), typeof(RestFnImpl)));
     //_baseClassMapRef.Set(_baseClassMapRef.Get().assoc(typeof(AFn),typeof(AFnImpl)));
 }
Пример #27
0
 internal virtual void SetMembersRef(IDictionary <Address, IMember> map)
 {
     _membersRef.Set(map);
 }
Пример #28
0
        public static ExprTimePeriod TimePeriodGetExprAllParams(
            EsperEPL2GrammarParser.TimePeriodContext ctx,
            IDictionary<ITree, ExprNode> astExprNodeMap,
            VariableCompileTimeResolver variableCompileTimeResolver,
            StatementSpecRaw spec,
            Configuration config,
            TimeAbacus timeAbacus)
        {
            ExprNode[] nodes = new ExprNode[9];
            for (int i = 0; i < ctx.ChildCount; i++)
            {
                IParseTree unitRoot = ctx.GetChild(i);

                ExprNode valueExpr;
                if (ASTUtil.IsTerminatedOfType(unitRoot.GetChild(0), EsperEPL2GrammarLexer.IDENT))
                {
                    string ident = unitRoot.GetChild(0).GetText();
                    valueExpr = ASTExprHelper.ResolvePropertyOrVariableIdentifier(ident, variableCompileTimeResolver, spec);
                }
                else
                {
                    AtomicReference<ExprNode> @ref = new AtomicReference<ExprNode>();
                    ExprAction action = (exprNode, astExprNodeMapX, node) => {
                        astExprNodeMapX.Remove(node);
                        @ref.Set(exprNode);
                    };
                    ASTExprHelper.RecursiveFindRemoveChildExprNode(unitRoot.GetChild(0), astExprNodeMap, action);
                    valueExpr = @ref.Get();
                }

                if (ASTUtil.GetRuleIndexIfProvided(unitRoot) == EsperEPL2GrammarParser.RULE_microsecondPart)
                {
                    nodes[8] = valueExpr;
                }

                if (ASTUtil.GetRuleIndexIfProvided(unitRoot) == EsperEPL2GrammarParser.RULE_millisecondPart)
                {
                    nodes[7] = valueExpr;
                }

                if (ASTUtil.GetRuleIndexIfProvided(unitRoot) == EsperEPL2GrammarParser.RULE_secondPart)
                {
                    nodes[6] = valueExpr;
                }

                if (ASTUtil.GetRuleIndexIfProvided(unitRoot) == EsperEPL2GrammarParser.RULE_minutePart)
                {
                    nodes[5] = valueExpr;
                }

                if (ASTUtil.GetRuleIndexIfProvided(unitRoot) == EsperEPL2GrammarParser.RULE_hourPart)
                {
                    nodes[4] = valueExpr;
                }

                if (ASTUtil.GetRuleIndexIfProvided(unitRoot) == EsperEPL2GrammarParser.RULE_dayPart)
                {
                    nodes[3] = valueExpr;
                }

                if (ASTUtil.GetRuleIndexIfProvided(unitRoot) == EsperEPL2GrammarParser.RULE_weekPart)
                {
                    nodes[2] = valueExpr;
                }

                if (ASTUtil.GetRuleIndexIfProvided(unitRoot) == EsperEPL2GrammarParser.RULE_monthPart)
                {
                    nodes[1] = valueExpr;
                }

                if (ASTUtil.GetRuleIndexIfProvided(unitRoot) == EsperEPL2GrammarParser.RULE_yearPart)
                {
                    nodes[0] = valueExpr;
                }
            }

            ExprTimePeriod timeNode = new ExprTimePeriodImpl(
                nodes[0] != null, nodes[1] != null,
                nodes[2] != null, nodes[3] != null,
                nodes[4] != null, nodes[5] != null,
                nodes[6] != null, nodes[7] != null,
                nodes[8] != null, timeAbacus);

            foreach (ExprNode node in nodes)
            {
                if (node != null)
                {
                    timeNode.AddChildNode(node);
                }
            }

            return timeNode;
        }
Пример #29
0
        private Variation EvaluateInternal(FeatureFlag flag, UnlaunchUser user, AtomicReference <string> evaluationReasonRef)
        {
            if (flag == null)
            {
                throw new ArgumentException("unlaunchFlag must not be null");
            }

            if (user == null)
            {
                throw new ArgumentException("user must not be null");
            }

            Variation variationToServe;
            var       evaluationReason = string.Empty;

            if (!flag.Enabled)
            {
                Logger.Debug($"FLAG_DISABLED, {flag.Key}, OFF_VARIATION is served to user {user.GetId()}");
                variationToServe = flag.OffVariation;
                evaluationReason = "Default Variation served. Because the flag is disabled.";
            }
            else if (!CheckDependencies(flag, user))
            {
                Logger.Info($"PREREQUISITE_FAILED for flag {flag.Key}, OFF_VARIATION is served to user {user.GetId()}");
                variationToServe = flag.OffVariation;
                evaluationReason = "Default Variation served. Because Pre-requisite failed.";
            }
            else if ((variationToServe = GetVariationIfUserInAllowList(flag, user)) != null)
            {
                Logger.Info($"USER_IN_TARGET_USER for flag {flag.Key}, VARIATION {variationToServe} is served to user {user.GetId()}");
                evaluationReason = $"Target User rules matched for userId: {user.GetId()}";
            }
            else
            {
                var bucketNumber = GetBucket(user.GetId(), flag.Key);
                foreach (var rule in flag.Rules)
                {
                    if (!rule.IsDefault() && rule.Matches(user))
                    {
                        variationToServe = GetVariationToServeByRule(rule, bucketNumber);
                        Logger.Debug($"RULE_MATCHED for flag {flag.Key}, {variationToServe.Key} Target Rule is served to user {user.GetId()}");
                        evaluationReason = $"Targeting Rule (priority #{rule.GetPriority()}) matched.";
                        break;
                    }
                }

                // No variation matched by rule. Use the default rule.
                if (variationToServe == null)
                {
                    var defaultRule = flag.DefaultRule;
                    variationToServe = GetVariationToServeByRule(defaultRule, bucketNumber);
                    Logger.Debug($"RULE_NOT_MATCHED for flag {flag.Key}, {variationToServe.Key} Default Rule is served to user {user.GetId()}");

                    evaluationReason = "Default Rule served. This is because the flag is Enabled and Target User and Targeting Rules didn't match.";
                }
            }

            evaluationReasonRef?.Set(evaluationReason);

            return(variationToServe);
        }
Пример #30
0
 public void Dispose()
 {
     _timer?.Dispose();
     _flagMapReference.Set(new Dictionary <string, FeatureFlag>());
     _isTaskRunning.Set(true);
 }