public JsonMetricsPublisherCommand(CommandMetrics metrics, ICircuitBreaker circuitBreaker = null)
 {
     this.commandName    = metrics.CommandName;
     this.metrics        = metrics;
     this.circuitBreaker = circuitBreaker ?? CircuitBreaker.CircuitBreakerFactory.GetInstance(commandName);
     this.properties     = metrics.Properties;
 }
Пример #2
0
 /// <inheritdoc />
 public bool TryGet(string key, out ICircuitBreaker circuitBreaker)
 {
     lock (_circuitBreakers)
     {
         return(_circuitBreakers.TryGetValue(key, out circuitBreaker));
     }
 }
Пример #3
0
        public void LogFailure(ICircuitBreaker circuitBreaker, int maximumNumberOfFailures, TimeSpan period)
        {
            _dbContext.Set <CircuitBreakerLog>().Add(new CircuitBreakerLog
            {
                CircuitBreakerId = ((CircuitBreaker)circuitBreaker).Id,
                Status           = ((CircuitBreaker)circuitBreaker).Status,
                Succeeded        = false,
                CreatedDateTime  = _dateTimeProvider.OffsetNow,
            });

            UpdateCircuitBreakerStatus(circuitBreaker, circuitBreaker.Status == CircuitStatus.HalfOpen, CircuitStatus.Open);

            _dbContext.SaveChanges();

            if (circuitBreaker.Status == CircuitStatus.Closed)
            {
                var sinceLastTime    = _dateTimeProvider.OffsetNow - period;
                var numberOfFailures = _dbContext.Set <CircuitBreakerLog>().Where(x => x.CircuitBreakerId == ((CircuitBreaker)circuitBreaker).Id &&
                                                                                  x.Succeeded == false && x.CreatedDateTime >= sinceLastTime).Count();

                UpdateCircuitBreakerStatus(circuitBreaker, numberOfFailures >= maximumNumberOfFailures, CircuitStatus.Open);

                _dbContext.SaveChanges();
            }
        }
Пример #4
0
        public ClusterNode(ClusterContext context, IConnectionPoolFactory connectionPoolFactory, ILogger <ClusterNode> logger,
                           ObjectPool <OperationBuilder> operationBuilderPool, ICircuitBreaker circuitBreaker, ISaslMechanismFactory saslMechanismFactory,
                           IRedactor redactor, IPEndPoint endPoint, BucketType bucketType, NodeAdapter nodeAdapter, IRequestTracer tracer)
        {
            _context              = context ?? throw new ArgumentNullException(nameof(context));
            _logger               = logger ?? throw new ArgumentNullException(nameof(logger));
            _circuitBreaker       = circuitBreaker ?? throw new ArgumentException(nameof(circuitBreaker));
            _operationBuilderPool =
                operationBuilderPool ?? throw new ArgumentNullException(nameof(operationBuilderPool));
            _saslMechanismFactory = saslMechanismFactory ?? throw new ArgumentException(nameof(saslMechanismFactory));
            _redactor             = redactor ?? throw new ArgumentNullException(nameof(redactor));
            _tracer    = tracer;
            BucketType = bucketType;
            EndPoint   = endPoint ?? throw new ArgumentNullException(nameof(endPoint));

            _cachedToString = $"{EndPoint}-{_id}";

            KeyEndPoints = new ReadOnlyObservableCollection <IPEndPoint>(_keyEndPoints);
            UpdateKeyEndPoints();
            ((INotifyCollectionChanged)_keyEndPoints).CollectionChanged += (_, e) => OnKeyEndPointsChanged(e);

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

            ConnectionPool = connectionPoolFactory.Create(this);

            if (nodeAdapter != null)
            {
                NodesAdapter = nodeAdapter;
            }
        }
