public void TestBooleanBuilderOverride2()
        {
            HystrixCommandOptions properties = new HystrixCommandOptions(
                HystrixCommandKeyDefault.AsKey("TEST"),
                new HystrixCommandOptions()
            {
                CircuitBreakerForceClosed = false
            });

            // the builder override should take precedence over the default
            Assert.False(properties.CircuitBreakerForceClosed);
        }
        public void TestIntegerBuilderOverride()
        {
            HystrixCommandOptions properties = new HystrixCommandOptions(
                HystrixCommandKeyDefault.AsKey("TEST"),
                new HystrixCommandOptions()
            {
                MetricsRollingStatisticalWindowInMilliseconds = 5000
            });

            // the builder override should take precedence over the default
            Assert.Equal(5000, properties.MetricsRollingStatisticalWindowInMilliseconds);
        }
        public ExecutionReport PlaceOrder(ExecutionReport order)
        {
            var options = new HystrixCommandOptions(HystrixCommandGroupKeyDefault.AsKey("OMS"), HystrixCommandKeyDefault.AsKey("OMS.NewOrder"));

            var cmd = new HystrixCommand <ExecutionReport>(options,
                                                           run: () => PlaceOrderRun(order),
                                                           fallback: () => PlaceOrderFallback(order));
//            Thread.Sleep(1000);
            var result = cmd.Execute();

            return(result);
        }
        public void TestNoRequestContextOnSimpleConcurencyStrategyWithoutException()
        {
            Dispose();
            var opts = new HystrixCommandOptions()
            {
                RequestLogEnabled = false,
                GroupKey          = HystrixCommandGroupKeyDefault.AsKey("SimpleCommand")
            };

            new SimpleCommand(output, opts).Execute();

            Assert.True(true, "Nothing blew up");
        }
        public void TestNoRequestContextOnSimpleConcurencyStrategyWithoutException()
        {
            base.Dispose();
            //ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.requestLog.enabled", "false");
            var opts = new HystrixCommandOptions()
            {
                RequestLogEnabled = false,
                GroupKey          = HystrixCommandGroupKeyDefault.AsKey("SimpleCommand")
            };

            new SimpleCommand(output, opts).Execute();

            //Assert.True("We are able to run the simple command without a context initialization error.", true);
        }
Пример #6
0
            private static IHystrixCommandOptions GetOptions()
            {
                HystrixCommandOptions opts = new HystrixCommandOptions()
                {
                    GroupKey   = HystrixCommandGroupKeyDefault.AsKey("testTimeoutConcurrency"),
                    CommandKey = HystrixCommandKeyDefault.AsKey("testTimeoutConcurrencyCommand"),
                    ExecutionTimeoutInMilliseconds = 3,
                    CircuitBreakerEnabled          = false,
                    FallbackIsolationSemaphoreMaxConcurrentRequests = NUM_CONCURRENT_COMMANDS,
                    ThreadPoolOptions = GetThreadPoolOptions()
                };

                return(opts);
            }
Пример #7
0
 private Command(
     HystrixCommandOptions setter,
     HystrixEventType executionResult,
     int executionLatency,
     string arg,
     HystrixEventType fallbackExecutionResult,
     int fallbackExecutionLatency)
     : base(setter)
 {
     executionResult2              = executionResult;
     this.executionLatency         = executionLatency;
     this.fallbackExecutionResult  = fallbackExecutionResult;
     this.fallbackExecutionLatency = fallbackExecutionLatency;
     this.arg = arg;
     _isFallbackUserDefined = true;
 }
Пример #8
0
        private async Task SetColorNotifyObservers(ColorChangeResponse response, bool?notify = true, double?duration = 1)
        {
            var hystrixOptions = new HystrixCommandOptions(HystrixCommandKeyDefault.AsKey("SetColor"));

            hystrixOptions.GroupKey = HystrixCommandGroupKeyDefault.AsKey("SetColorGroup");
            hystrixOptions.ExecutionTimeoutEnabled = false;
            SetColorCommand command = new SetColorCommand(hystrixOptions, _lifxKey, response.HexColor, duration);
            await command.ExecuteAsync();

            if (notify == true)
            {
                await _hubContext.Clients.All.SendAsync("Messages", new List <ColorChangeResponse> {
                    response
                });
            }
        }
        private IHystrixCommandOptions GetCommandOptions(string serviceName, string methodName)
        {
            var strategy = HystrixPlugins.OptionsStrategy;
            var dynOpts  = strategy.GetDynamicOptions(_configuration);

            var commandKey = HystrixCommandKeyDefault.AsKey($"{serviceName}.{methodName}");
            var groupKey   = HystrixCommandGroupKeyDefault.AsKey($"{serviceName}Group");

            IHystrixCommandOptions opts = new HystrixCommandOptions(groupKey, commandKey, null, dynOpts)
            {
                ThreadPoolKey = HystrixThreadPoolKeyDefault.AsKey($"{serviceName}Group")
            };

            opts.ThreadPoolOptions = new HystrixThreadPoolOptions(opts.ThreadPoolKey, null, dynOpts);

            return(opts);
        }
