Full Code of klarna/circuit_breaker for AI

master 840c38e65460 cached
16 files
53.4 KB
13.2k tokens
1 requests
Download .txt
Repository: klarna/circuit_breaker
Branch: master
Commit: 840c38e65460
Files: 16
Total size: 53.4 KB

Directory structure:
gitextract_vi90d9g9/

├── .gitignore
├── .travis.yml
├── LICENSE
├── README.md
├── doc/
│   ├── .gitignore
│   └── overview.edoc
├── ebin/
│   └── .gitignore
├── include/
│   └── circuit_breaker.hrl
├── rebar.config
├── src/
│   ├── circuit_breaker.app.src
│   ├── circuit_breaker.erl
│   ├── circuit_breaker_app.erl
│   ├── circuit_breaker_event.erl
│   └── circuit_breaker_sup.erl
└── test/
    ├── circuit_breaker_event_test.erl
    └── circuit_breaker_tests.erl

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
_build


================================================
FILE: .travis.yml
================================================
sudo: false

language: erlang

# Use the TEST env variable as the test command
script:
 - $TEST

# Special jobs
matrix:

  # Tests to run only with only the top OTP version (latest)
  include:

  # Check dialyzer
  - env: TEST="rebar3 dialyzer"

# Tests to run with every OTP release
env:
  - TEST="rebar3 eunit"

# Which OTP releases to test (keep latest on top)
otp_release:

  # Two latest minor versions of the most recent OTP release
  - 21.0

  # Last minor version of older OTP releases
  - 20.3
  - 19.3
  - 18.3

# Keep rebar cache (for PLT)
cache:
  directories:
  - "$HOME/.cache/rebar3"


================================================
FILE: LICENSE
================================================
Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "{}"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright {yyyy} {name of copyright owner}

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

================================================
FILE: README.md
================================================
[![Build Status](https://travis-ci.org/klarna/circuit_breaker.svg?branch=master)](https://travis-ci.org/klarna/circuit_breaker)

Generic circuit breaker that can be used to break any service that
isn't fully functional. A service can be manually blocked/cleared as well.

See doc/overview.edoc for more info.

Building
========

    rebar3 compile
    rebar3 doc
    rebar3 eunit

Using
=====

```erlang
%% Circuit-breaking
call(State, SomeId) ->
    circuit_breaker:call(
        % service identifier for the circuit
        {myservice, SomeId},

        % function being monitored
        fun() -> some_call(State) end,

        % call timeout
        timer:minutes(1),

        % reset fun, just returns true
        fun() -> true end,

        % timeout before reset in case of break
        timer:minutes(5),

        %% Options
        [
            % Number of errors tolerated per unit of time.
            {n_error, 3},
            {time_error, timer:minutes(30)},

            %% number of calls returning 'timeout' tolerated in a given
            %% period of time.
            {n_timeout, 3},
            % interval to happen
            {time_timeout, timer:minutes(30)},

            %% number of calls not responding in due time tolerated, and
            %% the time interval for the N failures to happen
            {n_call_timeout, 3},
            {time_call_timeout, timer:minutes(25)},

            %% When failing, the {'EXIT', Reason} tuple will be returned from
            %% the call. This list of `Reason's allows to avoid counting specific
            %% errors towards thresholds that can break a circuit.
            {ignore_errors, []}
        ]
    ).
```


================================================
FILE: doc/.gitignore
================================================
edoc-info
erlang.png
stylesheet.css
*.html


================================================
FILE: doc/overview.edoc
================================================
@copyright 2012 Klarna AB
@title Circuit breaker
@doc Circuit breaker

== General ==

Generic circuit breaker that can be used to break any service that
isn't fully functional. A service can be manually blocked/cleared as well.
The service will be executed in a spawned process that will continue
execution even after a specified call timeout in order to be able
to complete a request even if a response is not sent to the client.
NOTE: It's important that the service can store it's result even
if the result is not returned to the client.

Information regarding current services under circuit breaker
control can be displayed by: circuit_breaker:info/0.

The circuit breaker generates an error event if a service is
automatically blocked due to too many errors/timeouts.
An info event is sent when the service is automatically cleared again.

If several services are used to provide functionallity it's
outside the scope of this server to take care (e.g. send
a critical event) in the case that all used services are
blocked.

The heuristics/thresholds are configurable per service.

@end

================================================
FILE: ebin/.gitignore
================================================
*.app
*.beam


================================================
FILE: include/circuit_breaker.hrl
================================================
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Copyright 2012 Klarna AB
%%%
%%% Licensed under the Apache License, Version 2.0 (the "License");
%%% you may not use this file except in compliance with the License.
%%% You may obtain a copy of the License at
%%%
%%%     http://www.apache.org/licenses/LICENSE-2.0
%%%
%%% Unless required by applicable law or agreed to in writing, software
%%% distributed under the License is distributed on an "AS IS" BASIS,
%%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%%% See the License for the specific language governing permissions and
%%% limitations under the License.
%%%
%%% @doc Circuit breaker
%%% @copyright 2012 Klarna AB
%%% @end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%_* Defines ==========================================================
%% #circuit_breaker.flags
-define(CIRCUIT_BREAKER_OK,           0).
-define(CIRCUIT_BREAKER_WARNING,      (1 bsl 0)).
-define(CIRCUIT_BREAKER_BLOCKED,      (1 bsl 1)).
-define(CIRCUIT_BREAKER_CALL_TIMEOUT, (1 bsl 2)).
-define(CIRCUIT_BREAKER_TIMEOUT,      (1 bsl 3)).
-define(CIRCUIT_BREAKER_ERROR,        (1 bsl 4)).

%% Events
-define(manually_blocked,      manually_blocked).
-define(manually_deblocked,    manually_deblocked).
-define(manually_cleared,      manually_cleared).
-define(automatically_blocked, automatically_blocked).
-define(automatically_cleared, automatically_cleared).
-define(error,                 error).
-define(timeout,               timeout).
-define(call_timeout,          call_timeout).
-define(call_dropped,          call_dropped).
-define(ok_time_metric,        ok_time_metric).

%%%_* Emacs ============================================================
%%% Local Variables:
%%% allout-layout: t
%%% erlang-indent-level: 2
%%% End:


================================================
FILE: rebar.config
================================================
{erl_opts,
 [ debug_info
 , warn_export_vars
 , warn_unused_import
 ]}.

{dialyzer,
 [ {warnings,
    [ unmatched_returns
    , underspecs
    ]}
 , {base_plt_apps,
    [ erts
    , kernel
    , stdlib
    ]}
 ]}.


================================================
FILE: src/circuit_breaker.app.src
================================================
%%-*- mode: erlang -*-
{application, circuit_breaker, [ {description, "Circuit breaker"}
                               , {vsn,          git}
                               , {modules,      []}
                               , {registered,   [ circuit_breaker_sup
                                                ]}
                               , {applications, [ kernel
                                                , stdlib
                                                ]}
                               , {mod,          {circuit_breaker_app, []}}
                               ]}.


================================================
FILE: src/circuit_breaker.erl
================================================
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Copyright 2012 Klarna AB
%%%
%%% Licensed under the Apache License, Version 2.0 (the "License");
%%% you may not use this file except in compliance with the License.
%%% You may obtain a copy of the License at
%%%
%%%     http://www.apache.org/licenses/LICENSE-2.0
%%%
%%% Unless required by applicable law or agreed to in writing, software
%%% distributed under the License is distributed on an "AS IS" BASIS,
%%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%%% See the License for the specific language governing permissions and
%%% limitations under the License.
%%%
%%% @doc Circuit breaker
%%%
%%% Generic circuit breaker that can be used to break any service that
%%% isn't fully functional. A service can be manually blocked/cleared as well.
%%% The service will be executed in a spawned process that will continue
%%% execution even after a specified call timeout in order to be able
%%% to complete a request even if a response is not sent to the client.
%%% NOTE: It's important that the service can store it's result even
%%% if the result is not returned to the client.
%%%
%%% Information regarding current services under circuit breaker
%%% control can be displayed by: circuit_breaker:info/0.
%%%
%%% The circuit breaker generates an error event if a service is
%%% automatically blocked due to too many errors/timeouts.
%%% An info event is sent when the service is automatically cleared again.
%%%
%%% If several services are used to provide functionallity it's
%%% outside the scope of this server to take care (e.g. send
%%% a critical event) in the case that all used services are
%%% blocked.
%%%
%%% The heuristics/thresholds are configurable per service.
%%%
%%% @copyright 2012 Klarna AB
%%% @end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%_* Module declaration ===============================================
-module(circuit_breaker).

%%%_* Behaviour ========================================================
-behaviour(gen_server).

%%%_* Exports ==========================================================
%% API
-export([ start_link/0
        , call/2
        , call/5
        , call/6
        , clear/1
        , block/1
        , deblock/1
        , disabled/1
        , blocked/1
        , info/0
        , info_to_text/0
        ]).

-export([ ok/1
        , error/2
        , error/4
        , error/5
        , call_timeout/2
        , call_timeout/4
        , call_timeout/5
        , timeout/1
        , timeout/3
        , timeout/4
        ]).

%% Gen server callbacks
-export([ init/1
        , handle_call/3
        , handle_cast/2
        , handle_info/2
        , terminate/2
        , code_change/3
        ]).

%%%_* Includes =========================================================
-include("circuit_breaker.hrl").

-define(bit_clr(Fs,F), ((Fs) band (bnot (F)))).
-define(bit_set(Fs,F), ((Fs) bor (F))).
-define(bit_is_set(Fs, F),       ((Fs) band (F) =/= 0)).
-define(bit_set_rec(Rec, Flag),	Rec{flags = ?bit_set(Rec.flags, Flag)}).


%%%_* Records ==========================================================
-record(state, {}).
-record(circuit_breaker,
        { service                            % Term, e.g. {IP|Host, Port}
        , flags        = ?CIRCUIT_BREAKER_OK % Status, ?CIRCUIT_BREAKER_*
        , timeout      = 0                   % {N, non_neg_integer()} | 0
        , call_timeout = 0                   % {N, non_neg_integer()} | 0
        , error        = 0                   % {N, non_neg_integer()} | 0
        , reset_fun                          % Fun to check for up status
        , ref                                % Timer reference
        }).

%%%_* Defines ==========================================================
-define(SERVER,            ?MODULE).
-define(TABLE,             ?MODULE).
-define(CALL_TIMEOUT,      10 * 1000).      % 10 seconds
-define(RESET_TIMEOUT,     10 * 60 * 1000). % 10 minutes
-define(RESET_FUN,         fun() -> true end).
-define(N_ERROR,           10).
-define(N_TIMEOUT,         10).
-define(N_CALL_TIMEOUT,    10).
-define(TIME_ERROR,        60 * 1000).     % 1 minute
-define(TIME_TIMEOUT,      60 * 1000).     % 1 minute
-define(TIME_CALL_TIMEOUT, 5 * 60 * 1000). % 5 minutes
-define(IGNORE_ERRORS,     [no_hit, not_found]).
-define(THRESHOLDS,        [ {n_error,           ?N_ERROR}
                           , {n_timeout,         ?N_TIMEOUT}
                           , {n_call_timeout,    ?N_CALL_TIMEOUT}
                           , {time_error,        ?TIME_ERROR}
                           , {time_timeout,      ?TIME_TIMEOUT}
                           , {time_call_timeout, ?TIME_CALL_TIMEOUT}
                           , {ignore_errors,     ?IGNORE_ERRORS}
                           ]).

-type event_type() :: automatically_blocked |
                      automatically_cleared |
                      call_dropped          |
                      call_timeout          |
                      error                 |
                      manually_blocked      |
                      manually_cleared      |
                      manually_deblocked    |
                      ok_time_metric        |
                      timeout.

-type event_info() :: proplists:proplist() | #circuit_breaker{}.

-export_type([ event_type/0
             , event_info/0
             ]).

%%%_* API ==============================================================
-spec start_link() -> {ok, Pid::pid()} | ignore | {error, Reason::term()}.
%% @doc Start circuit_breaker.
%% @end
start_link() -> gen_server:start_link({local, ?SERVER}, ?SERVER, [], []).

-spec call(Service::term(), CallFun::function()) -> term().
%% @doc Call Service with default parameters.
%% @end
call(Service, CallFun) ->
  call(Service, CallFun, ?CALL_TIMEOUT, ?RESET_FUN, ?RESET_TIMEOUT).

-spec call(Service::term(), CallFun::function(),
           CallTimeout::integer(), ResetFun::function(),
           ResetTimeout::integer()) -> term().
%% @doc Call Service with custom parameters.
%% @end
call(Service, CallFun, CallTimeout, ResetFun, ResetTimeout) ->
  call(Service, CallFun, CallTimeout, ResetFun, ResetTimeout, ?THRESHOLDS).

-spec call(Service::term(), CallFun::function(),
           CallTimeout::integer(), ResetFun::function(),
           ResetTimeout::integer(), Thresholds::list()) -> term().
%% @doc Call Service with custom parameters.
%% @end
call(Service, CallFun, CallTimeout, ResetFun, ResetTimeout, Thresholds) ->
  case read(Service) of
    R when (R#circuit_breaker.flags > ?CIRCUIT_BREAKER_WARNING) ->
      event(?call_dropped, R),
      {error, {circuit_breaker, R#circuit_breaker.flags}};
    _ -> do_call(Service, CallFun, CallTimeout, ResetFun,
                 ResetTimeout, Thresholds)
  end.

-spec block(Service::term()) -> ok | {error, undefined}.
%% @doc Block Service.
%% @end
block(Service) ->
  case try_read(Service) of
    {ok, _} -> change_status(Service, block);
    false   -> {error, undefined}
  end.

-spec deblock(Service::term()) -> ok | {error, undefined}.
%% @doc Deblock Service.
%% @end
deblock(Service) ->
  case try_read(Service) of
    {ok, _} -> change_status(Service, deblock);
    false   -> {error, undefined}
  end.

-spec blocked(Service::term()) -> boolean().
%% @doc Check if Service is manually blocked.
%% @end
blocked(Service) ->
  case try_read(Service) of
    {ok, R} when ?bit_is_set(R#circuit_breaker.flags,
                             ?CIRCUIT_BREAKER_BLOCKED) -> true;
    _                                                  -> false
  end.

-spec disabled(Service::term()) -> boolean().
%% @doc Check if Service is disabled.
%% @end
disabled(Service) ->
  case try_read(Service) of
    {ok, R} -> R#circuit_breaker.flags >= ?CIRCUIT_BREAKER_BLOCKED;
    false   -> false
  end.

-spec clear(Service::term()) -> ok | {error, undefined}.
%% @doc Clear Service (except for manually blocked services).
%% @end
clear(Service) ->
  case try_read(Service) of
    {ok, _} -> change_status(Service, clear);
    false   -> {error, undefined}
  end.

-spec info() -> ok.
%% @doc Print information regarding services.
%% @end
info() ->
  Text = info_to_text(),
  io:put_chars(Text).

-spec info_to_text() -> io_lib:chars().
%% @doc Print information regarding services.
%% @end
info_to_text() ->
  Header  = format("Service", "Status", "Error", "Timeout", "CallTimeout"),
  Split   = format(dup(31, $-), dup(15, $-), dup(8, $-), dup(8, $-), dup(8, $-)),
  Entries = ets:foldl(fun do_info/2, [], ?TABLE),
  [Header, Split, Entries].

%%%_* Gen server callbacks =============================================
%% @hidden
init([]) ->
  ?TABLE = ets:new(?TABLE, [named_table, {keypos, #circuit_breaker.service}]),
  {ok, #state{}}.

%% @hidden
handle_call({init, Service}, _From, State) ->
  do_init(Service),
  {reply, ok, State};
handle_call({change_status, Service, What}, _From, State) ->
  do_change_status(Service, What),
  {reply, ok, State}.

%% @hidden
handle_cast(_Msg, State) -> {noreply, State}.

%% @hidden
handle_info({reset, Service, ResetTimeout}, State) ->
  reset_service(Service, ResetTimeout),
  {noreply, State};

%% @hidden
handle_info(_Info, State) -> {noreply, State}.

%% @hidden
terminate(_Reason, _State) -> ok.

%% @hidden
code_change(_OldVsn, State, _Extra) -> {ok, State}.

%%%_* Internal =========================================================

-dialyzer({no_fail_call, do_call/6}).

do_call(Service, CallFun, CallTimeout, ResetFun, ResetTimeout, Thresholds) ->
  Self   = self(),
  Pid    = proc_lib:spawn(fun() -> called(Self, preserve_exception(CallFun, Service), Service) end),
  MonRef = erlang:monitor(process, Pid),
  receive
    {Pid, Result, Service} ->
      erlang:demonitor(MonRef, [flush]),
      handle_result({got, Result}, Service, ResetFun, ResetTimeout, Thresholds);
    {'DOWN', MonRef, process, Pid, Reason} ->
      handle_result({'EXIT', Reason}, Service, ResetFun,
                    ResetTimeout, Thresholds)
  after CallTimeout ->
      %% Let CallFun/0 continue in order to finish work,
      %% but return to client now.
      Pid ! {Self, call_timeout},
      erlang:demonitor(MonRef, [flush]),
      handle_result({error, call_timeout, Pid}, Service, ResetFun,
                    ResetTimeout, Thresholds)
  end.

preserve_exception(CallFun, Service) ->
  try
    Start = os:timestamp(),
    Res = CallFun(),
    End = os:timestamp(),
    TimeTaken = timer:now_diff(End, Start),
    event(?ok_time_metric, Service, [{time, TimeTaken}]),
    Res
  catch
    Class:Reason:Stacktrace ->
      exit({raise, Class, Reason, Stacktrace})
  end.

called(Parent, Result, Service) ->
  receive
    {Parent, call_timeout} -> exit(normal) % Call did timeout, no return
  after 0 -> Parent ! {self(), Result, Service}
  end.

handle_result({got, Result}, Service, ResetFun, ResetTimeout, Thresholds) ->
  case Result of
    {error, timeout}                         ->
      timeout(Service, ResetFun, ResetTimeout, Thresholds);
    Result when element(1, Result) =:= error ->
      error(Service, Result, ResetFun, ResetTimeout, Thresholds);
    _ -> ok(Service)
  end,
  Result;
handle_result({error, call_timeout, Pid}, Service, ResetFun,
              ResetTimeout, Thresholds) ->
  call_timeout(Pid, Service, ResetFun, ResetTimeout, Thresholds),
  {error, timeout};
handle_result({'EXIT', {raise, Class, Reason, Stacktrace}}, Service, ResetFun,
              ResetTimeout, Thresholds) ->
  error(Service, {'EXIT', Reason}, ResetFun, ResetTimeout, Thresholds),
  %% Keep behavior as if CallFun/0 was executed in same process context.
  erlang:raise(Class, Reason, Stacktrace).

error(Service, Error) ->
  error(Service, Error, ?RESET_FUN, ?RESET_TIMEOUT).

error(Service, Error, ResetFun, ResetTimeout) ->
  error(Service, Error, ResetFun, ResetTimeout, ?THRESHOLDS).

error(Service, {_, Reason} = Error, ResetFun, ResetTimeout, Thresholds) ->
  case lists:member(Reason, ignore_errors(Thresholds)) of
    true  -> ok(Service);
    false ->
      event(error, Service, [{error, Error}]),
      change_status(Service, {error, ResetFun, ResetTimeout, Thresholds})
  end.

call_timeout(Pid, Service) ->
  call_timeout(Pid, Service, ?RESET_FUN, ?RESET_TIMEOUT).

call_timeout(Pid, Service, ResetFun, ResetTimeout) ->
  call_timeout(Pid, Service, ResetFun, ResetTimeout, ?THRESHOLDS).

call_timeout(Pid, Service, ResetFun, ResetTimeout, Thresholds) ->
  event(call_timeout, Service, [{error, {call_timeout, Pid}}]),
  change_status(Service, {call_timeout, ResetFun, ResetTimeout, Thresholds}).

timeout(Service) ->
  timeout(Service, ?RESET_FUN, ?RESET_TIMEOUT).

timeout(Service, ResetFun, ResetTimeout) ->
  timeout(Service, ResetFun, ResetTimeout, ?THRESHOLDS).

timeout(Service, ResetFun, ResetTimeout, Thresholds) ->
  event(timeout, Service, [{error, timeout}]),
  change_status(Service, {timeout, ResetFun, ResetTimeout, Thresholds}).

ok(Service) ->
  case try_read(Service) of
    {ok, R} when R#circuit_breaker.flags =/= ?CIRCUIT_BREAKER_OK ->
      change_status(Service, ok);
    {ok, _R} -> ok;
    false    -> init_circuit_breaker(Service)
  end.

init_circuit_breaker(Service) ->
  gen_server:call(?SERVER, {init, Service}, infinity).

change_status(Service, What) ->
  gen_server:call(?SERVER, {change_status, Service, What}, infinity).

do_info(R, Acc) ->
  Service           = io_lib:format("~p", [R#circuit_breaker.service]),
  Status            = fmt_flags(R#circuit_breaker.flags),
  {Errors, _}       = get_data(R, error),
  {Timeouts, _}     = get_data(R, timeout),
  {CallTimeouts, _} = get_data(R, call_timeout),
  Formatted         = format(Service, Status, integer_to_list(Errors),
                             integer_to_list(Timeouts), integer_to_list(CallTimeouts)),
  [Formatted | Acc].

fmt_flags(0) -> [pif(?CIRCUIT_BREAKER_OK)];
fmt_flags(F) -> lists:flatten(string:join(fmt_flags(0, F, []), ", ")).

fmt_flags(Pos, Flags, Acc) when Flags < (1 bsl Pos) ->
  lists:reverse(Acc);
fmt_flags(Pos, Flags, Acc) when ?bit_is_set(Flags, (1 bsl Pos)) ->
  fmt_flags(Pos + 1, Flags, [pif(1 bsl Pos)|Acc]);
fmt_flags(Pos, Flags, Acc) ->
  fmt_flags(Pos + 1, Flags, Acc).

pif(?CIRCUIT_BREAKER_OK)           -> "OK";
pif(?CIRCUIT_BREAKER_WARNING)      -> "WARNING";
pif(?CIRCUIT_BREAKER_BLOCKED)      -> "BLOCKED";
pif(?CIRCUIT_BREAKER_CALL_TIMEOUT) -> "CALL TIMEOUT";
pif(?CIRCUIT_BREAKER_TIMEOUT)      -> "TIMEOUT";
pif(?CIRCUIT_BREAKER_ERROR)        -> "ERROR".

dup(N, Char) -> lists:duplicate(N, Char).

format(A1, A2, A3, A4, A5) ->
  io_lib:format("~-31s ~-15s ~-8s ~-8s ~-8s~n", [A1, A2, A3, A4, A5]).

do_init(Service) ->
  case exists(Service) of
    false -> write(#circuit_breaker{service = Service});
    true  -> ok
  end.

do_change_status(Service, What) ->
  do_change_status(read(Service), Service, What).

%% What = {error, ResetFun, ResetTimeout, Thresholds} |
%%        {call_timeout, ResetFun, ResetTimeout, Thresholds} |
%%        {timeout, ResetFun, ResetTimeout, Thresholds} |
%%        ok |
%%        block |
%%        deblock |
%%        clear
do_change_status(R, Service, {Type, ResetFun, ResetTimeout, Thresholds}) ->
  fault_status(R, Service, Type, ResetFun, ResetTimeout, Thresholds);
do_change_status(R, _Service, ok) ->
  decrease_counter(R);
do_change_status(R0, _Service, block) ->
  %% Manually blocked
  event(manually_blocked, R0),
  R = maybe_cancel_timer(R0),
  write(?bit_set_rec(R#circuit_breaker, ?CIRCUIT_BREAKER_BLOCKED));
do_change_status(R0, Service, deblock) ->
  %% Manually deblocked; create new default #circuit_breaker{}.
  event(manually_deblocked, R0),
  _R = maybe_cancel_timer(R0),
  write(#circuit_breaker{service = Service});
do_change_status(R0, Service, clear) ->
  %% Manually cleared errors; do not clear CIRCUIT_BREAKER_BLOCKED
  event(manually_cleared, R0),
  R = maybe_cancel_timer(R0),
  Flags =
    if
      ?bit_is_set(R#circuit_breaker.flags,
                  ?CIRCUIT_BREAKER_BLOCKED) -> ?CIRCUIT_BREAKER_BLOCKED;
      true                                  -> ?CIRCUIT_BREAKER_OK
    end,
  write(#circuit_breaker{ service = Service
                        , flags   = Flags
                        }).

gnow() ->
  calendar:datetime_to_gregorian_seconds(calendar:local_time()).

fault_status(R0, _Service, Type, ResetFun, ResetTimeout, Thresholds) ->
  Now           = gnow(),
  {N, LastNow}  = get_data(R0, Type),
  NThreshold    = n_threshold(Thresholds, Type),
  TimeThreshold = time_threshold(Thresholds, Type),
  if
    N + 1 =:= NThreshold,
    Now - LastNow < TimeThreshold        ->
      event(automatically_blocked, R0, [{error, Type}]),
      Flag  = flag(Type),
      R1    = maybe_cancel_timer(R0),
      R2    = set_data(R1, Type, {N + 1, Now}),
      R     = start_timer(R2, ResetTimeout),
      Flags = ?bit_clr(R#circuit_breaker.flags, ?CIRCUIT_BREAKER_WARNING),
      write(R#circuit_breaker{ flags     = ?bit_set(Flags, Flag)
                             , reset_fun = ResetFun
                             });
    Now - LastNow < TimeThreshold, N > 0 ->
      write(set_data(R0, Type, {N + 1, Now}));
    true                                 ->
      R = set_data(R0, Type, {1, Now}),
      write(R#circuit_breaker{flags = ?bit_set(R#circuit_breaker.flags,
                                               ?CIRCUIT_BREAKER_WARNING)})
  end.

%% An ok request; decrease a counter in "severity" order.
decrease_counter(R0) ->
  Types = [error, timeout, call_timeout],
  case decrease_counter(Types, R0, false, 1) of
    {WarnP, R} when WarnP =:= false ->
      write(R#circuit_breaker{flags = ?bit_clr(R#circuit_breaker.flags,
                                               ?CIRCUIT_BREAKER_WARNING)});
    {_WarnP, R} -> write(R)
  end.

decrease_counter([Type|Types], R, WarnP, M) when M > 0   ->
  case get_data(R, Type) of
    {0, _} -> decrease_counter(Types, R, WarnP, M);
    {1, _} -> decrease_counter(Types, set_data(R, Type, 0), WarnP, M - 1);
    {N, T} -> decrease_counter(Types,
                               set_data(R, Type, {N - 1, T}), true, M - 1)
  end;
decrease_counter([Type|Types], R, WarnP, M) when M =:= 0 ->
  case get_data(R, Type) of
    {0, _} -> decrease_counter(Types, R, WarnP, M);
    _      -> decrease_counter(Types, R, true, M)
  end;
decrease_counter([], R, WarnP, _M)                       ->
  {WarnP, R}.

reset_service(Service, ResetTimeout) ->
  R = read(Service),
  case catch (R#circuit_breaker.reset_fun)() of
    true when ?bit_is_set(R#circuit_breaker.flags,
                          ?CIRCUIT_BREAKER_BLOCKED) ->
      write(#circuit_breaker{ service = Service
                            , flags   = ?CIRCUIT_BREAKER_BLOCKED
                            });
    true -> event(automatically_cleared, R),
            write(#circuit_breaker{service = Service});
    _    -> write(start_timer(R, ResetTimeout))
  end.

%%%_* Setters/getters --------------------------------------------------
%% Set/get fault data (error, timeout and call_timeout)
get_data(R, Type) ->
  case do_get_data(R, Type) of
    0    -> {0, gnow()};
    Data -> Data
  end.

do_get_data(R, error)           -> R#circuit_breaker.error;
do_get_data(R, timeout)         -> R#circuit_breaker.timeout;
do_get_data(R, call_timeout)    -> R#circuit_breaker.call_timeout.

set_data(R, error, Data)        -> R#circuit_breaker{error = Data};
set_data(R, timeout, Data)      -> R#circuit_breaker{timeout = Data};
set_data(R, call_timeout, Data) -> R#circuit_breaker{call_timeout = Data}.

n_threshold(L, error)        ->
  proplists:get_value(n_error, L, ?N_ERROR);
n_threshold(L, timeout)      ->
  proplists:get_value(n_timeout, L, ?N_TIMEOUT);
n_threshold(L, call_timeout) ->
  proplists:get_value(n_call_timeout, L, ?N_CALL_TIMEOUT).

time_threshold(L, error)        ->
  proplists:get_value(time_error, L, ?TIME_ERROR);
time_threshold(L, timeout)      ->
  proplists:get_value(time_timeout, L, ?TIME_TIMEOUT);
time_threshold(L, call_timeout) ->
  proplists:get_value(time_call_timeout, L, ?TIME_CALL_TIMEOUT).

ignore_errors(L) -> proplists:get_value(ignore_errors, L, ?IGNORE_ERRORS).

flag(error)        -> ?CIRCUIT_BREAKER_ERROR;
flag(timeout)      -> ?CIRCUIT_BREAKER_TIMEOUT;
flag(call_timeout) -> ?CIRCUIT_BREAKER_CALL_TIMEOUT.

%%%_* Timer ------------------------------------------------------------
%% Clear timer if existing
maybe_cancel_timer(R) when R#circuit_breaker.ref =/= undefined ->
  _ = timer:cancel(R#circuit_breaker.ref),
  flush_reset(R),
  R#circuit_breaker{ref = undefined};
maybe_cancel_timer(R) -> R.

flush_reset(R) ->
  receive
    {reset, Service, _ResetTimeout}
      when Service =:= R#circuit_breaker.service -> ok
  after 0 -> ok
  end.

start_timer(R, ResetTimeout) ->
  {ok, Ref} =
    timer:send_after(ResetTimeout, self(),
                     {reset, R#circuit_breaker.service, ResetTimeout}),
  R#circuit_breaker{ref = Ref}.

%%%_* ETS operations ---------------------------------------------------
read(Service) ->
  case ets:lookup(?TABLE, Service) of
    [R] -> R;
    []  -> #circuit_breaker{service = Service}
  end.

try_read(Service) ->
  case ets:lookup(?TABLE, Service) of
    [R] -> {ok, R};
    []  -> false
  end.

exists(Service) -> ets:lookup(?TABLE, Service) =/= [].

write(#circuit_breaker{} = R) -> ets:insert(?TABLE, R).

%%%_* Event ------------------------------------------------------------
-spec event(event_type(), event_info(), proplists:proplist()) -> any().
event(Type, #circuit_breaker{} = R, Info) when is_list(Info) ->
  event(Type, lists:append(Info, to_proplist(R)));
event(Type, Service, Info) when is_list(Info)                ->
  event(Type, read(Service), Info).

-spec event(event_type(), event_info()) -> any().
event(Type, #circuit_breaker{} = R)   -> event(Type, to_proplist(R));
event(Type, Info) when is_list(Info)  ->
  case application:get_env(circuit_breaker, event_handler) of
    {ok, Module} when is_atom(Module) ->
      Module:handle(Type, Info);
    _ ->
      ok
  end.

to_proplist(#circuit_breaker{ service      = Service
                            , flags        = Flags
                            , timeout      = NTimeout
                            , call_timeout = NCallTimeout
                            , error        = NError
                            }) ->
  [ {service, Service}
  , {flags, Flags}
  , {n_timeout, NTimeout}
  , {n_call_timeout, NCallTimeout}
  , {n_error, NError}
  ].

%%%_* Emacs ============================================================
%%% Local Variables:
%%% allout-layout: t
%%% erlang-indent-level: 2
%%% End:


================================================
FILE: src/circuit_breaker_app.erl
================================================
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Copyright 2012 Klarna AB
%%%
%%% Licensed under the Apache License, Version 2.0 (the "License");
%%% you may not use this file except in compliance with the License.
%%% You may obtain a copy of the License at
%%%
%%%     http://www.apache.org/licenses/LICENSE-2.0
%%%
%%% Unless required by applicable law or agreed to in writing, software
%%% distributed under the License is distributed on an "AS IS" BASIS,
%%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%%% See the License for the specific language governing permissions and
%%% limitations under the License.
%%%
%%% @doc Circuit breaker application
%%% @copyright 2012 Klarna AB
%%% @end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%_* Module declaration ===============================================
-module(circuit_breaker_app).

%%%_* Behaviour ========================================================
-behaviour(application).

%%%_* Exports ==========================================================
%% Application callbacks
-export([ start/2
        , stop/1
        ]).

%%%_* Application callbacks ============================================
-spec start(StartType::normal | {takeover, node()} | {failover, node()},
            StartArgs::term()) ->
               {ok, Pid::pid()}
             | {error, Reason::term()}.
%% @doc This function is called whenever an application is started using
%% application:start/1,2, and should start the processes of the
%% application. If the application is structured according to the OTP
%% design principles as a supervision tree, this means starting the top
%% supervisor of the tree.
%% @end
start(_StartType, _StartArgs) -> circuit_breaker_sup:start_link().

-spec stop(State::term()) -> ok.
%% @doc This function is called whenever an application has stopped. It is
%% intended to be the opposite of Module:start/2 and should do any
%% necessary cleaning up.
%% @end
stop(_State) -> ok.

%%%_* Emacs ============================================================
%%% Local Variables:
%%% allout-layout: t
%%% erlang-indent-level: 2
%%% End:


================================================
FILE: src/circuit_breaker_event.erl
================================================
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Copyright 2012 Klarna AB
%%%
%%% Licensed under the Apache License, Version 2.0 (the "License");
%%% you may not use this file except in compliance with the License.
%%% You may obtain a copy of the License at
%%%
%%%     http://www.apache.org/licenses/LICENSE-2.0
%%%
%%% Unless required by applicable law or agreed to in writing, software
%%% distributed under the License is distributed on an "AS IS" BASIS,
%%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%%% See the License for the specific language governing permissions and
%%% limitations under the License.
%%%
%%% @doc Circuit breaker event behaviour
%%%
%%% Handles events passed from the circuit breaker.
%%%
%%% @copyright 2012 Klarna AB
%%% @end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%_* Module declaration ===============================================
-module(circuit_breaker_event).

%%%_* Exports ==========================================================
%% Behaviour definition
-export([ behaviour_info/1
        ]).

%% API
-export([ handle/2
        ]).

%%%_* Types ============================================================
-type(type() :: manually_blocked
              | manually_deblocked
              | manually_cleared
              | automatically_cleared
              | automatically_blocked
              | error
              | call_timeout
              | timeout).

-export_type([ type/0
             ]).

%%%_* Behaviour definition =============================================
behaviour_info(callbacks) ->
  [ {handle, 2}
  ];
behaviour_info(_Other)    ->
  undefined.

%%%_* API ==============================================================
-spec handle(Type::type(), Info::list()) -> any().
%% @doc Called when circuit breaker generates an event.
%% @end
handle(Type, _Info) ->
  error_logger:info_msg("Received ~w from circuit breaker", [Type]).

%%%_* Emacs ============================================================
%%% Local Variables:
%%% allout-layout: t
%%% erlang-indent-level: 2
%%% End:


================================================
FILE: src/circuit_breaker_sup.erl
================================================
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Copyright 2012 Klarna AB
%%%
%%% Licensed under the Apache License, Version 2.0 (the "License");
%%% you may not use this file except in compliance with the License.
%%% You may obtain a copy of the License at
%%%
%%%     http://www.apache.org/licenses/LICENSE-2.0
%%%
%%% Unless required by applicable law or agreed to in writing, software
%%% distributed under the License is distributed on an "AS IS" BASIS,
%%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%%% See the License for the specific language governing permissions and
%%% limitations under the License.
%%%
%%% @doc Circuit breaker supervisor
%%% @copyright 2012 Klarna AB
%%% @end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%_* Module declaration ===============================================
-module(circuit_breaker_sup).

%%%_* Behaviour ========================================================
-behaviour(supervisor).

%%%_* Exports ==========================================================
%% API
-export([ start_link/0
        ]).

%% Supervisor callbacks
-export([ init/1
        ]).

%%%_* Defines ==========================================================
%% Helper macro for declaring children of supervisor
-define(CHILD(I, Type),
        {I, {I, start_link, []}, permanent, 5000, Type, [I]}).

%%%_* API ==============================================================
-spec start_link() -> {ok, pid()} | ignore | {error, Reason::term()}.
%% @doc Creates a supervisor process as part of a supervision tree.
%% The function will, among other things, ensure that the supervisor
%% is linked to the calling process (its supervisor). The created
%% supervisor process calls Module:init/1
%% @end
start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []).

%%%_* Supervisor callbacks =============================================
%% @hidden
init([]) ->
  {ok, {{one_for_one, 10, 20},
        [ ?CHILD(circuit_breaker, worker)
        ]}}.

%%%_* Emacs ============================================================
%%% Local Variables:
%%% allout-layout: t
%%% erlang-indent-level: 2
%%% End:


================================================
FILE: test/circuit_breaker_event_test.erl
================================================
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Copyright 2012 Klarna AB
%%%
%%% Licensed under the Apache License, Version 2.0 (the "License");
%%% you may not use this file except in compliance with the License.
%%% You may obtain a copy of the License at
%%%
%%%     http://www.apache.org/licenses/LICENSE-2.0
%%%
%%% Unless required by applicable law or agreed to in writing, software
%%% distributed under the License is distributed on an "AS IS" BASIS,
%%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%%% See the License for the specific language governing permissions and
%%% limitations under the License.
%%%
%%% @doc Circuit breaker event test
%%% @copyright 2012 Klarna AB
%%% @end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%_* Module declaration ===============================================
-module(circuit_breaker_event_test).

%%%_* Behaviour ========================================================
-beahviour(circuit_breaker_event).

%%%_* Exports ==========================================================
%% Circuit breaker callback
-export([ handle/2
        ]).

%%%_* Callback =========================================================
%% @see circuit_breaker_event:handle/2
handle(_Type, _Info) -> ok.

%%%_* Emacs ============================================================
%%% Local Variables:
%%% allout-layout: t
%%% erlang-indent-level: 2
%%% End:


================================================
FILE: test/circuit_breaker_tests.erl
================================================
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Copyright 2012 Klarna AB
%%%
%%% Licensed under the Apache License, Version 2.0 (the "License");
%%% you may not use this file except in compliance with the License.
%%% You may obtain a copy of the License at
%%%
%%%     http://www.apache.org/licenses/LICENSE-2.0
%%%
%%% Unless required by applicable law or agreed to in writing, software
%%% distributed under the License is distributed on an "AS IS" BASIS,
%%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%%% See the License for the specific language governing permissions and
%%% limitations under the License.
%%
%%% @doc Circuit breaker tests
%%% @copyright 2012 Klarna AB
%%% @end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%_* Module declaration ===============================================
-module(circuit_breaker_tests).

%%%_* Includes =========================================================
-include_lib("eunit/include/eunit.hrl").
-include("circuit_breaker.hrl").

%%%_* Defines ==========================================================
-define(SERVICE, service).
-define(APP,     circuit_breaker).

%%%_* Tests ============================================================
circuit_breaker_test_() ->
  {"Tests the circuit breaker functionality",
   { foreach
   , fun start/0             % setup
   , fun stop/1              % teardown
   , [ fun undefined/1
     , fun call_timeout_block/1
     , fun timeout_block/1
     , fun error_block/1
     , fun manual_block/1
     , fun manual_deblock/1
     , fun manual_clear/1
     , fun returns/1
     , fun reset/1
     , fun ignore_errors/1
     , fun info/1
     , fun info_to_text/1
     ]}}.

start() ->
  case application:start(?APP) of
    ok                            ->
      ok = application:set_env(?APP, event_handler, circuit_breaker_event_test);
    {error, {already_started, _}} ->
      circuit_breaker:clear(?SERVICE),
      already_started
  end.

stop(already_started) -> ok;
stop(_)               -> application:stop(?APP).

undefined(_Setup) ->
  [ ?_assertEqual({error, undefined}, circuit_breaker:block(?SERVICE))
  , ?_assertEqual({error, undefined}, circuit_breaker:deblock(?SERVICE))
  , ?_assertEqual({error, undefined}, circuit_breaker:clear(?SERVICE))
  , ?_assertEqual(false, circuit_breaker:disabled(?SERVICE))
  , ?_assertEqual(false, circuit_breaker:blocked(?SERVICE))
  ].

call_timeout_block(_Setup) ->
  call(),
  {_, 5} = loop_call(fun() -> timer:sleep(200) end),
  [ ?_assertEqual(false, circuit_breaker:blocked(?SERVICE))
  , ?_assert(circuit_breaker:disabled(?SERVICE))
  , ?_assertEqual({error, {circuit_breaker, ?CIRCUIT_BREAKER_CALL_TIMEOUT}},
                  call())
  ].

timeout_block(_Setup) ->
  call(),
  {_, 5} = loop_call(fun() -> {error, timeout} end),
  [ ?_assertEqual(false, circuit_breaker:blocked(?SERVICE))
  , ?_assert(circuit_breaker:disabled(?SERVICE))
  , ?_assertEqual({error, {circuit_breaker, ?CIRCUIT_BREAKER_TIMEOUT}},
                  call())
  ].

error_block(_Setup) ->
  call(),
  {_, 5} = loop_call(fun() -> {error, crash} end),
  [ ?_assertEqual(false, circuit_breaker:blocked(?SERVICE))
  , ?_assert(circuit_breaker:disabled(?SERVICE))
  , ?_assertEqual({error, {circuit_breaker, ?CIRCUIT_BREAKER_ERROR}},
                  call())
  ].

manual_block(_Setup) ->
  call(),
  circuit_breaker:block(?SERVICE),
  [ ?_assert(circuit_breaker:blocked(?SERVICE))
  , ?_assert(circuit_breaker:disabled(?SERVICE))
  , ?_assertEqual({error, {circuit_breaker, ?CIRCUIT_BREAKER_BLOCKED}}, call())
  ].

manual_deblock(_Setup) ->
  call(),
  circuit_breaker:block(?SERVICE),
  circuit_breaker:deblock(?SERVICE),
  [ ?_assertEqual(false, circuit_breaker:blocked(?SERVICE))
  , ?_assertEqual(false, circuit_breaker:disabled(?SERVICE))
  , ?_assert(call())
  ].

manual_clear(_Setup) ->
  call(),
  {_, 5} = loop_call(fun() -> {error, crash} end),
  circuit_breaker:clear(?SERVICE),
  [ ?_assertEqual(false, circuit_breaker:blocked(?SERVICE))
  , ?_assertEqual(false, circuit_breaker:disabled(?SERVICE))
  , ?_assert(call())
  ].

returns(_Setup) ->
  [ ?_assert(call())
  , ?_assertEqual({error, timeout}, call(fun() -> timer:sleep(200) end))
  , ?_assertEqual({error, timeout}, call(fun() -> {error, timeout} end))
  , ?_assertEqual({error, some_error}, call(fun() -> {error, some_error} end))
  , ?_assertException(exit, reason, call(fun() -> exit(reason) end))
  , ?_assertException(error, reason, call(fun() -> error(reason) end))
  , ?_assertException(throw, reason, call(fun() -> throw(reason) end))
  ].

reset(_Setup) ->
  {_, 5} = loop_call(fun() -> {error, timeout} end),
  [ ?_assert(retry(fun() ->
                       false =:= circuit_breaker:disabled(?SERVICE)
                   end, 1000, 10))
  ].

retry(F, T, N) when N > 0 ->
  case F() of
    Res when Res =:= false
           ; Res =:= error
           ; element(1, Res) =:= error ->
      timer:sleep(T),
      retry(F, T, N-1);
    Res ->
      Res
  end;
retry(_F, _T, 0) -> false.

ignore_errors(_Setup) ->
  call(),
  ok = loop_call(fun() -> {error, some_error} end),
  [ ?_assertEqual(false, circuit_breaker:disabled(?SERVICE))
  ].

info(_Setup) ->
  call(),
  [ ?_assertEqual(ok, circuit_breaker:info())
  ].

info_to_text(_Setup) ->
  call(),
  Result = iolist_to_binary(circuit_breaker:info_to_text()),
  Expected =
    <<"Service                         Status          Error    Timeout  CallTime\n"
    , "------------------------------- --------------- -------- -------- --------\n"
    , "service                         OK              0        0        0       \n"
    >>,
  [ ?_assertEqual(Expected, Result)
  ].

%%%_* Helpers ==========================================================
call() -> call(fun() -> true end).

%% Use custom values to test that these are used
call(F) ->
  circuit_breaker:call( ?SERVICE, F, 100, fun() -> true end, 2000
                      , [ {n_error,           5}
                        , {n_timeout,         5}
                        , {n_call_timeout,    5}
                        , {ignore_errors,     [some_error]}
                        ]
                      ).

loop_call(F) -> loop_call(F, 0).

loop_call(_F, 20) -> ok;
loop_call(F, N)   ->
  case call(F) of
    {error, {circuit_breaker, _}} = Error -> {Error, N};
    _                                     -> loop_call(F, N + 1)
  end.

%%%_* Emacs ============================================================
%%% Local Variables:
%%% allout-layout: t
%%% erlang-indent-level: 2
%%% End:
Download .txt
gitextract_vi90d9g9/

├── .gitignore
├── .travis.yml
├── LICENSE
├── README.md
├── doc/
│   ├── .gitignore
│   └── overview.edoc
├── ebin/
│   └── .gitignore
├── include/
│   └── circuit_breaker.hrl
├── rebar.config
├── src/
│   ├── circuit_breaker.app.src
│   ├── circuit_breaker.erl
│   ├── circuit_breaker_app.erl
│   ├── circuit_breaker_event.erl
│   └── circuit_breaker_sup.erl
└── test/
    ├── circuit_breaker_event_test.erl
    └── circuit_breaker_tests.erl
Condensed preview — 16 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (57K chars).
[
  {
    "path": ".gitignore",
    "chars": 7,
    "preview": "_build\n"
  },
  {
    "path": ".travis.yml",
    "chars": 599,
    "preview": "sudo: false\n\nlanguage: erlang\n\n# Use the TEST env variable as the test command\nscript:\n - $TEST\n\n# Special jobs\nmatrix:\n"
  },
  {
    "path": "LICENSE",
    "chars": 11323,
    "preview": "Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licens"
  },
  {
    "path": "README.md",
    "chars": 1688,
    "preview": "[![Build Status](https://travis-ci.org/klarna/circuit_breaker.svg?branch=master)](https://travis-ci.org/klarna/circuit_b"
  },
  {
    "path": "doc/.gitignore",
    "chars": 43,
    "preview": "edoc-info\nerlang.png\nstylesheet.css\n*.html\n"
  },
  {
    "path": "doc/overview.edoc",
    "chars": 1090,
    "preview": "@copyright 2012 Klarna AB\n@title Circuit breaker\n@doc Circuit breaker\n\n== General ==\n\nGeneric circuit breaker that can b"
  },
  {
    "path": "ebin/.gitignore",
    "chars": 13,
    "preview": "*.app\n*.beam\n"
  },
  {
    "path": "include/circuit_breaker.hrl",
    "chars": 1864,
    "preview": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Copyright 2012 Klarna AB\n%%%\n%%% Lic"
  },
  {
    "path": "rebar.config",
    "chars": 214,
    "preview": "{erl_opts,\n [ debug_info\n , warn_export_vars\n , warn_unused_import\n ]}.\n\n{dialyzer,\n [ {warnings,\n    [ unmatched_return"
  },
  {
    "path": "src/circuit_breaker.app.src",
    "chars": 590,
    "preview": "%%-*- mode: erlang -*-\n{application, circuit_breaker, [ {description, \"Circuit breaker\"}\n                               "
  },
  {
    "path": "src/circuit_breaker.erl",
    "chars": 22614,
    "preview": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Copyright 2012 Klarna AB\n%%%\n%%% Lic"
  },
  {
    "path": "src/circuit_breaker_app.erl",
    "chars": 2204,
    "preview": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Copyright 2012 Klarna AB\n%%%\n%%% Lic"
  },
  {
    "path": "src/circuit_breaker_event.erl",
    "chars": 2152,
    "preview": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Copyright 2012 Klarna AB\n%%%\n%%% Lic"
  },
  {
    "path": "src/circuit_breaker_sup.erl",
    "chars": 2226,
    "preview": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Copyright 2012 Klarna AB\n%%%\n%%% Lic"
  },
  {
    "path": "test/circuit_breaker_event_test.erl",
    "chars": 1484,
    "preview": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Copyright 2012 Klarna AB\n%%%\n%%% Lic"
  },
  {
    "path": "test/circuit_breaker_tests.erl",
    "chars": 6610,
    "preview": "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%% Copyright 2012 Klarna AB\n%%%\n%%% Lic"
  }
]

About this extraction

This page contains the full source code of the klarna/circuit_breaker GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 16 files (53.4 KB), approximately 13.2k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!