Пример #5
0
 public IDetailsParticipantBuilder <TRequest, TResponse> WithCircuitBreaker(ICircuitBreaker circuitBreaker)
 {
     Assert.ArgumentNotNull(circuitBreaker, nameof(circuitBreaker));
     ValidateDoesNotAlreadyHaveCircuitBreaker();
     _circuitBreaker = circuitBreaker;
     return(this);
 }
        public void testCircuitDoesNotTripOnFailuresBelowThreshold()
        {
            var             properties = CommandPropertiesTest.GetUnitTestPropertiesSetter();
            var             clock      = new MockedClock();
            CommandMetrics  metrics    = getMetrics(properties, clock);
            ICircuitBreaker cb         = getCircuitBreaker("KEY_ONE", "OWNER_TWO", metrics, properties, clock);

            // this should start as allowing requests
            Assert.True(cb.AllowRequest);
            Assert.False(cb.IsOpen());

            // success with high latency
            metrics.MarkSuccess(400);
            metrics.MarkSuccess(400);
            metrics.MarkFailure(10);
            metrics.MarkSuccess(400);
            metrics.MarkSuccess(40);
            metrics.MarkSuccess(400);
            metrics.MarkFailure(10);
            metrics.MarkFailure(10);

            // this should remain open as the failure threshold is below the percentage limit
            Assert.True(cb.AllowRequest);
            Assert.False(cb.IsOpen());
        }
Пример #7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="redisEndpoint"></param>
        /// <param name="redisPassword"></param>
        /// <param name="redisSsl"></param>
        /// <param name="onException"></param>
        /// <param name="onThrottled"></param>
        /// <param name="connectionTimeoutInMilliseconds"></param>
        /// <param name="syncTimeoutInMilliseconds"></param>
        /// <param name="countThrottledRequests"></param>
        /// <param name="circuitBreaker"></param>
        /// <param name="clock"></param>
        /// <param name="connectToRedisFunc"></param>
        public LeakyBucketRateLimiter(
            string redisEndpoint,
            string redisPassword                    = null,
            bool redisSsl                           = false,
            Action <Exception> onException          = null,
            Action <RateLimitingResult> onThrottled = null,
            int connectionTimeoutInMilliseconds     = 2000,
            int syncTimeoutInMilliseconds           = 1000,
            bool countThrottledRequests             = false,
            ICircuitBreaker circuitBreaker          = null,
            IClock clock = null,
            Func <Task <IConnectionMultiplexer> > connectToRedisFunc = null) :
            base(redisEndpoint,
                 redisPassword,
                 redisSsl,
                 onException,
                 onThrottled,
                 connectionTimeoutInMilliseconds,
                 syncTimeoutInMilliseconds,
                 countThrottledRequests,
                 circuitBreaker,
                 clock,
                 connectToRedisFunc)
        {
            var prepared = LuaScript.Prepare(_luaScript);

            _loadedLuaScript = prepared.Load(
                _redisConnection.GetServer(
                    _redisConnection.GetDatabase().IdentifyEndpoint()));
        }
Пример #8
0
 public ClientDefaultInterceptor(ILoadBalancing loadBalancing, IClientFactory clientFactory, ICircuitBreaker circuitBreaker, UraganoSettings uraganoSettings)
 {
     LoadBalancing   = loadBalancing;
     ClientFactory   = clientFactory;
     CircuitBreaker  = circuitBreaker;
     UraganoSettings = uraganoSettings;
 }
 public JsonMetricsPublisherCommand(string commandName, CommandMetrics metrics, ICircuitBreaker circuitBreaker, CommandProperties properties)
 {
     this.commandName = commandName;
     this.metrics = metrics;
     this.circuitBreaker = circuitBreaker;
     this.properties = properties;
 }
 public CircuitBreakerProductRepositoryDecorator(
     ICircuitBreaker breaker,
     IProductRepository decoratee)
 {
     this.breaker   = breaker;
     this.decoratee = decoratee;
 }