Пример #10
0
        private IHystrixCommandOptions CreateCommandOptions(MethodBase method)
        {
            var groupKeyName   = _clientName;
            var commandKeyName = GetCommandKey(_pryxyType, method);

            var groupKey   = HystrixCommandGroupKeyDefault.AsKey(groupKeyName);
            var commandKey = HystrixCommandKeyDefault.AsKey(commandKeyName);

            var configuration = _services.GetService <IConfiguration>();
            var strategy      = HystrixPlugins.OptionsStrategy;
            var dynOpts       = strategy.GetDynamicOptions(configuration);
            var opts          = new HystrixCommandOptions(commandKey, null, dynOpts)
            {
                GroupKey = groupKey
            };

            return(opts);
        }
Пример #11
0
        public static IHystrixCommandOptions GetCommandOptions(string serviceName, string methodName)
        {
            var configuration = new ConfigurationBuilder().AddInMemoryCollection().Build();
            var strategy      = HystrixPlugins.OptionsStrategy;
            var dynOpts       = strategy.GetDynamicOptions(configuration);

            var commandKey = HystrixCommandKeyDefault.AsKey($"{serviceName}.{methodName}");
            var groupKey   = HystrixCommandGroupKeyDefault.AsKey($"{serviceName}Group");

            IHystrixCommandOptions opts = new HystrixCommandOptions(groupKey, commandKey, null, dynOpts)
            {
                ThreadPoolKey = HystrixThreadPoolKeyDefault.AsKey($"{serviceName}Group")
            };

            opts.ThreadPoolOptions = new HystrixThreadPoolOptions(opts.ThreadPoolKey, null, dynOpts);

            return(opts);
        }
Пример #12
0
        public void TestIntegerInstanceDynamicOverrideOfEverything()
        {
            var configSettings           = @"
            {
                'hystrix': {
                    'command': {
                        'default': {
                            'metrics': {
                                'rollingStats': {
                                    'timeInMilliseconds': 1234
                                }
                            }
                        },
                        'TEST': {
                            'metrics': {
                                'rollingStats': {
                                    'timeInMilliseconds': 3456
                                }
                            }
                        }
                    }
                }

            }";
            var memStream                = GetMemoryStream(configSettings);
            ConfigurationBuilder builder = new ConfigurationBuilder();

            builder.Add(new JsonStreamConfigurationSource(memStream));
            var config   = builder.Build();
            var dynamics = new HystrixDynamicOptionsDefault(config);

            HystrixCommandOptions properties = new HystrixCommandOptions(HystrixCommandKeyDefault.AsKey("TEST"), new HystrixCommandOptions()
            {
                MetricsRollingStatisticalWindowInMilliseconds = 5000
            }, dynamics);

            // the instance specific dynamic property should take precedence over everything
            Assert.Equal(3456, properties.MetricsRollingStatisticalWindowInMilliseconds);
        }
Пример #13
0
            public static Command From(
                IHystrixCommandGroupKey groupKey,
                IHystrixCommandKey key,
                HystrixEventType desiredEventType,
                int latency,
                ExecutionIsolationStrategy isolationStrategy,
                HystrixEventType desiredFallbackEventType,
                int fallbackLatency)
            {
                var topts = new HystrixThreadPoolOptions()
                {
                    CoreSize      = 10,
                    MaxQueueSize  = -1,
                    ThreadPoolKey = HystrixThreadPoolKeyDefault.AsKey(groupKey.Name)
                };

                var setter = new HystrixCommandOptions()
                {
                    GroupKey   = groupKey,
                    CommandKey = key,

                    ExecutionTimeoutInMilliseconds                = 600,
                    ExecutionIsolationStrategy                    = isolationStrategy,
                    CircuitBreakerEnabled                         = true,
                    CircuitBreakerRequestVolumeThreshold          = 3,
                    MetricsHealthSnapshotIntervalInMilliseconds   = 100,
                    MetricsRollingStatisticalWindowInMilliseconds = 1000,
                    MetricsRollingStatisticalWindowBuckets        = 10,
                    RequestCacheEnabled = true,
                    RequestLogEnabled   = true,
                    FallbackIsolationSemaphoreMaxConcurrentRequests = 5,
                    ThreadPoolKey     = HystrixThreadPoolKeyDefault.AsKey(groupKey.Name),
                    ThreadPoolOptions = topts
                };

                string uniqueArg;

                switch (desiredEventType)
                {
                case HystrixEventType.SUCCESS:
                    uniqueArg = UniqueId.IncrementAndGet() + string.Empty;
                    return(new Command(setter, HystrixEventType.SUCCESS, latency, uniqueArg, desiredFallbackEventType, 0));

                case HystrixEventType.FAILURE:
                    uniqueArg = UniqueId.IncrementAndGet() + string.Empty;
                    return(new Command(setter, HystrixEventType.FAILURE, latency, uniqueArg, desiredFallbackEventType, fallbackLatency));

                case HystrixEventType.TIMEOUT:
                    uniqueArg = UniqueId.IncrementAndGet() + string.Empty;
                    return(new Command(setter, HystrixEventType.SUCCESS, 1000, uniqueArg, desiredFallbackEventType, fallbackLatency));    // use 1000 so that it always times out (at 600ms)

                case HystrixEventType.BAD_REQUEST:
                    uniqueArg = UniqueId.IncrementAndGet() + string.Empty;
                    return(new Command(setter, HystrixEventType.BAD_REQUEST, latency, uniqueArg, desiredFallbackEventType, 0));

                case HystrixEventType.RESPONSE_FROM_CACHE:
                    var arg = UniqueId.Value + string.Empty;
                    return(new Command(setter, HystrixEventType.SUCCESS, 0, arg, desiredFallbackEventType, 0));

                default:
                    throw new Exception("not supported yet");
                }
            }
