### Installation Source: https://context7.com/dream11/lua-circuit-breaker/llms.txt Instructions for installing the Lua Circuit Breaker library using luarocks or building from source. ```APIDOC ## Installation Install the library using luarocks: ```bash luarocks install lua-circuit-breaker ``` Or build from source: ```bash git clone https://github.com/dream11/lua-circuit-breaker cd lua-circuit-breaker luarocks make ``` ``` -------------------------------- ### Install lua-circuit-breaker from Source Source: https://github.com/dream11/lua-circuit-breaker/blob/master/docs/index.md Clone the repository and build the library locally using LuaRocks. ```bash luarocks make ``` -------------------------------- ### Install lua-circuit-breaker Source: https://github.com/dream11/lua-circuit-breaker/blob/master/README.md Installation methods using luarocks or source code. ```bash luarocks install lua-circuit-breaker ``` ```bash luarocks make ``` -------------------------------- ### Implement Circuit Breaker in Lua Source: https://github.com/dream11/lua-circuit-breaker/blob/master/README.md Example demonstrating how to initialize the factory, configure settings, and wrap an IO call with circuit breaker logic. ```lua --Import Circuit breaker factory. local circuit_breaker_lib = require "lua-circuit-breaker.factory" --Create a new instance of the circuit breaker factory. Always set version = 0. This is used for flushing the circuit breakers when the configuration is changed. local circuit_breakers = circuit_breaker_lib:new() -- Get a circuit breaker instance from factory. Returns a new instance only if not already created. local settings = { version = 1, window_time = 10, min_calls_in_window= 20, failure_percent_threshold= 51, wait_duration_in_open_state= 15, wait_duration_in_half_open_state= 120, half_open_max_calls_in_window= 10, half_open_min_calls_in_window= 5, notify = function(name, state) print(string.format("Breaker [ %s ] state changed to [ %s ]", name, state)) end, } local cb, err = circuit_breakers:get_circuit_breaker( "io_call_x", -- Name of circuit breaker. This should be unique. "io_calls", -- Used to group certain CB objects into one. settings, ) -- Check state of cb. This function returns an error if the state is open or half_open_max_calls_in_window is breached. local _, err_cb = cb:_before() if err_cb then return false, "Circuit breaker open error" end local generation = cb._generation -- Call IO method for which circuit breaking is required. local res, err_http = makeIOCall() -- Update the state of the cb based on successful / failure response. local ok = res and res.status and res.status < 500 cb:_after(generation, ok) -- generation is used to update the counter in the correct time bucket. ``` -------------------------------- ### Install lua-circuit-breaker via LuaRocks Source: https://github.com/dream11/lua-circuit-breaker/blob/master/docs/index.md Use this command to install the library using LuaRocks package manager. ```bash luarocks install lua-circuit-breaker ``` -------------------------------- ### Initialize and Use Circuit Breaker Source: https://github.com/dream11/lua-circuit-breaker/blob/master/docs/index.md Demonstrates how to initialize the circuit breaker factory, get a circuit breaker instance with custom settings, and integrate it with an IO call. Ensure to update the circuit breaker state after the call. ```lua --Import Circuit breaker factory. local circuit_breaker_lib = require "lua-circuit-breaker.factory" --Create a new instance of the circuit breaker factory. Always set version = 0. This is used for flushing the circuit breakers when the configuration is changed. local circuit_breakers = circuit_breaker_lib:new() -- Get a circuit breaker instance from factory. Returns a new instance only if not already created. local settings = { version = 1, window_time = 10, min_calls_in_window= 20, failure_percent_threshold= 51, wait_duration_in_open_state= 15, wait_duration_in_half_open_state= 120, half_open_max_calls_in_window= 10, half_open_min_calls_in_window= 5, notify = function(name, state) print(string.format("Breaker [ %s ] state changed to [ %s ]", name, state)) end, } local cb, err = circuit_breakers:get_circuit_breaker( "io_call_x", -- Name of circuit breaker. This should be unique. "io_calls", -- Used to group certain CB objects into one. settings, ) -- Check state of cb. This function returns an error if the state is open or half_open_max_calls_in_window is breached. local _, err_cb = cb:_before() if err_cb then return false, "Circuit breaker open error" end local generation = cb._generation -- Call IO method for which circuit breaking is required. local res, err_http = makeIOCall() -- Update the state of the cb based on successful / failure response. local ok = res and res.status and res.status < 500 cb:_after(generation, ok) -- generation is used to update the counter in the correct time bucket. ``` -------------------------------- ### Getting a Circuit Breaker Instance Source: https://context7.com/dream11/lua-circuit-breaker/llms.txt Explains how to retrieve or create a circuit breaker instance with specified settings, including configuration options. ```APIDOC ## Getting a Circuit Breaker Instance The `get_circuit_breaker(name, group, settings)` method retrieves or creates a circuit breaker with the specified configuration. If a breaker with the same name exists and the version hasn't changed, the existing instance is returned. Updating the version creates a new breaker with fresh counters. ```lua local circuit_breaker_lib = require "lua-circuit-breaker.factory" local circuit_breakers = circuit_breaker_lib:new() local settings = { version = 1, -- Required: version for config changes window_time = 10, -- Time window in seconds (default: 10) min_calls_in_window = 20, -- Minimum calls before evaluation (default: 20) failure_percent_threshold = 51, -- Failure % to open circuit (default: 51) wait_duration_in_open_state = 15, -- Seconds before trying half-open (default: 15) wait_duration_in_half_open_state = 120, -- Seconds in half-open before auto-close (default: 120) half_open_max_calls_in_window = 10, -- Max calls allowed in half-open (default: 10) half_open_min_calls_in_window = 5, -- Min calls before evaluating half-open (default: 5) notify = function(name, state) print(string.format("Breaker [%s] state changed to [%s]", name, state)) end, } -- Get or create a circuit breaker local cb, err = circuit_breakers:get_circuit_breaker( "api_endpoint_x", -- Unique name for this breaker "external_apis", -- Group name (optional, defaults to "default_group") settings ) if err then print("Error creating circuit breaker: " .. err) return end ``` ``` -------------------------------- ### Get or Create a Circuit Breaker Instance in Lua Source: https://context7.com/dream11/lua-circuit-breaker/llms.txt Retrieve an existing circuit breaker or create a new one with specified settings. Updating the version will create a new breaker with reset counters. Ensure all required settings are provided. ```lua local circuit_breaker_lib = require "lua-circuit-breaker.factory" local circuit_breakers = circuit_breaker_lib:new() local settings = { version = 1, -- Required: version for config changes window_time = 10, -- Time window in seconds (default: 10) min_calls_in_window = 20, -- Minimum calls before evaluation (default: 20) failure_percent_threshold = 51, -- Failure % to open circuit (default: 51) wait_duration_in_open_state = 15, -- Seconds before trying half-open (default: 15) wait_duration_in_half_open_state = 120, -- Seconds in half-open before auto-close (default: 120) half_open_max_calls_in_window = 10, -- Max calls allowed in half-open (default: 10) half_open_min_calls_in_window = 5, -- Min calls before evaluating half-open (default: 5) notify = function(name, state) print(string.format("Breaker [%s] state changed to [%s]", name, state)) end, } -- Get or create a circuit breaker local cb, err = circuit_breakers:get_circuit_breaker( "api_endpoint_x", -- Unique name for this breaker "external_apis", -- Group name (optional, defaults to "default_group") settings ) if err then print("Error creating circuit breaker: " .. err) return end ``` -------------------------------- ### Build Lua Circuit Breaker from Source Source: https://context7.com/dream11/lua-circuit-breaker/llms.txt Follow these steps to clone the repository and build the library from its source code. ```bash git clone https://github.com/dream11/lua-circuit-breaker cd lua-circuit-breaker luarocks make ``` -------------------------------- ### Creating a Circuit Breaker Factory Source: https://context7.com/dream11/lua-circuit-breaker/llms.txt Demonstrates how to create a new circuit breaker factory instance, which manages all circuit breaker objects. ```APIDOC ## Creating a Circuit Breaker Factory The `new()` method creates a new circuit breaker factory instance that manages all circuit breaker objects. The factory organizes breakers by groups and names, allowing efficient reuse and management. ```lua local circuit_breaker_lib = require "lua-circuit-breaker.factory" -- Create a new circuit breaker factory instance local circuit_breakers = circuit_breaker_lib:new() -- Factory structure after creating breakers: -- { -- group_1 = { name_1 = cb_object_1, name_2 = cb_object_2 }, -- group_2 = { name_3 = cb_object_3 }, -- default_group = { name_4 = cb_object_4 } -- } ``` ``` -------------------------------- ### Circuit Breaker Configuration and Usage Source: https://github.com/dream11/lua-circuit-breaker/blob/master/README.md This section details the parameters required to initialize a circuit breaker instance and the workflow for wrapping IO calls. ```APIDOC ## Circuit Breaker Configuration ### Description Defines the settings and initialization process for a circuit breaker instance. ### Parameters #### Settings Object - **name** (string) - Required - Unique identifier for the circuit breaker. - **group** (string) - Optional - Group identifier for the CB object (default: "default_group"). - **settings.version** (number) - Required - Version of settings; changing this flushes older CB instances. - **settings.window_time** (number) - Required - Window size in seconds. - **settings.min_calls_in_window** (number) - Required - Minimum calls in window to start calculation. - **settings.failure_percent_threshold** (number) - Required - Percentage of failures to trigger open state. - **settings.wait_duration_in_open_state** (number) - Required - Seconds to wait before transitioning from open to half-open. - **settings.wait_duration_in_half_open_state** (number) - Required - Seconds to wait in half-open before transitioning to closed. - **settings.half_open_min_calls_in_window** (number) - Required - Minimum calls in half-open state to start calculation. - **settings.half_open_max_calls_in_window** (number) - Required - Maximum calls allowed in half-open state. ### Usage Workflow 1. Call `cb:_before()` to check state and increment request count. 2. Execute the IO operation. 3. Call `cb:_after(generation, ok)` to update success/failure counters based on the result. ``` -------------------------------- ### Lua Circuit Breaker Factory and Usage Source: https://github.com/dream11/lua-circuit-breaker/blob/master/docs/index.md This snippet demonstrates how to initialize the circuit breaker factory, configure a circuit breaker, and integrate it into your application's IO calls. ```APIDOC ## Lua Circuit Breaker Usage ### Description This section details the process of setting up and utilizing the `lua-circuit-breaker` library. It covers initialization, configuration, and the lifecycle of a circuit breaker. ### Installation #### luarocks ```bash luarocks install lua-circuit-breaker ``` #### Source ```bash # Clone the repository git clone https://github.com/dream11/lua-circuit-breaker.git cd lua-circuit-breaker # Build and install using luarocks luarocks make ``` ### Sample Usage ```lua --Import Circuit breaker factory. local circuit_breaker_lib = require "lua-circuit-breaker.factory" --Create a new instance of the circuit breaker factory. Always set version = 0. This is used for flushing the circuit breakers when the configuration is changed. local circuit_breakers = circuit_breaker_lib:new() -- Define circuit breaker settings. local settings = { version = 1, -- Version of settings, changing this creates a new CB. window_time = 10, -- Window size in seconds. min_calls_in_window= 20, -- Minimum calls in window to start calculation. failure_percent_threshold= 51, -- % of requests that should fail to open the circuit. wait_duration_in_open_state= 15, -- Duration (sec) to wait before transitioning from open to half-open. wait_duration_in_half_open_state= 120, -- Duration (sec) to wait in half-open before transitioning to closed. half_open_max_calls_in_window= 10, -- Max calls allowed in half-open state. half_open_min_calls_in_window= 5, -- Min calls in half-open state to start calculation. notify = function(name, state) print(string.format("Breaker [ %s ] state changed to [ %s ]", name, state)) end, } -- Get a circuit breaker instance from the factory. local cb, err = circuit_breakers:get_circuit_breaker( "io_call_x", -- Unique name for this circuit breaker. "io_calls", -- Group name for related circuit breakers. settings, ) -- Check the circuit breaker state before making a call. local _, err_cb = cb:_before() if err_cb then -- Handle circuit breaker being open or max calls in half-open state breached. return false, "Circuit breaker open error" end local generation = cb._generation -- Store generation for later use. -- Simulate making an IO call. local res, err_http = makeIOCall() -- Determine if the call was successful (e.g., status code < 500). local ok = res and res.status and res.status < 500 -- Update the circuit breaker state based on the call result. cb:_after(generation, ok) -- Use generation to update the correct time bucket. ``` ### Circuit Breaker Settings Parameters | Parameter | Default | Type | Required | Description | |---|---|---|---|---| | `name` | NA | string | true | Unique name for the circuit breaker. | | `group` | `"default_group"` | string | false | Group to which the CB object will belong. | | `settings.version` | NA | number | true | Version of the settings object. Changing this creates a new CB and flushes the older one. | | `settings.window_time` | 10 | number | true | Window size in seconds for monitoring requests. | | `settings.min_calls_in_window` | 20 | number | true | Minimum number of calls required within the `window_time` to start calculating failure rates. | | `settings.failure_percent_threshold` | 51 | number | true | The percentage of failures within the `window_time` that will cause the circuit breaker to open. | | `settings.wait_duration_in_open_state` | 15 | number | true | The duration in seconds the circuit breaker will remain in the `open` state before transitioning to `half-open`. | | `settings.wait_duration_in_half_open_state` | 120 | number | true | The duration in seconds the circuit breaker will remain in the `half-open` state before transitioning back to `closed` (if successful) or `open` (if failed). | | `settings.half_open_max_calls_in_window` | 10 | number | true | The maximum number of calls allowed in the `half-open` state during its window. | | `settings.half_open_min_calls_in_window` | 5 | number | true | The minimum number of calls required within the `half-open` state's window to start calculation. | | `settings.half_open_to_open` | NA | function | false | A custom function to override the logic for transitioning from `half-open` to `open`. | | `settings.half_open_to_close` | NA | function | false | A custom function to override the logic for transitioning from `half-open` to `closed`. | | `settings.closed_to_open` | NA | function | false | A custom function to override the logic for transitioning from `closed` to `open`. | | `settings.notify` | NA | function | false | A custom function to be called when the circuit breaker state changes. It receives the breaker name and the new state as arguments. | ``` -------------------------------- ### Test Circuit Breaker with Docker Source: https://github.com/dream11/lua-circuit-breaker/blob/master/ngx_lua_sample/README.md Commands to manage the test environment and trigger circuit breaker states via HTTP requests. ```bash make up # it'll start serving on port 8080 (service) and 9090 (upstream service) http "http://localhost:8080/lua_content" # it fetches content from 9090 with no error # Let's inject a 1.5s timeout (the http client on 8080 is configured to timeout on 300ms) http "http://localhost:9090/commands?timeout=1500" # if we try to fetch from the upstream, it'll delay but it's going to work http "http://localhost:9090/lua_content" # but if we try to fetch from the service http "http://localhost:8080/lua_content" # it'll fail due to the timeout # now, let's force a open circuit state watch -n 0.1 http "http://localhost:8080/lua_content" # from time to time we'll see the cb trying to restablish the service # if you want to make the service back delete the timeout rule http DELETE "http://localhost:9090/commands?timeout=1500" ``` -------------------------------- ### Circuit Breaker Management Methods Source: https://github.com/dream11/lua-circuit-breaker/blob/master/docs/index.md Methods for initializing the circuit breaker factory and managing individual or grouped circuit breaker instances. ```APIDOC ## new() ### Description Creates a new circuit breaker factory instance. ## get_circuit_breaker(name, group, settings) ### Description Creates or retrieves a new circuit breaker object. ### Parameters - **name** (string) - Required - The name of the circuit breaker. - **group** (string) - Required - The group identifier for the circuit breaker. - **settings** (table) - Required - Configuration settings for the circuit breaker. ## check_group(group) ### Description Checks if a specific group exists. ### Parameters - **group** (string) - Required - The group identifier to check. ## remove_breakers_by_group(group) ### Description Removes all circuit breaker objects associated with a specific group. ### Parameters - **group** (string) - Required - The group identifier to remove. ## remove_circuit_breaker(name, group) ### Description Removes a specific circuit breaker within a group. If no group is provided, 'default_group' is assumed. ### Parameters - **name** (string) - Required - The name of the circuit breaker. - **group** (string) - Optional - The group identifier. ``` -------------------------------- ### Create a Circuit Breaker Factory in Lua Source: https://context7.com/dream11/lua-circuit-breaker/llms.txt Instantiate a circuit breaker factory to manage all circuit breaker objects. The factory organizes breakers by groups and names for efficient reuse. ```lua local circuit_breaker_lib = require "lua-circuit-breaker.factory" -- Create a new circuit breaker factory instance local circuit_breakers = circuit_breaker_lib:new() -- Factory structure after creating breakers: -- { -- group_1 = { name_1 = cb_object_1, name_2 = cb_object_2 }, -- group_2 = { name_3 = cb_object_3 }, -- default_group = { name_4 = cb_object_4 } -- } ``` -------------------------------- ### Execute Protected Calls with Circuit Breaker Source: https://context7.com/dream11/lua-circuit-breaker/llms.txt Use _before() to check circuit status and _after() to report call results. Always capture the generation before the IO operation to ensure accurate state updates. ```lua local circuit_breaker_lib = require "lua-circuit-breaker.factory" local circuit_breakers = circuit_breaker_lib:new() local settings = { version = 1, window_time = 10, min_calls_in_window = 20, failure_percent_threshold = 51, wait_duration_in_open_state = 15, wait_duration_in_half_open_state = 120, half_open_max_calls_in_window = 10, half_open_min_calls_in_window = 5, } local function make_protected_call() local cb, err = circuit_breakers:get_circuit_breaker("database_query", "db_calls", settings) if err then return nil, "Failed to get circuit breaker: " .. err end -- Step 1: Check circuit state before the call local _, err_cb = cb:_before() if err_cb then -- Circuit is open or too many requests in half-open state return nil, "Circuit breaker error: " .. err_cb end -- Step 2: Capture generation for accurate state tracking local generation = cb._generation -- Step 3: Make the actual IO call local res, err_io = perform_database_query() -- Your IO function -- Step 4: Report success or failure to the circuit breaker local ok = res ~= nil and err_io == nil cb:_after(generation, ok) if not ok then return nil, "Database query failed: " .. (err_io or "unknown error") end return res, nil end -- Example usage local result, error = make_protected_call() if error then print("Call failed: " .. error) else print("Call succeeded with result: " .. tostring(result)) end ``` -------------------------------- ### Integrate Circuit Breaker with OpenResty Source: https://context7.com/dream11/lua-circuit-breaker/llms.txt Use the factory pattern to manage circuit breaker state within an nginx-lua request handler. Ensure the circuit breaker is retrieved and checked before performing upstream IO operations. ```lua -- nginx.conf location block: -- location /api { -- content_by_lua_file /path/to/handler.lua; -- } -- handler.lua local cb_factory = require "lua-circuit-breaker.factory" local circuit_breakers = cb_factory:new() local settings = { version = 1, window_time = 10, min_calls_in_window = 5, failure_percent_threshold = 51, wait_duration_in_open_state = 15, wait_duration_in_half_open_state = 120, half_open_max_calls_in_window = 5, half_open_min_calls_in_window = 2, notify = function(name, state) ngx.log(ngx.ERR, string.format("Breaker [%s] state changed to [%s]", name, state)) end, } local function handle_request() local upstream_name = ngx.var.upstream_name or "default_upstream" local cb, err = circuit_breakers:get_circuit_breaker( upstream_name, "upstreams", settings ) if err then ngx.log(ngx.ERR, "Circuit breaker error: ", err) ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR) return end local _, err_cb = cb:_before() if err_cb then ngx.log(ngx.WARN, "Circuit open for: ", upstream_name) ngx.exit(ngx.HTTP_SERVICE_UNAVAILABLE) return end local generation = cb._generation -- Make upstream request local res = ngx.location.capture("/internal_upstream") local ok = res and res.status and res.status < 500 cb:_after(generation, ok) if not ok then ngx.exit(ngx.HTTP_BAD_GATEWAY) return end ngx.say(res.body) end handle_request() ``` -------------------------------- ### Circuit Breaker Management Methods Source: https://github.com/dream11/lua-circuit-breaker/blob/master/README.md Methods for creating, retrieving, and removing circuit breaker instances and groups. ```APIDOC ## new() ### Description Creates a new circuit breaker factory. ## get_circuit_breaker(name, group, settings) ### Description Creates a new circuit breaker object. ### Parameters - **name** (string) - Required - The name of the circuit breaker. - **group** (string) - Required - The group name. - **settings** (table) - Required - Configuration settings for the circuit breaker. ## check_group(group) ### Description Checks if a specific group is present. ### Parameters - **group** (string) - Required - The group name to check. ## remove_breakers_by_group(group) ### Description Removes all circuit breaker objects associated with a specific group. ### Parameters - **group** (string) - Required - The group name to remove. ## remove_circuit_breaker(name, group) ### Description Removes a particular circuit breaker inside a group. If group is not passed, 'default_group' is assumed. ### Parameters - **name** (string) - Required - The name of the circuit breaker. - **group** (string) - Optional - The group name. ``` -------------------------------- ### Verify Circuit Breaker Group Existence Source: https://context7.com/dream11/lua-circuit-breaker/llms.txt Use check_group() to verify if a specific group is configured within the factory before performing operations. ```lua local circuit_breaker_lib = require "lua-circuit-breaker.factory" local circuit_breakers = circuit_breaker_lib:new() local settings = { version = 1, window_time = 10, min_calls_in_window = 20, failure_percent_threshold = 51, wait_duration_in_open_state = 15, wait_duration_in_half_open_state = 120, half_open_max_calls_in_window = 10, half_open_min_calls_in_window = 5 } -- Create some circuit breakers circuit_breakers:get_circuit_breaker("endpoint_1", "api_group", settings) circuit_breakers:get_circuit_breaker("endpoint_2", "api_group", settings) circuit_breakers:get_circuit_breaker("db_query", "database_group", settings) -- Check if groups exist local api_exists = circuit_breakers:check_group("api_group") print("api_group exists: " .. tostring(api_exists)) -- true local unknown_exists = circuit_breakers:check_group("unknown_group") print("unknown_group exists: " .. tostring(unknown_exists)) -- false -- Conditional logic based on group existence if circuit_breakers:check_group("database_group") then print("Database circuit breakers are configured") end ``` -------------------------------- ### Handle Circuit Breaker Error States Source: https://context7.com/dream11/lua-circuit-breaker/llms.txt Access predefined error constants to differentiate between an open circuit and capacity limits in half-open states. ```lua local cb_errors = require "lua-circuit-breaker.errors" -- Error when circuit is in open state print(cb_errors.open) -- Output: "Circuit Breaker is open so request was terminated" -- Error when too many requests in half-open state print(cb_errors.too_many_requests) -- Output: "Circuit Breaker reports too many requests in half open state" -- Usage in error handling local circuit_breaker_lib = require "lua-circuit-breaker.factory" local circuit_breakers = circuit_breaker_lib:new() local settings = { version = 1, window_time = 10, min_calls_in_window = 5, failure_percent_threshold = 50, wait_duration_in_open_state = 15, wait_duration_in_half_open_state = 120, half_open_max_calls_in_window = 3, half_open_min_calls_in_window = 2 } local cb, _ = circuit_breakers:get_circuit_breaker("test", "test", settings) local _, err = cb:_before() if err == cb_errors.open then print("Service unavailable - circuit is open, try again later") elseif err == cb_errors.too_many_requests then print("Service busy - half-open capacity reached, try again shortly") elseif err then print("Unknown error: " .. err) end ``` -------------------------------- ### Custom State Transition Functions in Lua Source: https://context7.com/dream11/lua-circuit-breaker/llms.txt Override default state transition logic by providing custom functions for `closed_to_open`, `half_open_to_open`, and `half_open_to_close`. These functions receive a counters object and return true to trigger the transition. A `notify` function can also be provided for custom state change notifications. ```lua local circuit_breaker_lib = require "lua-circuit-breaker.factory" local circuit_breakers = circuit_breaker_lib:new() local settings = { version = 1, window_time = 10, min_calls_in_window = 10, failure_percent_threshold = 50, wait_duration_in_open_state = 15, wait_duration_in_half_open_state = 120, half_open_max_calls_in_window = 10, half_open_min_calls_in_window = 5, -- Custom: Open circuit after 5 consecutive failures closed_to_open = function(counters) return counters.consecutive_failures >= 5 end, -- Custom: Close from half-open after 3 consecutive successes half_open_to_close = function(counters) return counters.consecutive_successes >= 3 end, -- Custom: Re-open from half-open after 2 consecutive failures half_open_to_open = function(counters) return counters.consecutive_failures >= 2 end, notify = function(name, state) print(string.format("[CUSTOM] Breaker [%s] -> %s", name, state)) end, } local cb, _ = circuit_breakers:get_circuit_breaker("custom_service", "custom", settings) -- Counters available in custom functions: -- counters.requests - Total requests in current window -- counters.total_successes - Total successful calls -- counters.total_failures - Total failed calls -- counters.consecutive_successes - Consecutive successes (resets on failure) -- counters.consecutive_failures - Consecutive failures (resets on success) -- counters:total_samples() - Returns total_successes + total_failures ``` -------------------------------- ### Check Circuit Breaker State Source: https://context7.com/dream11/lua-circuit-breaker/llms.txt Retrieve the current state of a circuit breaker to determine if it is closed, open, or half-open. ```lua local circuit_breaker_lib = require "lua-circuit-breaker.factory" local breaker = require "lua-circuit-breaker.breaker" local circuit_breakers = circuit_breaker_lib:new() local settings = { version = 1, window_time = 10, min_calls_in_window = 5, failure_percent_threshold = 50, wait_duration_in_open_state = 15, wait_duration_in_half_open_state = 120, half_open_max_calls_in_window = 10, half_open_min_calls_in_window = 3, } local cb, _ = circuit_breakers:get_circuit_breaker("service_x", "services", settings) -- Check current state local current_state = cb:state() print("Current state: " .. current_state) -- Available states if current_state == breaker.states.closed then print("Circuit is closed - normal operation") elseif current_state == breaker.states.open then print("Circuit is open - failing fast") elseif current_state == breaker.states.half_open then print("Circuit is half-open - testing recovery") end ``` -------------------------------- ### Remove All Circuit Breakers in a Group in Lua Source: https://context7.com/dream11/lua-circuit-breaker/llms.txt Use `remove_breakers_by_group(group)` to remove all circuit breakers within a specified group. Returns true if the group existed and was removed, false otherwise. ```lua local circuit_breaker_lib = require "lua-circuit-breaker.factory" local circuit_breakers = circuit_breaker_lib:new() local settings = { version = 1, window_time = 10, min_calls_in_window = 20, failure_percent_threshold = 51, wait_duration_in_open_state = 15, wait_duration_in_half_open_state = 120, half_open_max_calls_in_window = 10, half_open_min_calls_in_window = 5 } -- Create multiple circuit breakers in the same group circuit_breakers:get_circuit_breaker("endpoint_1", "legacy_api", settings) circuit_breakers:get_circuit_breaker("endpoint_2", "legacy_api", settings) circuit_breakers:get_circuit_breaker("endpoint_3", "legacy_api", settings) circuit_breakers:get_circuit_breaker("new_endpoint", "new_api", settings) -- Remove all circuit breakers in a group at once local removed = circuit_breakers:remove_breakers_by_group("legacy_api") print("Removed legacy_api group: " .. tostring(removed)) -- true -- Verify group no longer exists local still_exists = circuit_breakers:check_group("legacy_api") print("legacy_api still exists: " .. tostring(still_exists)) -- false -- new_api group is unaffected local new_exists = circuit_breakers:check_group("new_api") print("new_api still exists: " .. tostring(new_exists)) -- true ``` -------------------------------- ### Remove Single Circuit Breaker in Lua Source: https://context7.com/dream11/lua-circuit-breaker/llms.txt Use `remove_circuit_breaker(name, group)` to remove a specific circuit breaker. The `group` parameter is optional and defaults to 'default_group'. Returns true on success, false if the breaker or group does not exist. ```lua local circuit_breaker_lib = require "lua-circuit-breaker.factory" local circuit_breakers = circuit_breaker_lib:new() local settings = { version = 1, window_time = 10, min_calls_in_window = 20, failure_percent_threshold = 51, wait_duration_in_open_state = 15, wait_duration_in_half_open_state = 120, half_open_max_calls_in_window = 10, half_open_min_calls_in_window = 5 } -- Create circuit breakers circuit_breakers:get_circuit_breaker("temp_endpoint", "temp_group", settings) circuit_breakers:get_circuit_breaker("default_endpoint", nil, settings) -- Goes to default_group -- Remove a circuit breaker from a specific group local removed = circuit_breakers:remove_circuit_breaker("temp_endpoint", "temp_group") print("Removed from temp_group: " .. tostring(removed)) -- true -- Remove from default_group (nil or empty string uses default_group) local removed_default = circuit_breakers:remove_circuit_breaker("default_endpoint", nil) print("Removed from default_group: " .. tostring(removed_default)) -- true -- Attempting to remove non-existent breaker local not_found = circuit_breakers:remove_circuit_breaker("non_existent", "temp_group") print("Non-existent removal: " .. tostring(not_found)) -- false ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.