Пример #11
0
        public async Task TestLowVolumeDoesNotTripCircuit()
        {
            string key = "cmd-I";

            int sleepWindow = 400;
            int lowVolume   = 5;

            HystrixCommand <bool> cmd1 = new FailureCommand(key, 0, sleepWindow, lowVolume);
            ICircuitBreaker       cb   = cmd1._circuitBreaker;
            var stream = HealthCountsStream.GetInstance(HystrixCommandKeyDefault.AsKey(key), cmd1.CommandOptions);

            Assert.True(WaitForHealthCountToUpdate(key, 1000, output), "Health count stream failed to start");

            // this should start as allowing requests
            Assert.True(cb.AllowRequest, "Request NOT allowed when expected!");
            Assert.False(cb.IsOpen, "Circuit breaker is open when it should be closed!");

            await cmd1.ExecuteAsync();

            HystrixCommand <bool> cmd2 = new FailureCommand(key, 0, sleepWindow, lowVolume);
            await cmd2.ExecuteAsync();

            HystrixCommand <bool> cmd3 = new FailureCommand(key, 0, sleepWindow, lowVolume);
            await cmd3.ExecuteAsync();

            HystrixCommand <bool> cmd4 = new FailureCommand(key, 0, sleepWindow, lowVolume);
            await cmd4.ExecuteAsync();

            // Allow window to pass, even though it has all failed we won't trip the circuit because the volume is low
            // Time.Wait(200);
            Assert.True(WaitForHealthCountToUpdate(key, 250, output), "Health count stream failed to update");

            Assert.True(cb.AllowRequest, "Request NOT allowed when expected!");
            Assert.False(cb.IsOpen, "Circuit breaker is open when it should be closed!");
        }
Пример #12
0
        public async Task TestTripCircuitOnTimeouts()
        {
            string key = "cmd-D";

            HystrixCommand <bool> cmd1 = new TimeoutCommand(key);
            ICircuitBreaker       cb   = cmd1._circuitBreaker;
            var stream = HealthCountsStream.GetInstance(HystrixCommandKeyDefault.AsKey(key), cmd1.CommandOptions);

            Assert.True(WaitForHealthCountToUpdate(key, 1000, output), "Health count stream failed to start");

            // this should start as allowing requests
            Assert.True(cb.AllowRequest, "Request NOT allowed when expected!");
            Assert.False(cb.IsOpen, "Circuit breaker is open when it should be closed!");

            // success with high latency
            await cmd1.ExecuteAsync();

            HystrixCommand <bool> cmd2 = new TimeoutCommand(key);
            await cmd2.ExecuteAsync();

            HystrixCommand <bool> cmd3 = new TimeoutCommand(key);
            await cmd3.ExecuteAsync();

            HystrixCommand <bool> cmd4 = new TimeoutCommand(key);
            await cmd4.ExecuteAsync();

            // Allow window to pass, everything has been a timeout so we should not allow any requests
            // Time.Wait(125);
            Assert.True(WaitForHealthCountToUpdate(key, 250, output), "Health count stream failed to update");

            Assert.False(cb.AllowRequest, "Request allowed when NOT expected!");
            Assert.True(cb.IsOpen, "Circuit is closed when it should be open!");
        }
        public void testSingleTestOnOpenCircuitAfterTimeWindow()
        {
            int             sleepWindow = 200;
            var             properties  = CommandPropertiesTest.GetUnitTestPropertiesSetter().WithCircuitBreakerSleepWindowInMilliseconds(sleepWindow);
            var             clock       = new MockedClock();
            CommandMetrics  metrics     = getMetrics(properties, clock);
            ICircuitBreaker cb          = getCircuitBreaker("KEY_ONE", "OWNER_TWO", metrics, properties, clock);

            // fail
            metrics.MarkFailure(1000);
            metrics.MarkFailure(1000);
            metrics.MarkFailure(1000);
            metrics.MarkFailure(1000);

            // everything has failed in the test window so we should return false now
            Assert.False(cb.AllowRequest);
            Assert.True(cb.IsOpen());

            // wait for sleepWindow to pass
            clock.Increment(sleepWindow + 50);

            // we should now allow 1 request
            Assert.True(cb.AllowRequest);
            // but the circuit should still be open
            Assert.True(cb.IsOpen());
            // and further requests are still blocked
            Assert.False(cb.AllowRequest);
        }
        public void testTripCircuit()
        {
            var             properties = CommandPropertiesTest.GetUnitTestPropertiesSetter();
            var             clock      = new MockedClock();
            CommandMetrics  metrics    = getMetrics(properties, clock);
            ICircuitBreaker cb         = getCircuitBreaker("KEY_ONE", "OWNER_TWO", metrics, properties, clock);

            metrics.MarkSuccess(1000);
            metrics.MarkSuccess(1000);
            metrics.MarkSuccess(1000);
            metrics.MarkSuccess(1000);

            // this should still allow requests as everything has been successful
            Assert.True(cb.AllowRequest);
            Assert.False(cb.IsOpen());


            // fail
            metrics.MarkFailure(1000);
            metrics.MarkFailure(1000);
            metrics.MarkFailure(1000);
            metrics.MarkFailure(1000);

            // everything has failed in the test window so we should return false now
            Assert.False(cb.AllowRequest);
            Assert.True(cb.IsOpen());
        }
        public void testTripCircuitOnTimeoutsAboveThreshold()
        {
            var             properties = CommandPropertiesTest.GetUnitTestPropertiesSetter();
            var             clock      = new MockedClock();
            CommandMetrics  metrics    = getMetrics(properties, clock);
            ICircuitBreaker cb         = getCircuitBreaker("KEY_ONE", "OWNER_TWO", metrics, properties, clock);

            // this should start as allowing requests
            Assert.True(cb.AllowRequest);
            Assert.False(cb.IsOpen());

            // success with high latency
            metrics.MarkSuccess(400);
            metrics.MarkSuccess(400);
            metrics.MarkTimeout(10);
            metrics.MarkSuccess(400);
            metrics.MarkTimeout(10);
            metrics.MarkTimeout(10);
            metrics.MarkSuccess(400);
            metrics.MarkTimeout(10);
            metrics.MarkTimeout(10);

            // this should trip the circuit as the error percentage is above the threshold
            Assert.False(cb.AllowRequest);
            Assert.True(cb.IsOpen());
        }
Пример #16
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="redisEndpoint"></param>
        /// <param name="redisPassword"></param>
        /// <param name="redisSsl"></param>
        /// <param name="onException"></param>
        /// <param name="onThrottled"></param>
        /// <param name="connectionTimeoutInMilliseconds"></param>
        /// <param name="syncTimeoutInMilliseconds"></param>
        /// <param name="countThrottledRequests"></param>
        /// <param name="circuitBreaker"></param>
        /// <param name="clock"></param>
        /// <param name="connectToRedisFunc"></param>
        protected RedisRateLimiter(string redisEndpoint,
                                   string redisPassword,
                                   bool redisSsl,
                                   Action <Exception> onException          = null,
                                   Action <RateLimitingResult> onThrottled = null,
                                   int connectionTimeoutInMilliseconds     = 2000,
                                   int syncTimeoutInMilliseconds           = 1000,
                                   bool countThrottledRequests             = false,
                                   ICircuitBreaker circuitBreaker          = null,
                                   IClock clock = null,
                                   Func <Task <IConnectionMultiplexer> > connectToRedisFunc = null)
        {
            if (redisEndpoint == null)
            {
                throw new ArgumentNullException(nameof(redisEndpoint));
            }

            _onThrottled            = onThrottled;
            _countThrottledRequests = countThrottledRequests;
            _connectToRedisFunc     = connectToRedisFunc;
            _clock = clock;
            _circuitBreakerPolicy = circuitBreaker ??
                                    new DefaultCircuitBreaker(3, 10000, 300);

            if (connectToRedisFunc == null)
            {
                SetupConnectionConfiguration(redisEndpoint, redisPassword, redisSsl, connectionTimeoutInMilliseconds, syncTimeoutInMilliseconds);
            }

            //SetupCircuitBreaker(faultThreshholdPerWindowDuration, faultWindowDurationInMilliseconds, circuitOpenDurationInSecs, onException, onCircuitOpened, onCircuitClosed);
            ConnectToRedis(onException);
        }
 public CircuitBreakerListener(IListener <TRequest, TResponse> inner, ICircuitBreaker circuitBreaker)
 {
     Assert.ArgumentNotNull(inner, nameof(inner));
     Assert.ArgumentNotNull(circuitBreaker, nameof(circuitBreaker));
     _inner          = inner;
     _circuitBreaker = circuitBreaker;
 }
 public JsonMetricsPublisherCommand(CommandMetrics metrics, ICircuitBreaker circuitBreaker=null)
 {
     this.commandName = metrics.CommandName;
     this.metrics = metrics;
     this.circuitBreaker = circuitBreaker ?? CircuitBreaker.CircuitBreakerFactory.GetInstance(commandName);
     this.properties = metrics.Properties;
 }
 public static void Execute(this ICircuitBreaker breaker, Action action)
 {
     breaker.Execute <object>(() =>
     {
         action();
         return(null);
     });
 }
Пример #20
0
        public ICircuitBreaker Get(object state)
        {
            ICircuitBreaker result = null;

            store.TryGetValue(state, out result);

            return(result);
        }
Пример #21
0
 public ExternalSpendService(
     ISupplierService supplierService,
     ICircuitBreaker circuitBreaker
     )
 {
     this.supplierService = supplierService;
     this.circuitBreaker  = circuitBreaker;
 }
Пример #22
0
 public CategoryController(ICircuitBreaker circuitBreaker,
                           CategoryCommandHandler categoryCommandHandler,
                           CategoryQueryHandler categoryQueryHandler)
 {
     _circuitBreaker         = circuitBreaker;
     _categoryCommandHandler = categoryCommandHandler;
     _categoryQueryHandler   = categoryQueryHandler;
 }
Пример #23
0
        public OpenBehavior(ICircuitBreaker breaker, Exception exception, IEnumerator<TimeSpan> timeoutEnumerator)
        {
            _breaker = breaker;
            _exception = exception;
            _timeoutEnumerator = timeoutEnumerator;

            _timer = GetTimer(timeoutEnumerator);
            _elapsed = Stopwatch.StartNew();
        }
Пример #24
0
        public OpenBehavior(ICircuitBreaker breaker, Exception exception, IEnumerator <TimeSpan> timeoutEnumerator)
        {
            _breaker           = breaker;
            _exception         = exception;
            _timeoutEnumerator = timeoutEnumerator;

            _timer   = GetTimer(timeoutEnumerator);
            _elapsed = Stopwatch.StartNew();
        }
Пример #25
0
 public ClusterNodeFactory(ClusterContext clusterContext, IConnectionFactory connectionFactory, ILogger <ClusterNode> logger, ITypeTranscoder transcoder, ICircuitBreaker circuitBreaker, ISaslMechanismFactory saslMechanismFactory)
 {
     _clusterContext       = clusterContext ?? throw new ArgumentNullException(nameof(clusterContext));
     _connectionFactory    = connectionFactory ?? throw new ArgumentNullException(nameof(connectionFactory));
     _logger               = logger ?? throw new ArgumentNullException(nameof(logger));
     _transcoder           = transcoder ?? throw new ArgumentNullException(nameof(transcoder));
     _circuitBreaker       = circuitBreaker ?? throw new ArgumentException(nameof(circuitBreaker));
     _saslMechanismFactory = saslMechanismFactory;
 }
        public CircuitBreakerInteceptionBehavior(
            ICircuitBreaker breaker)
        {
            if (breaker == null)
            {
                throw new ArgumentNullException("breaker");
            }

            this.breaker = breaker;
        }
Пример #27
0
        public TestCommandBuilder SetCircuitBreaker(TestCircuitBreaker circuitBreaker)
        {
            this.CircuitBreaker = circuitBreaker;
            if (circuitBreaker != null)
            {
                this.Metrics = circuitBreaker.Metrics;
            }

            return(this);
        }