Пример #14
0
        public void TestBooleanCodeDefault()
        {
            HystrixCommandOptions properties = new HystrixCommandOptions(HystrixCommandKeyDefault.AsKey("TEST"), new HystrixCommandOptions());

            Assert.Equal(HystrixCommandOptions.Default_CircuitBreakerForceClosed, properties.CircuitBreakerForceClosed);
        }
Пример #15
0
 internal static HystrixCommandMetrics GetMetrics(IHystrixCommandKey commandKey, HystrixCommandOptions properties)
 {
     return(HystrixCommandMetrics.GetInstance(commandKey, CommandOwnerForUnitTest.OWNER_ONE, ThreadPoolKeyForUnitTest.THREAD_POOL_ONE, properties));
 }
Пример #16
0
        public void TestIntegerCodeDefault()
        {
            HystrixCommandOptions properties = new HystrixCommandOptions(HystrixCommandKeyDefault.AsKey("TEST"), new HystrixCommandOptions());

            Assert.Equal(HystrixCommandOptions.Default_MetricsRollingStatisticalWindow, properties.MetricsRollingStatisticalWindowInMilliseconds);
        }
Пример #17
0
        public async Task <IActionResult> Get()
        {
            try
            {
                var auth = new SingleUserAuthorizer
                {
                    CredentialStore = new InMemoryCredentialStore
                    {
                        ConsumerKey      = _twitterCreds.ConsumerKey,
                        ConsumerSecret   = _twitterCreds.ConsumerSecret,
                        OAuthToken       = _twitterCreds.AccessToken,
                        OAuthTokenSecret = _twitterCreds.AccessTokenSecret
                    }
                };
                await auth.AuthorizeAsync();

                var ctx = new TwitterContext(auth);
                if (auth == null)
                {
                }
                string searchTerm = _twitterSearchTerm;

                Search searchResponse =
                    await
                        (from search in ctx.Search
                        where search.Type == SearchType.Search &&
                        search.ResultType == ResultType.Recent &&
                        search.Query == searchTerm &&
                        search.IncludeEntities == true &&
                        search.TweetMode == TweetMode.Extended &&
                        search.Count == 10 &&
                        search.SinceID == sinceId
                        select search)
                    .SingleOrDefaultAsync();

                if (!searchResponse.Statuses.Any())
                {
                    return(Json(new TweetListWithSentiment
                    {
                        Tweets = new List <EnhancedTwitterStatus>()
                    }));
                }
                var subset = searchResponse.Statuses.OrderBy(o => o.StatusID) /*.Take(2)*/;
                sinceId = subset.Max(i => i.StatusID);
                var texts    = subset.Select(t => t.FullText);
                var analyzed = await _utils.GetColorAndSentimentFromText(texts);

                var aggScore = analyzed.Average(r => r.Sentiment);

                var toReturn = new TweetListWithSentiment {
                    Tweets         = new List <EnhancedTwitterStatus>(),
                    AggregateScore = aggScore,
                    AggregateColor = _utils.HexColorFromDouble(aggScore)
                };
                var hystrixOptions = new HystrixCommandOptions(HystrixCommandKeyDefault.AsKey("SetColor"))
                {
                    GroupKey = HystrixCommandGroupKeyDefault.AsKey("SetColorGroup"),
                    ExecutionTimeoutEnabled = false
                };
                SetColorCommand command = new SetColorCommand(hystrixOptions, _lifxKey, toReturn.AggregateColor);
                await command.ExecuteAsync();

                foreach (var status in subset.Select((value, i) => new { i, value }))
                {
                    var s        = status.value;
                    var analysis = analyzed.Find(a => a.TextInput == s.FullText);
                    toReturn.Tweets.Add(new EnhancedTwitterStatus
                    {
                        FullText       = s.FullText,
                        CreatedAt      = s.CreatedAt,
                        User           = s.User,
                        SentimentValue = analysis.Sentiment,
                        HexColor       = analysis.HexColor
                    });
                }

                return(Json(toReturn));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }