Lua implementation of the Circuit Breaker pattern.
Installation
luarocks install moonbreaker
Usage
local moonbreaker = require "moonbreaker"
-- Create Circuit Breaker instance with some settings.
local breaker = moonbreaker {
limit = 10,
timeout = 60,
}
-- We have some error-prone service function...
local function service(threshold)
if math.random() > threshold then
return nil, "error"
end
return true
end
-- ...and we can decorate it with our breaker instance.
service = breaker(service)
-- Now we’re ready to call it!
local ok, err = service(0.5)
See spec/moonbreaker_spec.lua
for details.
Interface
local moonbreaker = require "moonbreaker"
moonbreaker(settings: Settings?): CircuitBreaker
Create a new Circuit Breaker instance.
Example
local breaker = moonbreaker {
limit = 10,
timeout = 60,
success = moonbreaker.success.falsy_err,
}
CircuitBreaker(service: function): function
Wraps service
function with the Circuit Breaker.
Example
service = breaker(service)
CircuitBreaker:state(): state
Get the current state of the Circuit Breaker.
Example
local state = breaker:state()
if state == moonbreaker.states.closed then
print("All systems operational!")
elseif state == moonbreaker.states.open then
print("Houston, we have a problem")
elseif state == moonbreaker.states.half_open then
print("Trying to recover")
end
Settings
Setting | Type | Default |
---|---|---|
|
|
|
|
|
|
|
|
|
Transition Conditions |
||
|
|
|
|
|
|
Interaction With Service Function |
||
|
||
|
||
|
||
|
||
Other |
||
|
||
|
|
Example
local breaker = moonbreaker {
limit = 5,
timeout = 60,
interval = 2 * 60,
should_open = moonbreaker.on.total_failures_rate {
rate = 0.7,
min_samples = 10,
},
success = moonbreaker.success.always,
report_error = moonbreaker.error_reporting.error,
notify = function (state)
print("next state: " .. state)
end,
}
Helpers
moonbreaker.on
-
consecutive_failures(limit: number)
-
consecutive_successes(limit: number)
-
total_failures(limit: number)
-
total_failures_rate(params: {rate: number, min_samples: number})
moonbreaker.success
-
truthy
-
falsy_err
-
always
moonbreaker.error_reporting
-
nil_err
-
false_err
-
error
Types
state
local states = moonbreaker.states
state
is one of:
-
states.closed
-
states.opened
-
states.half_open
error
local errors = moonbreaker.errors
error
is one of:
-
errors.open: string
-
errors.too_many_requests: string
Counters
Counters
is a table with the following properties:
-
requests: number
-
total_successes: number
-
total_failures: number
-
consecutive_successes: number
-
consecutive_failures: number
Settings
Settings
is a table with the properties listed in the
settings table.
Copyright
Copyright © 2020 Arthur Khashaev. See license for details.