Пример #28
0
        private void UpdateCircuitBreakerStatus(ICircuitBreaker circuitBreaker, bool shouldUpdate, CircuitStatus circuitStatus)
        {
            if (!shouldUpdate)
            {
                return;
            }

            circuitBreaker.Status            = circuitStatus;
            circuitBreaker.LastStatusUpdated = _dateTimeProvider.OffsetNow;
        }
        public CircuitBreakerInterceptor(
            ICircuitBreaker breaker)
        {
            if (breaker == null)
            {
                throw new ArgumentNullException("breaker");
            }

            this.breaker = breaker;
        }
Пример #30
0
 private async Task ThrowExceptionsInCircuitBreaker(ICircuitBreaker circuitBreaker, int numberOfExceptions)
 {
     for (var i = 0; i < numberOfExceptions; i++)
     {
         await circuitBreaker.ExecuteAsync(
             token => throw new ApplicationException(),
             exception => Task.CompletedTask,
             _cts.Token);
     }
 }
Пример #31
0
        public async Task TestTripCircuitOnFailuresAboveThreshold()
        {
            string key = "cmd-B";

            HystrixCommand <bool> cmd1 = new SuccessCommand(key, 0);
            ICircuitBreaker       cb   = cmd1._circuitBreaker;
            var stream = HealthCountsStream.GetInstance(HystrixCommandKeyDefault.AsKey(key), cmd1.CommandOptions);

            Assert.True(WaitForHealthCountToUpdate(key, 1000, output), "Health count stream failed to start");

            // this should start as allowing requests
            Assert.True(cb.AllowRequest, "Request NOT allowed when expected!");
            Assert.False(cb.IsOpen, "Circuit breaker is open when it should be closed!");

            // success with high latency
            _ = await cmd1.ExecuteAsync();

            HystrixCommand <bool> cmd2 = new SuccessCommand(key, 0);

            _ = await cmd2.ExecuteAsync();

            HystrixCommand <bool> cmd3 = new FailureCommand(key, 0);

            _ = await cmd3.ExecuteAsync();

            HystrixCommand <bool> cmd4 = new SuccessCommand(key, 0);

            _ = await cmd4.ExecuteAsync();

            HystrixCommand <bool> cmd5 = new FailureCommand(key, 0);

            _ = await cmd5.ExecuteAsync();

            HystrixCommand <bool> cmd6 = new SuccessCommand(key, 0);

            _ = await cmd6.ExecuteAsync();

            HystrixCommand <bool> cmd7 = new FailureCommand(key, 0);

            _ = await cmd7.ExecuteAsync();

            HystrixCommand <bool> cmd8 = new FailureCommand(key, 0);

            _ = await cmd8.ExecuteAsync();

            // Let window pass, this should trip the circuit as the error percentage is above the threshold
            // Time.Wait(125);
            Assert.True(WaitForHealthCountToUpdate(key, 250, output), "Health count stream failed to update");

            output.WriteLine("ReqLog : " + HystrixRequestLog.CurrentRequestLog.GetExecutedCommandsAsString());
            output.WriteLine("Current CircuitBreaker Status : " + cmd1.Metrics.Healthcounts);
            Assert.False(cb.AllowRequest, "Request allowed when NOT expected!");
            Assert.True(cb.IsOpen, "Circuit is closed when it should be open!");
        }
Пример #32
0
 public void Set(ICircuitBreaker c, object state)
 {
     if (state != null)
     {
         store.AddOrUpdate(state, c, (key, old) => c);
     }
     else
     {
         throw new ArgumentException(nameof(state));
     }
 }
Пример #33
0
 public RoutingInfoCommunicator(SqlDataAccess dataAccess, CriticalError criticalError)
 {
     this.dataAccess = dataAccess;
     circuitBreaker  = new RepeatedFailuresOverTimeCircuitBreaker(
         name: "Refresh",
         timeToWaitBeforeTriggering: TimeSpan.FromMinutes(2),
         triggerAction: exception =>
     {
         criticalError.Raise("Failed to refresh routing info.", exception);
     });
 }
Пример #34
0
        private static async Task Execute(ICircuitBreaker cb, ICircuitRequest request)
        {
            var result = await cb.ExecuteAsync(request, cxt => DoSomething(cxt));

            Console.WriteLine(result.Value);

            WriteStatus(result);
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("******");
            Console.WriteLine();
        }
        public ExpiredTimeoutsPoller(IQueryTimeouts timeoutsFetcher, IDispatchMessages dispatcher, string dispatcherAddress, ICircuitBreaker circuitBreaker, Func<DateTime> currentTimeProvider)
        {
            this.timeoutsFetcher = timeoutsFetcher;
            this.dispatcher = dispatcher;
            this.dispatcherAddress = dispatcherAddress;
            this.circuitBreaker = circuitBreaker;
            this.currentTimeProvider = currentTimeProvider;

            var now = currentTimeProvider();
            startSlice = now.AddYears(-10);
            NextRetrieval = now;
        }
Пример #36
0
 public Autoscaler(
     IDynamoDbTableThroughputClient throughputClient,
     IDynamoDbTableMetricsClient metricsClient,
     IAutoscalingCalculator autoscalingCalculator,
     ICircuitBreaker circuitBreaker, 
     ILogger structuredLogger)
 {
     this.throughputClient = throughputClient;
     this.metricsClient = metricsClient;
     this.autoscalingCalculator = autoscalingCalculator;
     this.circuitBreaker = circuitBreaker;
     this.structuredLogger = structuredLogger;
 }
        public CircuitBreakerProductManagementAgent(IProductManagementAgent agent, ICircuitBreaker breaker)
        {
            if (agent == null)
            {
                throw new ArgumentNullException("agent");
            }
            if (breaker == null)
            {
                throw new ArgumentNullException("breaker");
            }

            this.innerAgent = agent;
            this.breaker = breaker;
        }
        private IMetricsPublisherCommand GetOrCreatePublisherForCommand(string commandName, CommandMetrics metrics, ICircuitBreaker circuitBreaker)
        {
            // attempt to retrieve from cache first
            IMetricsPublisherCommand publisher;
            if (_commandPublishers.TryGetValue(commandName, out publisher))
            {
                return publisher;
            }

            // it doesn't exist so we need to create it
            publisher = _context.GetService<IMetricsPublisherCommand>() ?? new DefaultPublisherCommand();

            // attempt to store it (race other threads)
            return _commandPublishers.GetOrAdd(commandName, publisher);
        }
        private IMetricsPublisherCommand GetOrCreatePublisherForCommand(string commandName, CommandMetrics metrics, ICircuitBreaker circuitBreaker, CommandProperties properties)
        {
            // attempt to retrieve from cache first
            IMetricsPublisherCommand publisher;
            if (_commandPublishers.TryGetValue(commandName, out publisher))
            {
                return publisher;
            }

            // it doesn't exist so we need to create it
            IMetricsPublisherCommandFactory factory;
            if (!_commandPublisherFactories.TryGetValue(commandName, out factory))
                return null;

            // attempt to store it (race other threads)
            return _commandPublishers.GetOrAdd(commandName, factory.Create(commandName, metrics, circuitBreaker, properties));
        }
Пример #40
0
 private static void TryExecute(ICircuitBreaker circuitBreaker, Action action)
 {
     try
     {
         circuitBreaker.Execute(action);
     }
     catch (CircuitBreakerOpenException)
     {
         Console.WriteLine("CircuitBreakerOpenException");
     }
     catch (CircuitBreakerTimeoutException)
     {
         Console.WriteLine("CircuitBreakerTimeoutException");
     }
     catch (Exception)
     {
         Console.WriteLine("Exception");
     }
 }
Пример #41
0
 private static async Task TryExecuteAsync(ICircuitBreaker circuitBreaker, Func<Task> action)
 {
     try
     {
         await circuitBreaker.ExecuteAsync(action);
     }
     catch (CircuitBreakerOpenException)
     {
         Console.WriteLine("CircuitBreakerOpenException");
     }
     catch (CircuitBreakerTimeoutException)
     {
         Console.WriteLine("CircuitBreakerTimeoutException");
     }
     catch (Exception)
     {
         Console.WriteLine("Exception");
     }
 }
        internal static CommandState PrepareInternal(Type commandType, IJellyfishContext context, string commandGroup, string commandName, CommandPropertiesBuilder propertiesBuilder=null, IClock clock = null, CommandMetrics metrics = null, ICircuitBreaker circuitBreaker = null)
        {
            var state = new CommandState();

            state.CommandName = commandName ?? commandType.FullName;
            state.CommandGroup = commandGroup ?? state.CommandName;

            clock = clock ?? Clock.GetInstance();
            var properties = propertiesBuilder?.Build( state.CommandName ) ?? new CommandProperties( state.CommandName );
            metrics = metrics ?? CommandMetricsFactory.GetInstance( state.CommandName, state.CommandGroup, properties, clock );
            circuitBreaker = circuitBreaker ?? ( properties.CircuitBreakerEnabled.Value ? CircuitBreakerFactory.GetOrCreateInstance( state.CommandName, properties, metrics, clock ) : new NoOpCircuitBreaker() );
            context.MetricsPublisher.CreateOrRetrievePublisherForCommand( state.CommandGroup, metrics, circuitBreaker );

            ServiceCommandOptions flags = ServiceCommandOptions.None;
            if(IsMethodImplemented( commandType, "GetFallback" ))
                flags |= ServiceCommandOptions.HasFallBack;
            if(IsMethodImplemented( commandType, "GetCacheKey" ))
                flags |= ServiceCommandOptions.HasCacheKey;
            state.Flags = flags;
            return state;
        }
Пример #43
0
        /// <summary>
        /// Instantiate a message processor, using the provided handlers
        /// and timeout/concurrency configuration
        /// </summary>
        public EventProcessor(IMessageHandlerResolver handlerResolver,
            ICircuitBreaker circuitBreaker,
            int maxConcurrency,
            string eventHubName,
            IDispatcherInstrumentationPublisher instrumentationPublisher)
        {
            Logger.Info(
                "Initializing event processor with concurrency {0}",
                maxConcurrency);

            _handlerResolver = handlerResolver;
            _circuitBreaker = circuitBreaker;
            _eventHubName = eventHubName;
            _instrumentationPublisher = instrumentationPublisher;

            // Set up the execution options for bounded concurrency
            // when using the TPL data flow action block
            _options = new ExecutionDataflowBlockOptions
            {
                MaxDegreeOfParallelism = maxConcurrency
            };
        }
Пример #44
0
 public ClosedBehavior(ICircuitBreaker breaker)
 {
     _breaker = breaker;
     _timer = new Timer(Reset, null, breaker.OpenDuration, breaker.OpenDuration);
 }
 public IMetricsPublisherCommand Create(string commandName, CommandMetrics metrics, ICircuitBreaker circuitBreaker, CommandProperties properties)
 {
     return new JsonMetricsPublisherCommand(commandName, metrics, circuitBreaker, properties);
 }
 public IMetricsPublisherCommand CreateOrRetrievePublisherForCommand(string commandName, CommandMetrics metrics, ICircuitBreaker circuitBreaker)
 {
     return GetOrCreatePublisherForCommand(commandName, metrics, circuitBreaker);
 }
Пример #47
0
 public HalfOpenBehavior(ICircuitBreaker breaker, Exception exception, IEnumerator<TimeSpan> timeoutEnumerator)
 {
     _breaker = breaker;
     _exception = exception;
     _timeoutEnumerator = timeoutEnumerator;
 }
 public static IMetricsPublisherCommand CreateOrRetrievePublisherForCommand(string commandName, CommandMetrics metrics, ICircuitBreaker circuitBreaker, CommandProperties properties)
 {
     return MetricsPublisherFactory.Instance.GetOrCreatePublisherForCommand(commandName, metrics, circuitBreaker, properties);
 }
Пример #49
0
 public FakeService(ICircuitBreaker<DoStuffSettings> circuitBreakerDoStuff, ICircuitBreaker<AlsoDoThisSettings> circuitBreakerAlsoDoThis)
 {
     _circuitBreakerDoStuff = circuitBreakerDoStuff;
     _circuitBreakerAlsoDoThis = circuitBreakerAlsoDoThis;
 }