├── .formatter.exs ├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── TODO.md ├── config └── config.exs ├── lib ├── external_service.ex └── external_service │ ├── gateway.ex │ ├── rate_limit.ex │ └── retry_options.ex ├── mix.exs ├── mix.lock └── test ├── external_service ├── gateway_test.exs └── rate_limit_test.exs ├── external_service_test.exs └── test_helper.exs /.formatter.exs: -------------------------------------------------------------------------------- 1 | [ 2 | inputs: [ 3 | "lib/**/*.{ex,exs}", 4 | "test/**/*.{ex,exs}", 5 | "mix.exs" 6 | ], 7 | # line_length: 100, 8 | locals_without_parens: [ 9 | ] 10 | ] 11 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # The directory Mix will write compiled artifacts to. 2 | /_build 3 | 4 | # If you run "mix test --cover", coverage assets end up here. 5 | /cover 6 | 7 | # The directory Mix downloads your dependencies sources to. 8 | /deps 9 | 10 | # Where 3rd-party dependencies like ExDoc output generated docs. 11 | /doc 12 | 13 | # Ignore .fetch files in case you like to edit your project deps locally. 14 | /.fetch 15 | 16 | # Ignore elixir LS files 17 | /.elixir_ls 18 | 19 | # Ignore swp files 20 | 21 | *.sw[opn] 22 | 23 | # If the VM crashes, it generates a dump, let's ignore it too. 24 | erl_crash.dump 25 | 26 | # Also ignore archive artifacts (built via "mix archive.build"). 27 | *.ez 28 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project, from version 1.0.0 onward, will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) 6 | and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). 7 | 8 | ## [Unreleased] 9 | 10 | ## 1.1.4 - 2024-01-04 11 | ### Fixed 12 | - Replace use of deprecated `System.stacktrace/0` with `__STACKTRACE__/0` ([PR #17 from @iperks](https://github.com/jvoegele/external_service/pull/17)) 13 | 14 | ## [1.1.3] - 2023-05-12 15 | ### Changed 16 | - Update to retry 0.18.0 17 | - Update ex_rated to 2.1 18 | 19 | ## [1.1.2] - 2021-09-30 20 | 21 | ### Changed 22 | - Make sleep function configurable ([PR #11 from @doorgan](https://github.com/jvoegele/external_service/pull/11)) 23 | 24 | ## [1.1.1] - 2021-09-17 25 | ### Changed 26 | - Update to fuse 2.5 27 | - Update ex_rated to 2.0 28 | 29 | ## [1.1.0] - 2021-09-17 30 | ### Added 31 | - Add `ExternalService.stop/1` ([PR #9 from @doorgan](https://github.com/jvoegele/external_service/pull/9)) 32 | 33 | ### Changed 34 | - Allow any term as fuse name ([PR #10 from @doorgan](https://github.com/jvoegele/external_service/pull/10)) 35 | 36 | 37 | ## [1.0.1] - 2020-06-08 38 | ### Added 39 | - Add ability to reset fuses 40 | - Add documentation for initialization and configuration of gateway modules 41 | 42 | ## [1.0.0] - 2020-06-05 43 | ### Added 44 | - Add new ExternalService.Gateway module for module-based service gateways. 45 | - Add this changelog...better late than never! 46 | 47 | [Unreleased]: https://github.com/jvoegele/external_service/compare/1.0.1...HEAD 48 | [1.1.2]: https://github.com/jvoegele/external_service/compare/1.1.1...1.1.2 49 | [1.1.1]: https://github.com/jvoegele/external_service/compare/1.1.0...1.1.1 50 | [1.1.0]: https://github.com/jvoegele/external_service/compare/1.0.1...1.1.0 51 | [1.0.1]: https://github.com/jvoegele/external_service/compare/1.0.0...1.0.1 52 | [1.0.0]: https://github.com/jvoegele/external_service/compare/0.9.3...1.0.0 53 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ExternalService 2 | 3 | An Elixir library for safely using external service or API using customizable retry logic, automatic rate limiting, and the circuit breaker pattern. Calls to external services can be synchronous, asynchronous background tasks, or multiple calls can be made in parallel for MapReduce style processing. 4 | 5 | ## Overview 6 | 7 | `ExternalService` is, in essence, the combination of two techniques: retrying individual requests that have failed and preventing cascading failures with circuit breakers. The basic approach to using `ExternalService` is to wrap all usages of any external services in an Elixir function and pass this function to the `ExternalService.call` function, together with some options that control the retry mechanism. By doing so, `ExternalService` can manage calls to the external API that you’re using, and apply retry logic to individual calls while ensuring that your application is protected from outages or other problems with the external API by using “circuit breakers” (described in more detail below). 8 | 9 | In addition to the `call` function, `ExternalService` also provides a `call_async` function, which uses an Elixir Task to call the external service asynchronously, and a `call_async_stream` function, which makes multiple calls to the external service in parallel. 10 | 11 | Both of these functions apply the same retry and “circuit breaker” mechanisms as the regular call function. Let’s look at these mechanisms in further detail. 12 | 13 | ### Retrying failed requests 14 | 15 | Many of the failures that occur when accessing external services are transient in nature. For example, there could be network congestion causing a request to timeout, or the service could be under heavy load and is not able to handle any more requests at the time. The best strategy for dealing with such transient failures is to simply retry the failed request – perhaps after a brief backoff period. The `external_service` package uses the [retry library](https://hex.pm/packages/retry) from Safwan Kamarrudin to automate retry logic. This retry library provides flexible configuration to control various aspects of retry logic, such as whether to use linear or exponential backoff, the maximum delay between retries, and the total amount of time to spend retrying before giving up. 16 | 17 | ### Circuit breakers for preventing catastrophic cascade 18 | 19 | The Circuit Breaker pattern was first described in Michael Nygard's landmark book [Release It!](https://pragprog.com/book/mnee/release-it) and was later popularized by Martin Fowler on his [bliki post](https://martinfowler.com/bliki/CircuitBreaker.html). To quote Nygard, “Circuit breakers are a way to automatically degrade functionality when the system is under stress.” 20 | 21 | The Circuit Breaker pattern is modeled after electrical circuit breakers, which are designed to protect electrical circuits from damage caused by excess current. Like these electrical circuit breakers, software “circuit breakers” are designed to protect the system at large from damage caused by faults in a component of the system. By protecting calls to external services, the circuit breaker can monitor for failures. If the failures reach some given threshold, the circuit breaker “trips” and further calls to the service will immediately return an error without even making a call to the external API itself. After a configurable period of time, the circuit breaker is automatically reset and calls to the external service will once again be attempted with the same monitoring as before. 22 | 23 | In contrast to retry logic, which is applied to each individual call to a service, the circuit breaker for a given service is global to the entire system. If a circuit trips, then it trips for all users of the associated service. This is a key feature of the Circuit Breaker pattern, and is what allows it to prevent cascading failures. 24 | 25 | The `external_service` package uses the [Erlang fuse library](https://github.com/jlouis/fuse) from Jesper Louis Andersen for implementing circuit breakers. To extend the electrical analogies, circuit breakers in the fuse library are called “fuses.” These fuses can be used to protect against cascading failure by first asking the fuse if it is OK to proceed using the `:fuse.ask` function. If this function returns `:ok` then it is OK to proceed to calling on the external service. If, on the other hand, it returns `:blown`, then the fuse has been tripped and it is not safe to call the external service. In this scenario, your code must have a fallback option to compensate for the fact that the external service is unavailable, which might mean returning cached data or indicating to the user that the functionality is not currently available. 26 | 27 | What causes a fuse to trip? 28 | When using a fuse, your application code must tell the fuse about any failures that occur. If you’ve asked the fuse if it is OK to proceed but then receive an error from the external service, your code should call the `:fuse.melt` function, which “melts the fuse a little bit”. Once the fuse has been “melted” enough times, the fuse is tripped and future calls to `:fuse.ask` for that fuse will return `:blown`. 29 | 30 | ExternalService wraps the functionality provided by fuse in a convenient interface and automates the handling of the fuse so that you don’t need to explicitly call `:fuse.ask` or `:fuse.melt` in your code. Instead, you simply use the ExternalService.call function with the name of the fuse as the first argument, together with the function in which you’ve wrapped your call to the external API. Then, the ExternalService.call function will first ask the given fuse before making the call and will return `{:error, :fuse_blown}` if the fuse is blown. It will also automatically call `:fuse.melt` any time the call to the given function results in a retry. This eventually results in a blown fuse if there are enough failed requests to the service being protected by the fuse. 31 | 32 | The only requirement for using a fuse for a particular service is that it must be initialized before using the service. This is done with the `ExternalService.start/2` function, which takes the fuse name and options as arguments. The fuse name is an atom which must uniquely identify the external service to which the fuse applies. This function should be called in your application startup code, which is typically the `Application.start` function for your application. 33 | 34 | ### Rate Limiting 35 | 36 | Since version 0.8.0, `ExternalService` allows for rate limiting of calls to a service by specifying the rate limit as an optional argument to `ExternalService.start`. If the `rate_limit` option is passed to `ExternalService.start`, then all calls to the external service will be automatically rate-limited. Once the number of calls to the external service has exceeded the limits for a given time window, then `ExternalService` will delay the call to the service until the time window has expired and calls to the service are allowed again. By default, the delay is accomplished using Elixir's `Process.sleep/1` function, so if you are using `ExternalService.call` then the calling process is put to sleep for the specified time window. If, on the other hand, you are using `ExternalService.call_async` or `ExternalService.call_async_stream`, then it is the background process(es) that are put to sleep, and the calling process is _not_ put to sleep in this case. The sleep function can be configured by passing the `:sleep_function` option to `ExternalService.start`. In any case, the rate-limiting is applied to all calls to a particular service across your application so that you can rest assured that you will not violate the rate limits imposed by the external service that you are calling. 37 | 38 | Applying rate limits to an external service is as simple as specifying the limits in `ExternalService.start`, as in the following example, which limits calls to `:some_external_service` a maximum of 10 times per second: 39 | 40 | ```elixir 41 | ExternalService.start(:some_external_service, rate_limit: {10, 1000}) 42 | ``` 43 | 44 | ## Usage Examples 45 | 46 | Below are some example usages of `ExternalService` that illustrate how to configure fuses and retries, and how to use the various forms of the `call` functions for using an external service reliably. Some of the examples are adapted from the Ropig code base that was the original use case for `ExternalService`, and they show how to use `ExternalService` for interacting with Google's `Pub/Sub` messaging service. 47 | 48 | ### Fuse initialization 49 | 50 | This example shows how to initialize the fuse for a service, as well as how to apply automatic rate limiting to that service. 51 | 52 | ```elixir 53 | defmodule PubSub do 54 | @fuse_name __MODULE__ 55 | @fuse_options [ 56 | # Tolerate 5 failures for every 1 second time window. 57 | fuse_strategy: {:standard, 5, 1_000}, 58 | # Reset the fuse 5 seconds after it is blown. 59 | fuse_refresh: 5_000, 60 | # Limit to 100 calls per second. 61 | rate_limit: {100, 1_000} 62 | ] 63 | 64 | def start do 65 | ExternalService.start(@fuse_name, @fuse_options) 66 | end 67 | end 68 | ``` 69 | 70 | ### Triggering a retry 71 | 72 | This example illustrates the usage of the `ExternalService.call` function and some of the retry options that can be used to control retry behavior. Notice how we delegate to a named function in `call`. 73 | 74 | ```elixir 75 | defmodule PubSub do 76 | @retry_errors [ 77 | 408, # TIMEOUT 78 | 429, # RESOURCE_EXHAUSTED 79 | 499, # CANCELLED 80 | 500, # INTERNAL 81 | 503, # UNAVAILABLE 82 | 504, # DEADLINE_EXCEEDED 83 | ] 84 | @retry_opts %ExternalService.RetryOptions{ 85 | # Use linear backoff. Exponential backoff is also available. 86 | backoff: {:linear, 100, 1}, 87 | # Stop retrying after 5 seconds. 88 | expiry: 5_000, 89 | } 90 | 91 | def publish(message, topic) do 92 | ExternalService.call(PubSub, @retry_opts, fn -> try_publish(message, topic) end) 93 | end 94 | 95 | defp try_publish(message, topic) do 96 | message 97 | |> Kane.Message.publish(%Kane.Topic{name: topic}) 98 | |> case do 99 | {:error, reason, code} when code in @retry_errors -> 100 | {:retry, reason} 101 | kane_result -> 102 | # If not a retriable error, just return the result. 103 | kane_result 104 | end 105 | end 106 | end 107 | ``` 108 | 109 | We wrap our call to the external service in a function and pass this function to `ExternalService.call` with retry options as the second argument. Importantly, we use a special return value from our anonymous function to trigger a retry. A retry is triggered by one of three mechanisms: 110 | 111 | 1. the function returns `:retry` 112 | 1. the function returns a tuple of the form `{:retry, reason}` 113 | 1. the function raises an Elixir `RuntimeError`, or another exception type specified in the `rescue_only` option 114 | 115 | In our example code, we examine the result of calling Kane.Message.publish and if it is an error response with an error code that matches one of our predetermined `@retry_errors`, we then trigger a retry. 116 | 117 | Not all failed requests should be retried, of course. Some failures are due to bugs in the calling code; such calls can never succeed and therefore should not be retried. In our case, we consulted the documentation for Google Pub/Sub to determine which error codes should result in a retry. You will have to decide on a strategy to determine what error conditions are retriable for your service. 118 | 119 | ### Error handling 120 | 121 | Although the retry mechanism goes a long way towards eliminating transient failures, there will be times when a service is unavailable for a long enough time that retries ultimately fail. If, for example, a request has been retried several times and the time spent on retries exceeds the configured `expiry` time for that request, then `ExternalService.call` will give up and return the tuple `{:error, :retries_exhausted}`. 122 | 123 | Another failure scenario is when there are many different processes using an external service concurrently, such as for example many different web requests. If the service or API being used is temporarily unable to handle requests, then all of these concurrent calls to the service will eventually trip the circuit breaker associated with that external service. Then, `ExternalService.call` will return the tuple `{:error, :fuse_blown}`. Further calls to the service at this point would immediately result in the `{:error, :fuse_blown}` until the fuse is reset, which happens automatically after the configured `fuse_refresh` time for the fuse. 124 | 125 | It is up to the caller to determine how to handle these errors. A web application might, for example, log the error and return a *503 Service Unavailable* status code. Background jobs could log the error and pause until the service is fully functioning again. This example shows a Phoenix controller that uses the `PubSub.publish` function from above and handles failed requests by returning a *503* status code. 126 | 127 | ```elixir 128 | defmodule MyApp.MyController do 129 | use MyAppWeb, :controller 130 | require Logger 131 | 132 | @topic "some_topic" 133 | 134 | def create(conn, %{"message" => message}) do 135 | case PubSub.publish(message, @topic) do 136 | {:ok, _result} -> 137 | send_resp(conn, 201, "") 138 | 139 | {:error, {:retries_exhausted, reason}} -> 140 | Logger.error("Retries exhausted while trying to publish to #{@topic}: #{inspect(reason)}") 141 | send_resp(conn, 503, "") 142 | 143 | {:error, {:fuse_blown, fuse_name}} -> 144 | Logger.error("Fuse blown while trying to publish to #{@topic}: #{inspect(fuse_name)}") 145 | send_resp(conn, 503, "") 146 | 147 | error -> 148 | # If we got here it means that we did not an :ok response from Kane, nor did we get one of 149 | # the error tuples meaning retries_exhausted or fuse_blown, so it must be some other kind 150 | # of non-retriable error response from Kane itself. Log the error and send back a 503. 151 | Logger.error("Unknown error while trying to publish to #{@topic}: #{inspect(error)}") 152 | send_resp(conn, 503, "") 153 | end 154 | end 155 | end 156 | ``` 157 | 158 | ### Cleaning up error handling with `ExternalService.call!` 159 | 160 | As seen in the above example, error handling code can be somewhat intricate because we must distinguish between error responses that are created by `ExternalService.call` versus responses that originate from the service itself. In cases like this it can be useful to use `ExternalService.call!` so that error responses created by `ExternalService` are raised as exceptions instead of returned as error tuples. To show how this works, let's add a new `publish!` function to the `PubSub` module, which is just like `publish` except that it uses `call!` instead of `call`. 161 | 162 | ```elixir 163 | defmodule PubSub do 164 | # same @retry_errors and @retry_opts from above example... 165 | 166 | # Will raise a `RetriesExhaustedError` or `FuseBlownError` in event of failure. 167 | def publish!(message, topic) do 168 | ExternalService.call!(PubSub, @retry_opts, fn -> try_publish(message, topic) end) 169 | end 170 | end 171 | ``` 172 | 173 | Now let's see how this impacts our calling code in the hypothetical controller: 174 | 175 | ```elixir 176 | defmodule MyApp.MyController do 177 | use MyAppWeb, :controller 178 | require Logger 179 | 180 | @topic "some_topic" 181 | 182 | def create(conn, %{"message" => message}) do 183 | try do 184 | case PubSub.publish!(message, @topic) do 185 | {:ok, _result} -> 186 | send_resp(conn, 201, "") 187 | 188 | error -> 189 | Logger.error("Unknown error while trying to publish to #{@topic}: #{inspect(error)}") 190 | send_resp(conn, 503, "") 191 | end 192 | rescue 193 | e in [ExternalService.RetriesExhaustedError, ExternalService.FuseBlownError] -> 194 | Logger.error(Exception.format(:error, e)) 195 | send_resp(conn, 503, "") 196 | end 197 | end 198 | end 199 | ``` 200 | 201 | By using `call!`, it is much more apparent which kinds of errors are coming from the actual service being used, rather than those that are created by `ExternalService`. 202 | 203 | ### Asynchronous calls 204 | 205 | In addition to the [`call`](https://hexdocs.pm/external_service/ExternalService.html#call/3) function demonstrated above, the `ExternalService` module also provides `call_async` and `call_async_stream`: 206 | 207 | * [`call_async`](https://hexdocs.pm/external_service/ExternalService.html#call_async/3) - asynchronous version of `call` that returns an Elixir `Task` that can be used to retrieve the result 208 | * [`call_async_stream`](https://hexdocs.pm/external_service/ExternalService.html#call_async_stream/5) - parallel, streaming version of `call` that is modeled after Elixir's built-in `Task.async_stream` function 209 | 210 | Both of these asynchronous functions apply the same retry and circuit breaker mechanisms as the synchronous `call` function, so any necessary retries are performed transparently in the background task(s). 211 | 212 | In the code examples that follow, these asynchronous forms of `call` are illustrated using the same `@retry_errors`, `@retry_opts`, and `try_publish/2` function from the previous example above. 213 | 214 | ```elixir 215 | defmodule PubSub do 216 | # same @retry_errors and @retry_opts from above example... 217 | 218 | # Returns an Elixir `Task`, which can be used to retrieve the result, 219 | # using `Task.await`, for example. 220 | def publish_async(message, topic) do 221 | ExternalService.call_async(PubSub, @retry_opts, fn -> try_publish(message, topic) end) 222 | end 223 | 224 | # Publish many messages in parallel and return a Stream of results as described by `Task.async_stream`. 225 | def publish_async_stream(messages, topic) when is_list(messages) do 226 | ExternalService.call_async_stream(messages, PubSub, @retry_opts, fn message -> 227 | try_publish(message, topic) 228 | end) 229 | end 230 | end 231 | ``` 232 | 233 | Using the async version is a simple means of achieving paralellism since other work can be accomplished while the external calls are taking place. For example: 234 | 235 | ```elixir 236 | task = PubSub.publish_async("Hello", "world") 237 | do_other_things() 238 | case Task.await(task) do 239 | {:ok, _result} -> 240 | :ok 241 | {:error, {:retries_exhausted, reason}} -> 242 | :error 243 | {:error, {:fuse_blown, fuse_name}} -> 244 | :error 245 | end 246 | ``` 247 | 248 | ## Documentation 249 | 250 | See [my blog post](https://ropig.com/blog/use-external-services-safely-reliably-elixir-applications/) for overview documentation, and then check out the [API reference](https://hexdocs.pm/external_service/api-reference.html) for full details. 251 | 252 | ## Installation 253 | 254 | `external_service` is [available in Hex](https://hex.pm/packages/external_service), and can be installed 255 | by adding `external_service` to your list of dependencies in `mix.exs`: 256 | 257 | ```elixir 258 | def deps do 259 | [{:external_service, "~> 1.1.3"}] 260 | end 261 | ``` 262 | 263 | Documentation can be generated with [ExDoc](https://github.com/elixir-lang/ex_doc) 264 | and published on [HexDocs](https://hexdocs.pm). Once published, the docs can 265 | be found at [https://hexdocs.pm/external_service](https://hexdocs.pm/external_service). 266 | 267 | Sponsored by Ropig http://ropig.com 268 | -------------------------------------------------------------------------------- /TODO.md: -------------------------------------------------------------------------------- 1 | # TODO 2 | 3 | TODO items for external_service 4 | 5 | ### Todo 6 | 7 | - [ ] Address open issues and PRs 8 | - [ ] https://github.com/jvoegele/external_service/issues/13 9 | - [ ] https://github.com/jvoegele/external_service/issues/7 10 | - [ ] https://github.com/jvoegele/external_service/issues/5 11 | - [ ] https://github.com/jvoegele/external_service/pull/12 12 | - [ ] Reorganize and improve documentation 13 | - [ ] Break up large README into focused guides 14 | - [ ] Incorporate ExDoc "cheat sheets" for retry techniques, circuit breaker usage, etc. 15 | - [ ] Provide guidance for when and how to use ExternalService.Gateway 16 | - [x] Remove obsolete sponsorship message 17 | - [ ] Set up sponsorship in GitHub and/or Hex? 18 | - [ ] Improve error reporting 19 | - [ ] Use structured errors in {:error, tuples} 20 | - [ ] Ensure exceptions include all relevant details 21 | - [ ] Consider using Flow for call_async_stream 22 | - [ ] Make fuse and retry configuration more readable and discoverable 23 | - [ ] Optionally pass fuse and/or retry info to anonymous functions passed to the various `call` functions 24 | - [ ] Telemetry integration: events for external calls, throttling due to rate limit, etc. 25 | - [ ] Use decorator annotations for marking functions as external calls that use given retry opts? 26 | - [ ] Improve encapsulation of third-party libraries (fuse, retry, ex_rated) 27 | - [ ] Consider removing some or all of those dependencies 28 | 29 | ### In Progress 30 | 31 | - [ ] Fix sporadically failing test: test/external_service_test.exs:171 32 | - [ ] Make ExternalService.Gateway.Config 100% resilient (Don't link to other processes? Use Elixir's Registry?) 33 | 34 | ### Done ✓ 35 | 36 | - [x] Create TODO.md 37 | -------------------------------------------------------------------------------- /config/config.exs: -------------------------------------------------------------------------------- 1 | # This file is responsible for configuring your application 2 | # and its dependencies with the aid of the Mix.Config module. 3 | import Config 4 | 5 | # This configuration is loaded before any dependency and is restricted 6 | # to this project. If another project depends on this project, this 7 | # file won't be loaded nor affect the parent project. For this reason, 8 | # if you want to provide default values for your application for 9 | # 3rd-party users, it should be done in your "mix.exs" file. 10 | 11 | # You can configure for your application as: 12 | # 13 | # config :external_service, key: :value 14 | # 15 | # And access this configuration in your application as: 16 | # 17 | # Application.get_env(:external_service, :key) 18 | # 19 | # Or configure a 3rd-party app: 20 | # 21 | # config :logger, level: :info 22 | # 23 | 24 | # It is also possible to import configuration files, relative to this 25 | # directory. For example, you can emulate configuration per environment 26 | # by uncommenting the line below and defining dev.exs, test.exs and such. 27 | # Configuration from the imported file will override the ones defined 28 | # here (which is why it is important to import them last). 29 | # 30 | # import_config "#{Mix.env}.exs" 31 | 32 | config :sasl, :sasl_error_logger, false 33 | -------------------------------------------------------------------------------- /lib/external_service.ex: -------------------------------------------------------------------------------- 1 | defmodule ExternalService do 2 | @moduledoc """ 3 | ExternalService handles all retry and circuit breaker logic for calls to external services. 4 | """ 5 | 6 | alias ExternalService.RetryOptions 7 | alias ExternalService.RateLimit 8 | alias :fuse, as: Fuse 9 | 10 | require Logger 11 | 12 | @typedoc "Name of a fuse" 13 | @type fuse_name :: term() 14 | 15 | @typedoc "Error tuple returned when the allowable number of retries has been exceeded" 16 | @type retries_exhausted :: {:error, {:retries_exhausted, reason :: any}} 17 | 18 | @typedoc "Error tuple returned when a fuse has been melted enough times that the fuse is blown" 19 | @type fuse_blown :: {:error, {:fuse_blown, fuse_name}} 20 | 21 | @typedoc "Error tuple returned when a fuse has not been initialized with `ExternalService.start/1`" 22 | @type fuse_not_found :: {:error, {:fuse_not_found, fuse_name}} 23 | 24 | @typedoc "Union type representing all the possible error tuple return values" 25 | @type error :: retries_exhausted | fuse_blown | fuse_not_found 26 | 27 | @type retriable_function_result :: 28 | :retry | {:retry, reason :: any()} | (function_result :: any()) 29 | 30 | @type retriable_function :: (() -> retriable_function_result()) 31 | 32 | @typedoc """ 33 | Strategy controlling fuse behavior. 34 | """ 35 | @type fuse_strategy :: 36 | {:standard, max_melt_attempts :: pos_integer(), time_window :: pos_integer()} 37 | | {:fault_injection, rate :: float(), max_melt_attempts :: pos_integer(), 38 | time_window :: pos_integer()} 39 | 40 | @typedoc """ 41 | A tuple specifying rate-limiting behavior. 42 | 43 | The first element of the tuple is the number of calls to allow in a given time window. 44 | The second element is the time window in milliseconds. 45 | """ 46 | @type rate_limit :: {limit :: pos_integer(), time_window :: pos_integer()} 47 | 48 | @typedoc """ 49 | The sleep function to be called when reaching the configured rate limit quota. 50 | 51 | In some situations, like tests, blocking the process for an extended period of 52 | time can be undesired. In these cases this function can be changed. Defaults 53 | to `Process.sleep/1`. 54 | """ 55 | @type sleep_function :: (number -> any) 56 | 57 | @typedoc """ 58 | Options used for controlling circuit breaker and rate-limiting behavior. 59 | 60 | See the [fuse docs](https://hexdocs.pm/fuse/) for further information about available fuse options. 61 | """ 62 | @type options :: [ 63 | fuse_strategy: fuse_strategy(), 64 | fuse_refresh: pos_integer(), 65 | rate_limit: rate_limit(), 66 | sleep_function: sleep_function() 67 | ] 68 | 69 | @default_fuse_options %{ 70 | fuse_strategy: {:standard, 10, 10_000}, 71 | fuse_refresh: 60_000 72 | } 73 | 74 | defmodule RetriesExhaustedError do 75 | @moduledoc """ 76 | Exception raised by `ExternalService.call!/3` when the allowable number of retries has been 77 | exceeded. 78 | """ 79 | defexception [:message] 80 | end 81 | 82 | defmodule FuseBlownError do 83 | @moduledoc """ 84 | Exception raised by `ExternalService.call!/3` when a fuse has been melted enough times that 85 | the fuse is blown. 86 | """ 87 | defexception [:message] 88 | end 89 | 90 | defmodule FuseNotFoundError do 91 | @moduledoc """ 92 | Exception raised by `ExternalService.call!/3` when a fuse has not been initialized with 93 | `ExternalService.start/1`. 94 | """ 95 | defexception [:message] 96 | end 97 | 98 | defmodule State do 99 | @moduledoc false 100 | 101 | defstruct [:fuse_name, :fuse_options, :rate_limit] 102 | 103 | def init(fuse_name, fuse_options, rate_limit) do 104 | state = %__MODULE__{ 105 | fuse_name: fuse_name, 106 | fuse_options: fuse_options, 107 | rate_limit: rate_limit 108 | } 109 | 110 | Agent.start(fn -> state end, name: registered_name(fuse_name)) 111 | state 112 | end 113 | 114 | def get(fuse_name), do: Agent.get(registered_name(fuse_name), & &1) 115 | 116 | def registered_name(fuse_name), do: Module.concat(fuse_name, __MODULE__) 117 | end 118 | 119 | @doc """ 120 | Initializes a new fuse for a specific service. 121 | 122 | The `fuse_name` is a term that uniquely identifies an external service within the scope of 123 | an application. 124 | 125 | The `options` argument allows for controlling the circuit breaker behavior and rate-limiting 126 | behavior when making calls to the external service. See `t:options/0` for details. 127 | """ 128 | @spec start(fuse_name(), options()) :: :ok 129 | def start(fuse_name, options \\ []) do 130 | fuse_opts = { 131 | Keyword.get(options, :fuse_strategy, @default_fuse_options.fuse_strategy), 132 | {:reset, Keyword.get(options, :fuse_refresh, @default_fuse_options.fuse_refresh)} 133 | } 134 | 135 | :ok = Fuse.install(fuse_name, fuse_opts) 136 | rate_limit = RateLimit.new(fuse_name, Keyword.get(options, :rate_limit), options) 137 | State.init(fuse_name, fuse_opts, rate_limit) 138 | :ok 139 | end 140 | 141 | @doc """ 142 | Stops the fuse for a specific service. 143 | """ 144 | @spec stop(fuse_name()) :: :ok 145 | def stop(fuse_name) when is_atom(fuse_name) do 146 | :ok = Fuse.remove(fuse_name) 147 | :ok = State.registered_name(fuse_name) |> Agent.stop() 148 | :ok 149 | end 150 | 151 | @doc """ 152 | Resets the given fuse. 153 | 154 | After reset, the fuse will be unbroken with no melts. 155 | """ 156 | @spec reset_fuse(fuse_name()) :: :ok | {:error, :not_found} 157 | def reset_fuse(fuse_name), do: Fuse.reset(fuse_name) 158 | 159 | @doc """ 160 | Given a fuse name and retry options execute a function handling any retry and circuit breaker 161 | logic. 162 | 163 | `ExternalService.start` must be run with the fuse name before using call. 164 | 165 | The provided function can indicate that a retry should be performed by returning the atom 166 | `:retry` or a tuple of the form `{:retry, reason}`, where `reason` is any arbitrary term, or by 167 | raising a `RuntimeError`. Any other result is considered successful so the operation will not be 168 | retried and the result of the function will be returned as the result of `call`. 169 | """ 170 | @spec call(fuse_name(), RetryOptions.t(), retriable_function()) :: 171 | error | (function_result :: any) 172 | def call(fuse_name, retry_opts \\ %RetryOptions{}, function) do 173 | case call_with_retry(fuse_name, retry_opts, function) do 174 | {:no_retry, result} -> result 175 | {:error, :retry} -> {:error, {:retries_exhausted, :reason_unknown}} 176 | {:error, {:retry, reason}} -> {:error, {:retries_exhausted, reason}} 177 | result -> result 178 | end 179 | end 180 | 181 | @doc """ 182 | Like `call/3`, but raises an exception if retries are exhausted or the fuse is blown. 183 | """ 184 | @spec call!(fuse_name(), RetryOptions.t(), retriable_function()) :: 185 | function_result :: any | no_return 186 | def call!(fuse_name, retry_opts \\ %RetryOptions{}, function) do 187 | case call_with_retry(fuse_name, retry_opts, function) do 188 | {:no_retry, result} -> 189 | result 190 | 191 | {:error, :retry} -> 192 | raise ExternalService.RetriesExhaustedError, message: "fuse_name: #{fuse_name}" 193 | 194 | {:error, {:retry, reason}} -> 195 | raise ExternalService.RetriesExhaustedError, 196 | message: "reason: #{inspect(reason)}, fuse_name: #{fuse_name}" 197 | 198 | {:error, {:fuse_blown, fuse_name}} -> 199 | raise ExternalService.FuseBlownError, message: inspect(fuse_name) 200 | 201 | {:error, {:fuse_not_found, fuse_name}} -> 202 | raise ExternalService.FuseNotFoundError, message: fuse_not_found_message(fuse_name) 203 | end 204 | end 205 | 206 | @doc """ 207 | Asynchronous version of `ExternalService.call`. 208 | 209 | Returns a `Task` that may be used to retrieve the result of the async call. 210 | """ 211 | @spec call_async(fuse_name(), RetryOptions.t(), retriable_function()) :: Task.t() 212 | def call_async(fuse_name, retry_opts \\ %RetryOptions{}, function) do 213 | Task.async(fn -> call(fuse_name, retry_opts, function) end) 214 | end 215 | 216 | @doc """ 217 | Parallel, streaming version of `ExternalService.call`. 218 | 219 | See `call_async_stream/5` for full documentation. 220 | """ 221 | @spec call_async_stream(Enumerable.t(), fuse_name(), (any() -> retriable_function_result())) :: 222 | Enumerable.t() 223 | def call_async_stream(enumerable, fuse_name, function) when is_function(function), 224 | do: call_async_stream(enumerable, fuse_name, %RetryOptions{}, [], function) 225 | 226 | @doc """ 227 | Parallel, streaming version of `ExternalService.call`. 228 | 229 | See `call_async_stream/5` for full documentation. 230 | """ 231 | @spec call_async_stream( 232 | Enumerable.t(), 233 | fuse_name(), 234 | RetryOptions.t() | (async_opts :: list()), 235 | (any() -> retriable_function_result()) 236 | ) :: Enumerable.t() 237 | def call_async_stream(enumerable, fuse_name, retry_opts_or_async_opts, function) 238 | 239 | def call_async_stream(enumerable, fuse_name, retry_opts = %RetryOptions{}, function) 240 | when is_function(function), 241 | do: call_async_stream(enumerable, fuse_name, retry_opts, [], function) 242 | 243 | def call_async_stream(enumerable, fuse_name, async_opts, function) 244 | when is_list(async_opts) and is_function(function), 245 | do: call_async_stream(enumerable, fuse_name, %RetryOptions{}, async_opts, function) 246 | 247 | @doc """ 248 | Parallel, streaming version of `ExternalService.call`. 249 | 250 | This function uses Elixir's built-in `Task.async_stream/3` function and the description below is 251 | taken from there. 252 | 253 | Returns a stream that runs the given function `function` concurrently on each 254 | item in `enumerable`. 255 | 256 | Each `enumerable` item is passed as argument to the given function `function` 257 | and processed by its own task. The tasks will be linked to the current 258 | process, similarly to `async/1`. 259 | """ 260 | @spec call_async_stream( 261 | Enumerable.t(), 262 | fuse_name(), 263 | RetryOptions.t(), 264 | async_opts :: list(), 265 | (any() -> retriable_function_result()) 266 | ) :: Enumerable.t() 267 | def call_async_stream(enumerable, fuse_name, retry_opts = %RetryOptions{}, async_opts, function) 268 | when is_list(async_opts) and is_function(function) do 269 | fun = fn item -> 270 | call(fuse_name, retry_opts, fn -> function.(item) end) 271 | end 272 | 273 | Task.async_stream(enumerable, fun, async_opts) 274 | end 275 | 276 | @spec call_with_retry(fuse_name(), RetryOptions.t(), retriable_function()) :: 277 | {:no_retry, function_result :: any()} 278 | | {:error, :retry} 279 | | {:error, {:retry, reason :: any()}} 280 | | fuse_blown 281 | | fuse_not_found 282 | | (function_result :: any()) 283 | defp call_with_retry(fuse_name, retry_opts, function) do 284 | require Retry 285 | 286 | Retry.retry with: apply_retry_options(retry_opts), rescue_only: retry_opts.rescue_only do 287 | case Fuse.ask(fuse_name, :sync) do 288 | :ok -> try_function(fuse_name, function) 289 | :blown -> throw(:blown) 290 | {:error, :not_found} -> throw(:not_found) 291 | end 292 | after 293 | {:no_retry, _} = result -> result 294 | else 295 | {:error, :retry} = error -> error 296 | {:error, {:retry, _reason}} = error -> error 297 | error -> raise(error) 298 | end 299 | catch 300 | :blown -> 301 | {:error, {:fuse_blown, fuse_name}} 302 | 303 | :not_found -> 304 | log_fuse_not_found(fuse_name) 305 | {:error, {:fuse_not_found, fuse_name}} 306 | end 307 | 308 | defp apply_retry_options(retry_opts) do 309 | import Retry.DelayStreams 310 | 311 | delay_stream = 312 | case retry_opts.backoff do 313 | {:exponential, initial_delay} -> exponential_backoff(initial_delay) 314 | {:linear, initial_delay, factor} -> linear_backoff(initial_delay, factor) 315 | end 316 | 317 | retry_opts 318 | |> Map.take([:randomize, :expiry, :cap]) 319 | |> Enum.reduce(delay_stream, fn {key, value}, acc -> 320 | if value do 321 | apply(Retry.DelayStreams, key, [acc, value]) 322 | else 323 | acc 324 | end 325 | end) 326 | end 327 | 328 | @spec try_function(fuse_name, retriable_function) :: 329 | {:error, {:retry, any}} | {:error, :retry} | {:no_retry, any} | no_return 330 | defp try_function(fuse_name, function) do 331 | rate_limit = State.get(fuse_name).rate_limit 332 | 333 | case RateLimit.call(rate_limit, function) do 334 | {:retry, reason} -> 335 | Fuse.melt(fuse_name) 336 | {:error, {:retry, reason}} 337 | 338 | :retry -> 339 | Fuse.melt(fuse_name) 340 | {:error, :retry} 341 | 342 | result -> 343 | {:no_retry, result} 344 | end 345 | rescue 346 | error -> 347 | Fuse.melt(fuse_name) 348 | reraise error, __STACKTRACE__ 349 | end 350 | 351 | defp log_fuse_not_found(fuse_name) do 352 | Logger.error(fuse_not_found_message(fuse_name)) 353 | end 354 | 355 | defp fuse_not_found_message(fuse_name) do 356 | fuse_name = inspect(fuse_name) 357 | 358 | "Fuse :#{fuse_name} not found. To initialize this fuse, call " <> 359 | "ExternalService.start(:#{fuse_name}) in your application start code." 360 | end 361 | end 362 | -------------------------------------------------------------------------------- /lib/external_service/gateway.ex: -------------------------------------------------------------------------------- 1 | defmodule ExternalService.Gateway do 2 | @moduledoc """ 3 | Defines a gateway to an external service. 4 | 5 | `ExternalService.Gateway` allows for defining module-based gateways to external services. 6 | Instead of explicitly starting a fuse with its configuration and separately passing in retry 7 | options on each call to the service, a module-based gateway allows one to specify default fuse 8 | and retry options at the module level. 9 | 10 | When a module uses the `ExternalService.Gateway` module, an implementation of the 11 | `ExternalService.Gateway` behaviour will be generated using the fuse, retry, and rate-limit 12 | options provided to the `use ExternalService.Gateway` statement. See the documentation for the 13 | various callbacks in this module for more details. 14 | 15 | ## Example 16 | 17 | defmodule MyApp.SomeService do 18 | use ExternalService.Gateway, 19 | fuse: [ 20 | # Tolerate 5 failures for every 1 second time window. 21 | strategy: {:standard, 5, 10_000}, 22 | # Reset the fuse 5 seconds after it is blown. 23 | refresh: 5_000 24 | ], 25 | # Limit to 5 calls per second. 26 | rate_limit: {5, :timer.seconds(1)}, 27 | retry: [ 28 | # Use linear backoff. Exponential backoff is also available. 29 | backoff: {:linear, 100, 1}, 30 | # Stop retrying after 5 seconds. 31 | expiry: 5_000 32 | ] 33 | 34 | def call_the_service(params) do 35 | external_call fn -> 36 | # Call the service with params, then return the result or :retry. 37 | case do_call(params) do 38 | {:ok, result} -> {:ok, result} 39 | {:error, reason} -> {:retry, reason} 40 | end 41 | end 42 | end 43 | end 44 | 45 | ## Initialization and configuration 46 | 47 | Gateways must be started (preferably under a supervisor) before being used. 48 | 49 | To initialize a gateway with its default configuration, just add the gateway module to the 50 | top-level supervisor for your application: 51 | 52 | children = [ 53 | MyApp.SomeService 54 | ] 55 | 56 | Supervisor.start_link(children, strategy: :one_for_one) 57 | 58 | It is also possible to override the default configuration for the gateway by passing options to 59 | the child specification that is passed to the supervisor. This can be useful for using different 60 | configuration in the test environment. For example: 61 | 62 | some_service_config = Application.get_env(:my_app, :some_service, []) 63 | 64 | children = [ 65 | {MyApp.SomeService, some_service_config} 66 | ] 67 | 68 | Supervisor.start_link(children, strategy: :one_for_one) 69 | """ 70 | 71 | alias ExternalService.RetryOptions 72 | 73 | @doc """ 74 | Invoked to call the given function using the retry options configured for the gateway. 75 | 76 | See `ExternalService.call/3` for more information. 77 | """ 78 | @callback external_call(ExternalService.retriable_function()) :: 79 | ExternalService.error() | (function_result :: any) 80 | 81 | @doc """ 82 | Invoked to call the given function using custom retry options. 83 | 84 | See `ExternalService.call/3` for more information. 85 | """ 86 | @callback external_call(RetryOptions.t(), ExternalService.retriable_function()) :: 87 | ExternalService.error() | (function_result :: any) 88 | 89 | @doc """ 90 | Like `external_call/1`, but raises an exception if retries are exhausted or the fuse is blown. 91 | 92 | See `ExternalService.call!/3` for more information. 93 | """ 94 | @callback external_call!(ExternalService.retriable_function()) :: 95 | function_result :: any | no_return 96 | 97 | @doc """ 98 | Like `external_call/2`, but raises an exception if retries are exhausted or the fuse is blown. 99 | 100 | See `ExternalService.call!/3` for more information. 101 | """ 102 | @callback external_call!(RetryOptions.t(), ExternalService.retriable_function()) :: 103 | function_result :: any | no_return 104 | 105 | @doc """ 106 | Asynchronous version of `external_call/1`. 107 | 108 | Returns a `Task` that may be used to retrieve the result of the async call. 109 | 110 | See `ExternalService.call_async` for more information. 111 | """ 112 | @callback external_call_async(ExternalService.retriable_function()) :: Task.t() 113 | 114 | @doc """ 115 | Asynchronous version of `external_call/2`. 116 | 117 | Returns a `Task` that may be used to retrieve the result of the async call. 118 | 119 | See `ExternalService.call_async` for more information. 120 | """ 121 | @callback external_call_async(RetryOptions.t(), ExternalService.retriable_function()) :: 122 | Task.t() 123 | 124 | @doc """ 125 | Parallel, streaming version of `external_call/1`. 126 | 127 | See `ExternalService.call_async_stream/5` for more information. 128 | """ 129 | @callback external_call_async_stream( 130 | Enumerable.t(), 131 | (any() -> ExternalService.retriable_function_result()) 132 | ) :: 133 | Enumerable.t() 134 | 135 | @doc """ 136 | Parallel, streaming version of `external_call/2`. 137 | 138 | See `ExternalService.call_async_stream/5` for more information. 139 | """ 140 | @callback external_call_async_stream( 141 | Enumerable.t(), 142 | RetryOptions.t() | (async_opts :: list()), 143 | (any() -> ExternalService.retriable_function_result()) 144 | ) :: 145 | Enumerable.t() 146 | 147 | @doc """ 148 | Parallel, streaming version of `external_call/2`. 149 | 150 | See `ExternalService.call_async_stream/5` for more information. 151 | """ 152 | @callback external_call_async_stream( 153 | Enumerable.t(), 154 | RetryOptions.t(), 155 | async_opts :: list(), 156 | (any() -> ExternalService.retriable_function_result()) 157 | ) :: 158 | Enumerable.t() 159 | 160 | defmacro __using__(opts) do 161 | quote do 162 | @behaviour ExternalService.Gateway 163 | 164 | alias ExternalService.RetryOptions 165 | 166 | @opts unquote(opts) 167 | 168 | @doc """ 169 | Returns a child specification to start a gateway under a supervisor. 170 | """ 171 | def child_spec(opts) do 172 | %{id: __MODULE__, type: :worker, start: {__MODULE__, :start_link, [opts]}} 173 | end 174 | 175 | @doc """ 176 | Starts a gateway linked to the current process. 177 | """ 178 | def start_link(opts) do 179 | ExternalService.Gateway.start_link(__MODULE__, @opts, opts) 180 | end 181 | 182 | @doc """ 183 | Resets the fuse for the gateway. 184 | 185 | After reset, the fuse will be unbroken with no melts. 186 | """ 187 | def reset_fuse do 188 | config = get_config() 189 | ExternalService.reset_fuse(fuse_name(config)) 190 | end 191 | 192 | @doc """ 193 | Returns the configuration with which the gateway was started. 194 | """ 195 | def gateway_config, do: ExternalService.Gateway.get_config(__MODULE__) 196 | 197 | @impl ExternalService.Gateway 198 | def external_call(retry_opts \\ nil, function) do 199 | config = get_config() 200 | ExternalService.call(fuse_name(config), retry_opts(retry_opts, config), function) 201 | end 202 | 203 | @impl ExternalService.Gateway 204 | def external_call!(retry_opts \\ nil, function) do 205 | config = get_config() 206 | ExternalService.call!(fuse_name(config), retry_opts(retry_opts, config), function) 207 | end 208 | 209 | @impl ExternalService.Gateway 210 | def external_call_async(retry_opts \\ nil, function) do 211 | config = get_config() 212 | ExternalService.call_async(fuse_name(config), retry_opts(retry_opts, config), function) 213 | end 214 | 215 | @impl ExternalService.Gateway 216 | def external_call_async_stream(enumerable, function) do 217 | config = get_config() 218 | ExternalService.call_async_stream(enumerable, fuse_name(config), function) 219 | end 220 | 221 | @impl ExternalService.Gateway 222 | def external_call_async_stream(enumerable, retry_opts_or_async_opts, function) do 223 | config = get_config() 224 | 225 | ExternalService.call_async_stream( 226 | enumerable, 227 | fuse_name(config), 228 | retry_opts_or_async_opts, 229 | function 230 | ) 231 | end 232 | 233 | @impl ExternalService.Gateway 234 | def external_call_async_stream(enumerable, retry_opts, async_opts, function) do 235 | config = get_config() 236 | 237 | ExternalService.call_async_stream( 238 | enumerable, 239 | fuse_name(config), 240 | retry_opts, 241 | async_opts, 242 | function 243 | ) 244 | end 245 | 246 | defp retry_opts(nil, config), do: RetryOptions.new(config[:retry]) 247 | defp retry_opts(%RetryOptions{} = retry_opts, _config), do: retry_opts 248 | defp retry_opts(opts, _config), do: RetryOptions.new(opts) 249 | 250 | defp fuse_name(config), do: get_in(config, [:fuse, :name]) 251 | 252 | defp get_config, do: ExternalService.Gateway.get_config(__MODULE__) 253 | 254 | defp get_config(key, default \\ nil), do: Keyword.get(get_config(), key, default) 255 | end 256 | end 257 | 258 | @doc false 259 | def start_link(module, module_opts, start_opts) 260 | when is_list(module_opts) and is_list(start_opts) do 261 | config = DeepMerge.deep_merge(module_opts, start_opts) 262 | {fuse_name, fuse_opts} = config |> Keyword.get(:fuse, []) |> Keyword.pop(:name, module) 263 | service_start_opts = Keyword.merge(fuse_opts, Keyword.take(config, [:rate_limit])) 264 | :ok = ExternalService.start(fuse_name, service_start_opts) 265 | 266 | Agent.start_link( 267 | fn -> Keyword.put(config, :fuse, Keyword.put(fuse_opts, :name, fuse_name)) end, 268 | name: config_agent(module) 269 | ) 270 | end 271 | 272 | @doc false 273 | def get_config(module), do: Agent.get(config_agent(module), & &1) 274 | 275 | defp config_agent(module), do: Module.concat(module, Config) 276 | end 277 | -------------------------------------------------------------------------------- /lib/external_service/rate_limit.ex: -------------------------------------------------------------------------------- 1 | defmodule ExternalService.RateLimit do 2 | @moduledoc false 3 | 4 | require Logger 5 | 6 | @opaque t :: %__MODULE__{ 7 | fuse: ExternalService.fuse_name(), 8 | bucket: String.t(), 9 | limit: pos_integer, 10 | time_window: pos_integer, 11 | sleep: function 12 | } 13 | 14 | defstruct [:fuse, :bucket, :limit, :time_window, :sleep] 15 | 16 | defmacro is_rate_limit(limit, time_window) do 17 | quote do 18 | is_integer(unquote(limit)) and unquote(limit) > 0 and is_integer(unquote(time_window)) and 19 | unquote(time_window) > 0 20 | end 21 | end 22 | 23 | def new(fuse_name, fuse_opts, opts \\ []) 24 | 25 | def new(_fuse_name, nil, _opts), do: %__MODULE__{} 26 | 27 | def new(fuse_name, %{time_window: window, limit: limit}, opts), 28 | do: new(fuse_name, {limit, window}, opts) 29 | 30 | def new(fuse_name, fuse_opts, opts) when is_list(fuse_opts) do 31 | limit = Keyword.get(fuse_opts, :limit) 32 | time_window = Keyword.get(fuse_opts, :time_window) 33 | new(fuse_name, {limit, time_window}, opts) 34 | end 35 | 36 | def new(fuse_name, {limit, window}, opts) when is_rate_limit(limit, window) do 37 | bucket = bucket_name(fuse_name) 38 | 39 | rate_limit = %__MODULE__{ 40 | fuse: fuse_name, 41 | bucket: bucket, 42 | limit: limit, 43 | time_window: window, 44 | sleep: Keyword.get(opts, :sleep_function, &Process.sleep/1) 45 | } 46 | 47 | rate_limit 48 | end 49 | 50 | def new(_fuse_name, _invalid_args, _options) do 51 | raise(ArgumentError, message: "Invalid rate limit arguments") 52 | end 53 | 54 | @spec call(t, (() -> any), non_neg_integer) :: any 55 | def call(rate_limit, function, sleep_count \\ 0) 56 | 57 | def call( 58 | %__MODULE__{bucket: bucket, limit: limit, time_window: window} = rate_limit, 59 | function, 60 | sleep_count 61 | ) 62 | when is_rate_limit(limit, window) and is_function(function) do 63 | case ExRated.check_rate(bucket, window, limit) do 64 | {:ok, _} -> 65 | function.() 66 | 67 | {:error, _} -> 68 | sleep_time = sleep_time(rate_limit) 69 | log_sleep(rate_limit.fuse, bucket, limit, window, sleep_time, sleep_count) 70 | rate_limit.sleep.(sleep_time) 71 | call(rate_limit, function, sleep_count + 1) 72 | end 73 | end 74 | 75 | def call(%__MODULE__{}, function, _sleep_count) when is_function(function), do: function.() 76 | 77 | @spec bucket_name(atom) :: String.t() 78 | def bucket_name(root_fuse_name), 79 | do: to_string(Module.concat(root_fuse_name, __MODULE__)) 80 | 81 | defp sleep_time(%__MODULE__{limit: limit, time_window: window}), 82 | do: trunc(Float.ceil(window / limit)) 83 | 84 | defp log_sleep(fuse_name, bucket, limit, window, sleep_time, sleep_count) do 85 | if sleep_count == 0 do 86 | Logger.info(fn -> 87 | [ 88 | "[ExternalService] Rate limit exceeded for service ", 89 | inspect(fuse_name), 90 | "; sleeping for ", 91 | inspect(sleep_time), 92 | " milliseconds." 93 | ] 94 | end) 95 | 96 | Logger.debug(fn -> 97 | [ 98 | "[ExternalService] ExRated bucket info: ", 99 | inspect(ExRated.inspect_bucket(bucket, window, limit)) 100 | ] 101 | end) 102 | end 103 | end 104 | end 105 | -------------------------------------------------------------------------------- /lib/external_service/retry_options.ex: -------------------------------------------------------------------------------- 1 | defmodule ExternalService.RetryOptions do 2 | @moduledoc """ 3 | Options used for controlling retry logic. 4 | See the [retry docs](https://hexdocs.pm/retry/Retry.html) for information about the available 5 | retry options. 6 | """ 7 | 8 | @typedoc """ 9 | A tuple describing the backoff strategy for increasing delay between retries. 10 | 11 | The first element of the tuple must be one of the atoms `:exponential` or `:linear`. 12 | In both cases, the second element of the tuple is an integer representing the initial delay 13 | between retries, in milliseconds. 14 | For linear delay, there is also a third element in the tuple, which is a number representing 15 | the factor that the initial delay will be multiplied by on each successive retry. 16 | """ 17 | @type backoff :: 18 | {:exponential, initial_delay :: pos_integer()} 19 | | {:linear, initial_delay :: pos_integer(), factor :: pos_integer()} 20 | 21 | @typedoc """ 22 | Struct representing the retry options to apply to calls to external services. 23 | 24 | * `backoff`: tuple describing the backoff strategy (see `t:backoff/0`) 25 | * `randomize`: boolean indicating whether or not delays between retries should be randomized 26 | * `expiry`: limit total length of time to allow for retries to the specified time budget 27 | * milliseconds 28 | * `cap`: limit maximum amount of time between retries to the specified number of milliseconds 29 | * `rescue_only`: retry only on exceptions matching one of the list of provided exception types, 30 | (defaults to `[RuntimeError]`) 31 | """ 32 | @type t :: %__MODULE__{ 33 | backoff: backoff(), 34 | randomize: boolean(), 35 | expiry: pos_integer() | nil, 36 | cap: pos_integer() | nil, 37 | rescue_only: list(module()) 38 | } 39 | 40 | defstruct backoff: {:exponential, 10}, 41 | randomize: false, 42 | expiry: nil, 43 | cap: nil, 44 | rescue_only: [RuntimeError] 45 | 46 | def new(opts) do 47 | struct(__MODULE__, opts) 48 | end 49 | end 50 | -------------------------------------------------------------------------------- /mix.exs: -------------------------------------------------------------------------------- 1 | defmodule ExternalService.Mixfile do 2 | use Mix.Project 3 | 4 | def project do 5 | [ 6 | app: :external_service, 7 | version: "1.1.4", 8 | description: 9 | "Elixir library for safely using any external service or API using automatic retry with rate limiting and circuit breakers. Calls to external services can be synchronous, asynchronous background tasks, or multiple calls can be made in parallel for MapReduce style processing.", 10 | source_url: "https://github.com/jvoegele/external_service", 11 | elixir: "~> 1.4", 12 | start_permanent: Mix.env() == :prod, 13 | package: package(), 14 | docs: docs(), 15 | deps: deps() 16 | ] 17 | end 18 | 19 | # Run "mix help compile.app" to learn about applications. 20 | def application do 21 | [ 22 | extra_applications: [:logger] 23 | # mod: {ExternalService.Application, []} 24 | ] 25 | end 26 | 27 | # Run "mix help deps" to learn about dependencies. 28 | defp deps do 29 | [ 30 | {:fuse, "~> 2.5"}, 31 | {:retry, "~> 0.18.0"}, 32 | {:ex_rated, "~> 2.1"}, 33 | {:deep_merge, "~> 1.0"}, 34 | {:ex_doc, "~> 0.29.4", only: :dev, runtime: false}, 35 | {:dialyxir, "~> 1.3", only: [:dev, :test], runtime: false}, 36 | {:credo, "~> 1.7", only: [:dev, :test], runtime: false} 37 | ] 38 | end 39 | 40 | defp package do 41 | # These are the default files included in the package 42 | [ 43 | name: :external_service, 44 | files: ["lib", "mix.exs", "README*", "LICENSE*"], 45 | maintainers: ["Jason Voegele"], 46 | licenses: ["Apache 2.0"], 47 | links: %{"GitHub" => "https://github.com/jvoegele/external_service"} 48 | ] 49 | end 50 | 51 | defp docs do 52 | [ 53 | extras: ["README.md"], 54 | main: "readme" 55 | ] 56 | end 57 | end 58 | -------------------------------------------------------------------------------- /mix.lock: -------------------------------------------------------------------------------- 1 | %{ 2 | "bunt": {:hex, :bunt, "1.0.0", "081c2c665f086849e6d57900292b3a161727ab40431219529f13c4ddcf3e7a44", [:mix], [], "hexpm", "dc5f86aa08a5f6fa6b8096f0735c4e76d54ae5c9fa2c143e5a1fc7c1cd9bb6b5"}, 3 | "credo": {:hex, :credo, "1.7.2", "fdee3a7cb553d8f2e773569181f0a4a2bb7d192e27e325404cc31b354f59d68c", [:mix], [{:bunt, "~> 0.2.1 or ~> 1.0", [hex: :bunt, repo: "hexpm", optional: false]}, {:file_system, "~> 0.2 or ~> 1.0", [hex: :file_system, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "dd15d6fbc280f6cf9b269f41df4e4992dee6615939653b164ef951f60afcb68e"}, 4 | "deep_merge": {:hex, :deep_merge, "1.0.0", "b4aa1a0d1acac393bdf38b2291af38cb1d4a52806cf7a4906f718e1feb5ee961", [:mix], [], "hexpm", "ce708e5f094b9cd4e8f2be4f00d2f4250c4095be93f8cd6d018c753894885430"}, 5 | "dialyxir": {:hex, :dialyxir, "1.4.3", "edd0124f358f0b9e95bfe53a9fcf806d615d8f838e2202a9f430d59566b6b53b", [:mix], [{:erlex, ">= 0.2.6", [hex: :erlex, repo: "hexpm", optional: false]}], "hexpm", "bf2cfb75cd5c5006bec30141b131663299c661a864ec7fbbc72dfa557487a986"}, 6 | "earmark": {:hex, :earmark, "1.4.4", "4821b8d05cda507189d51f2caeef370cf1e18ca5d7dfb7d31e9cafe6688106a4", [:mix], [], "hexpm", "1f93aba7340574847c0f609da787f0d79efcab51b044bb6e242cae5aca9d264d"}, 7 | "earmark_parser": {:hex, :earmark_parser, "1.4.39", "424642f8335b05bb9eb611aa1564c148a8ee35c9c8a8bba6e129d51a3e3c6769", [:mix], [], "hexpm", "06553a88d1f1846da9ef066b87b57c6f605552cfbe40d20bd8d59cc6bde41944"}, 8 | "erlex": {:hex, :erlex, "0.2.6", "c7987d15e899c7a2f34f5420d2a2ea0d659682c06ac607572df55a43753aa12e", [:mix], [], "hexpm", "2ed2e25711feb44d52b17d2780eabf998452f6efda104877a3881c2f8c0c0c75"}, 9 | "ex2ms": {:hex, :ex2ms, "1.6.1", "66d472eb14da43087c156e0396bac3cc7176b4f24590a251db53f84e9a0f5f72", [:mix], [], "hexpm", "a7192899d84af03823a8ec2f306fa858cbcce2c2e7fd0f1c49e05168fb9c740e"}, 10 | "ex_doc": {:hex, :ex_doc, "0.29.4", "6257ecbb20c7396b1fe5accd55b7b0d23f44b6aa18017b415cb4c2b91d997729", [:mix], [{:earmark_parser, "~> 1.4.31", [hex: :earmark_parser, repo: "hexpm", optional: false]}, {:makeup_elixir, "~> 0.14", [hex: :makeup_elixir, repo: "hexpm", optional: false]}, {:makeup_erlang, "~> 0.1", [hex: :makeup_erlang, repo: "hexpm", optional: false]}], "hexpm", "2c6699a737ae46cb61e4ed012af931b57b699643b24dabe2400a8168414bc4f5"}, 11 | "ex_rated": {:hex, :ex_rated, "2.1.0", "d40e6fe35097b10222df2db7bb5dd801d57211bac65f29063de5f201c2a6aebc", [:mix], [{:ex2ms, "~> 1.5", [hex: :ex2ms, repo: "hexpm", optional: false]}], "hexpm", "936c155337253ed6474f06d941999dd3a9cf0fe767ec99a59f2d2989dc2cc13f"}, 12 | "file_system": {:hex, :file_system, "1.0.0", "b689cc7dcee665f774de94b5a832e578bd7963c8e637ef940cd44327db7de2cd", [:mix], [], "hexpm", "6752092d66aec5a10e662aefeed8ddb9531d79db0bc145bb8c40325ca1d8536d"}, 13 | "fuse": {:hex, :fuse, "2.5.0", "71afa90be21da4e64f94abba9d36472faa2d799c67fedc3bd1752a88ea4c4753", [:rebar3], [], "hexpm", "7f52a1c84571731ad3c91d569e03131cc220ebaa7e2a11034405f0bac46a4fef"}, 14 | "jason": {:hex, :jason, "1.4.1", "af1504e35f629ddcdd6addb3513c3853991f694921b1b9368b0bd32beb9f1b63", [:mix], [{:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "fbb01ecdfd565b56261302f7e1fcc27c4fb8f32d56eab74db621fc154604a7a1"}, 15 | "makeup": {:hex, :makeup, "1.1.1", "fa0bc768698053b2b3869fa8a62616501ff9d11a562f3ce39580d60860c3a55e", [:mix], [{:nimble_parsec, "~> 1.2.2 or ~> 1.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "5dc62fbdd0de44de194898b6710692490be74baa02d9d108bc29f007783b0b48"}, 16 | "makeup_elixir": {:hex, :makeup_elixir, "0.16.1", "cc9e3ca312f1cfeccc572b37a09980287e243648108384b97ff2b76e505c3555", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}, {:nimble_parsec, "~> 1.2.3 or ~> 1.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "e127a341ad1b209bd80f7bd1620a15693a9908ed780c3b763bccf7d200c767c6"}, 17 | "makeup_erlang": {:hex, :makeup_erlang, "0.1.3", "d684f4bac8690e70b06eb52dad65d26de2eefa44cd19d64a8095e1417df7c8fd", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm", "b78dc853d2e670ff6390b605d807263bf606da3c82be37f9d7f68635bd886fc9"}, 18 | "nimble_parsec": {:hex, :nimble_parsec, "1.4.0", "51f9b613ea62cfa97b25ccc2c1b4216e81df970acd8e16e8d1bdc58fef21370d", [:mix], [], "hexpm", "9c565862810fb383e9838c1dd2d7d2c437b3d13b267414ba6af33e50d2d1cf28"}, 19 | "retry": {:hex, :retry, "0.18.0", "dc58ebe22c95aa00bc2459f9e0c5400e6005541cf8539925af0aa027dc860543", [:mix], [], "hexpm", "9483959cc7bf69c9e576d9dfb2b678b71c045d3e6f39ab7c9aa1489df4492d73"}, 20 | } 21 | -------------------------------------------------------------------------------- /test/external_service/gateway_test.exs: -------------------------------------------------------------------------------- 1 | defmodule ExternalService.GatewayTest do 2 | use ExUnit.Case 3 | 4 | defmodule TestGateway do 5 | use ExternalService.Gateway, 6 | fuse: [ 7 | name: SomeService, 8 | strategy: {:standard, 5, 10_000}, 9 | refresh: 5_000 10 | ], 11 | rate_limit: {5, :timer.seconds(1)}, 12 | retry: [ 13 | backoff: {:linear, 100, 1}, 14 | expiry: 5_000 15 | ] 16 | 17 | def get_foo(foo_id) do 18 | external_call(fn -> 19 | %{foo: foo_id} 20 | end) 21 | end 22 | end 23 | 24 | describe "child_spec" do 25 | test "generates a child spec for starting under a supervisor" do 26 | assert %{id: TestGateway, type: :worker, start: start_tuple} = 27 | TestGateway.child_spec(foo: :bar) 28 | 29 | assert start_tuple == {TestGateway, :start_link, [[foo: :bar]]} 30 | end 31 | end 32 | 33 | describe "start_link" do 34 | test "starts gateway process with configuration" do 35 | {:ok, pid} = TestGateway.start_link([]) 36 | assert is_pid(pid) 37 | 38 | assert TestGateway.gateway_config() == [ 39 | fuse: [ 40 | name: SomeService, 41 | strategy: {:standard, 5, 10_000}, 42 | refresh: 5_000 43 | ], 44 | rate_limit: {5, :timer.seconds(1)}, 45 | retry: [ 46 | backoff: {:linear, 100, 1}, 47 | expiry: 5_000 48 | ] 49 | ] 50 | end 51 | 52 | test "merges gateway configuration with start options" do 53 | {:ok, pid} = TestGateway.start_link( 54 | fuse: [ 55 | refresh: 999 56 | ], 57 | rate_limit: {9, 999}, 58 | retry: [ 59 | expiry: 999 60 | ] 61 | ) 62 | assert is_pid(pid) 63 | 64 | assert TestGateway.gateway_config() == [ 65 | fuse: [ 66 | name: SomeService, 67 | strategy: {:standard, 5, 10_000}, 68 | refresh: 999 69 | ], 70 | rate_limit: {9, 999}, 71 | retry: [ 72 | backoff: {:linear, 100, 1}, 73 | expiry: 999 74 | ] 75 | ] 76 | end 77 | 78 | test "can be restarted by supervisor" do 79 | {:ok, pid} = start_supervised({TestGateway, [rate_limit: {9, 999}]}) 80 | assert Process.whereis(Module.concat(TestGateway, Config)) == pid 81 | assert TestGateway.gateway_config()[:rate_limit] == {9, 999} 82 | 83 | Process.exit(pid, :testing_restart) 84 | refute Process.alive?(pid) 85 | refute Process.whereis(Module.concat(TestGateway, Config)) == pid 86 | 87 | # Give the supervisor a little time to restart the process 88 | Process.sleep(50) 89 | assert TestGateway.gateway_config()[:rate_limit] == {9, 999} 90 | end 91 | end 92 | end 93 | -------------------------------------------------------------------------------- /test/external_service/rate_limit_test.exs: -------------------------------------------------------------------------------- 1 | defmodule ExternalService.RateLimitTest do 2 | use ExUnit.Case 3 | alias ExternalService.RateLimit 4 | 5 | @moduletag capture_log: true 6 | 7 | describe "new/2" do 8 | test "calling with nil makes an empty RateLimit struct" do 9 | assert RateLimit.new(:foo, nil) == %RateLimit{} 10 | end 11 | 12 | test "with map" do 13 | rate_limit = RateLimit.new(:foo, %{time_window: 100, limit: 10}) 14 | assert %RateLimit{limit: 10, time_window: 100} = rate_limit 15 | end 16 | 17 | test "with keyword list" do 18 | rate_limit = RateLimit.new(:foo, time_window: 100, limit: 10) 19 | assert %RateLimit{limit: 10, time_window: 100} = rate_limit 20 | end 21 | 22 | test "with tuple" do 23 | rate_limit = RateLimit.new(:foo, {10, 100}) 24 | assert %RateLimit{limit: 10, time_window: 100} = rate_limit 25 | end 26 | 27 | test "enforces valid arguments" do 28 | assert_raise(ArgumentError, fn -> RateLimit.new(:foo, {0, 100}) end) 29 | assert_raise(ArgumentError, fn -> RateLimit.new(:foo, {10, 0}) end) 30 | end 31 | end 32 | 33 | describe "call/2" do 34 | setup [:init_sleep_spy] 35 | 36 | test "with no rate limit", %{sleep_spy: spy} do 37 | rate_limit = RateLimit.new(:unlimited, nil) 38 | result = RateLimit.call(%{rate_limit | sleep: spy}, fn -> 42 end) 39 | assert result == 42 40 | assert get_sleep_calls() == [] 41 | end 42 | 43 | test "sleeps for time window when limit exceeded", %{sleep_spy: spy} do 44 | rate_limit = 45 | :limited 46 | |> RateLimit.new({2, 50}) 47 | |> Map.put(:sleep, spy) 48 | 49 | results = Enum.map(1..5, fn x -> RateLimit.call(rate_limit, fn -> x end) end) 50 | assert results == [1, 2, 3, 4, 5] 51 | 52 | # Sleeps are somewhat non-deterministic, but we should get 2, 3, or 4 of them in this case. 53 | assert get_sleep_calls() in Enum.map([2, 3, 4], &List.duplicate(25, &1)) 54 | end 55 | 56 | defp init_sleep_spy(_context) do 57 | {:ok, _pid} = Agent.start_link(fn -> [] end, name: :sleep_spy) 58 | 59 | sleep_spy = fn sleep_time -> 60 | Agent.update(:sleep_spy, &[sleep_time | &1]) 61 | Process.sleep(sleep_time) 62 | end 63 | 64 | [sleep_spy: sleep_spy] 65 | end 66 | 67 | defp get_sleep_calls, do: Enum.reverse(Agent.get(:sleep_spy, & &1)) 68 | end 69 | end 70 | -------------------------------------------------------------------------------- /test/external_service_test.exs: -------------------------------------------------------------------------------- 1 | defmodule ExternalServiceTest do 2 | use ExUnit.Case 3 | alias ExternalService 4 | alias ExternalService.RetryOptions 5 | 6 | @moduletag capture_log: true 7 | 8 | @fuse_name :"test-fuse" 9 | 10 | @retry_opts %RetryOptions{ 11 | backoff: {:linear, 0, 1} 12 | } 13 | 14 | @expiring_retry_options %RetryOptions{ 15 | backoff: {:linear, 1, 1}, 16 | expiry: 1 17 | } 18 | 19 | describe "uninitialized fuse" do 20 | test "call returns :fuse_not_found error" do 21 | result = ExternalService.call(:testing_nonexistent_fuse, fn -> :noop end) 22 | assert result == {:error, {:fuse_not_found, :testing_nonexistent_fuse}} 23 | end 24 | 25 | test "call! raises FuseNotFoundError" do 26 | assert_raise ExternalService.FuseNotFoundError, fn -> 27 | ExternalService.call!(:testing_nonexistent_fuse, fn -> :noop end) 28 | end 29 | end 30 | end 31 | 32 | describe "start" do 33 | test "installs a fuse" do 34 | ExternalService.start(@fuse_name) 35 | assert :fuse.ask(@fuse_name, :sync) == :ok 36 | end 37 | end 38 | 39 | describe "stop" do 40 | test "removes a fuse" do 41 | ExternalService.stop(@fuse_name) 42 | assert :fuse.ask(@fuse_name, :sync) == {:error, :not_found} 43 | end 44 | end 45 | 46 | describe "call" do 47 | @fuse_retries 5 48 | 49 | setup do 50 | Process.put(@fuse_name, 0) 51 | ExternalService.start(@fuse_name, fuse_strategy: {:standard, @fuse_retries, 10_000}) 52 | end 53 | 54 | test "calls function once when successful" do 55 | ExternalService.call(@fuse_name, @retry_opts, fn -> 56 | Process.put(@fuse_name, Process.get(@fuse_name) + 1) 57 | :ok 58 | end) 59 | 60 | assert Process.get(@fuse_name) == 1 61 | end 62 | 63 | test "calls function again when it returns retry" do 64 | ExternalService.call(@fuse_name, @retry_opts, fn -> 65 | Process.put(@fuse_name, Process.get(@fuse_name) + 1) 66 | :retry 67 | end) 68 | 69 | assert Process.get(@fuse_name) == @fuse_retries + 1 70 | end 71 | 72 | test "stops retrying on success" do 73 | ExternalService.call(@fuse_name, @retry_opts, fn -> 74 | Process.put(@fuse_name, Process.get(@fuse_name) + 1) 75 | 76 | case Process.get(@fuse_name) do 77 | 1 -> :retry 78 | _ -> :ok 79 | end 80 | end) 81 | 82 | assert Process.get(@fuse_name) == 2 83 | end 84 | 85 | test "calls function again when it raises a RuntimeError" do 86 | ExternalService.call(@fuse_name, @retry_opts, fn -> 87 | Process.put(@fuse_name, Process.get(@fuse_name) + 1) 88 | raise "KABOOM!" 89 | end) 90 | 91 | assert Process.get(@fuse_name) == @fuse_retries + 1 92 | end 93 | 94 | test "calls function again when it raises an exception in the rescue_only list" do 95 | retry_opts = %{@retry_opts | rescue_only: [ArithmeticError, ArgumentError]} 96 | 97 | ExternalService.call(@fuse_name, retry_opts, fn -> 98 | Process.put(@fuse_name, Process.get(@fuse_name) + 1) 99 | raise ArgumentError, message: "KABOOM!" 100 | end) 101 | 102 | assert Process.get(@fuse_name) == @fuse_retries + 1 103 | end 104 | 105 | test "does not call function again when it raises an exception not in the rescue_only list" do 106 | retry_opts = %{@retry_opts | rescue_only: [SystemLimitError, File.Error]} 107 | 108 | assert_raise(RuntimeError, fn -> 109 | ExternalService.call(@fuse_name, retry_opts, fn -> 110 | Process.put(@fuse_name, Process.get(@fuse_name) + 1) 111 | raise "KABOOM!" 112 | end) 113 | end) 114 | 115 | assert Process.get(@fuse_name) == 1 116 | end 117 | 118 | test "returns fuse_blown when the fuse is blown by retries" do 119 | res = 120 | ExternalService.call(@fuse_name, @retry_opts, fn -> 121 | :retry 122 | end) 123 | 124 | assert res == {:error, {:fuse_blown, @fuse_name}} 125 | end 126 | 127 | test "returns fuse_blown when the fuse is blown by exceptions" do 128 | res = 129 | ExternalService.call(@fuse_name, @retry_opts, fn -> 130 | raise "KABOOM!" 131 | end) 132 | 133 | assert res == {:error, {:fuse_blown, @fuse_name}} 134 | end 135 | 136 | test "returns :error when retries are exhausted with :retry" do 137 | res = 138 | ExternalService.call(@fuse_name, @expiring_retry_options, fn -> 139 | :retry 140 | end) 141 | 142 | assert res == {:error, {:retries_exhausted, :reason_unknown}} 143 | end 144 | 145 | test "returns :error when retries are exhausted with a reason" do 146 | res = 147 | ExternalService.call(@fuse_name, @expiring_retry_options, fn -> 148 | {:retry, "reason"} 149 | end) 150 | 151 | assert res == {:error, {:retries_exhausted, "reason"}} 152 | end 153 | 154 | test "propagates original exception when retries are exhausted by an exception" do 155 | assert_raise RuntimeError, "KABOOM!", fn -> 156 | ExternalService.call(@fuse_name, @expiring_retry_options, fn -> 157 | raise "KABOOM!" 158 | end) 159 | end 160 | end 161 | 162 | test "returns original result value when given a function that is not retriable" do 163 | res = 164 | ExternalService.call(@fuse_name, @retry_opts, fn -> 165 | {:error, "reason"} 166 | end) 167 | 168 | assert res == {:error, "reason"} 169 | end 170 | 171 | test "calls sleep function when rate limit is reached" do 172 | fuse_name = "sleep test fuse" 173 | 174 | Process.put(:call_count, 0) 175 | 176 | sleep = fn _ -> Process.put(:sleep_fired, true) end 177 | 178 | ExternalService.start(fuse_name, rate_limit: {5, 10}, sleep_function: sleep) 179 | 180 | for i <- 1..10 do 181 | ExternalService.call(fuse_name, fn -> 182 | unless Process.get(:sleep_fired) do 183 | Process.put(:call_count, Process.get(:call_count) + 1) 184 | end 185 | 186 | i 187 | end) 188 | end 189 | 190 | assert Process.get(:sleep_fired) == true 191 | assert Process.get(:call_count) == 5 192 | end 193 | end 194 | 195 | describe "call!" do 196 | @fuse_retries 5 197 | 198 | setup do 199 | Process.put(@fuse_name, 0) 200 | ExternalService.start(@fuse_name, fuse_strategy: {:standard, @fuse_retries, 10_000}) 201 | end 202 | 203 | test "calls function once when successful" do 204 | ExternalService.call!(@fuse_name, @retry_opts, fn -> 205 | Process.put(@fuse_name, Process.get(@fuse_name) + 1) 206 | :ok 207 | end) 208 | 209 | assert Process.get(@fuse_name) == 1 210 | end 211 | 212 | test "calls function again when it returns retry" do 213 | try do 214 | ExternalService.call!(@fuse_name, @retry_opts, fn -> 215 | Process.put(@fuse_name, Process.get(@fuse_name) + 1) 216 | :retry 217 | end) 218 | rescue 219 | ExternalService.FuseBlownError -> :ok 220 | end 221 | 222 | assert Process.get(@fuse_name) == @fuse_retries + 1 223 | end 224 | 225 | test "stops retrying on success" do 226 | ExternalService.call!(@fuse_name, @retry_opts, fn -> 227 | Process.put(@fuse_name, Process.get(@fuse_name) + 1) 228 | 229 | case Process.get(@fuse_name) do 230 | 1 -> :retry 231 | _ -> :ok 232 | end 233 | end) 234 | 235 | assert Process.get(@fuse_name) == 2 236 | end 237 | 238 | test "calls function again when it raises an exception" do 239 | try do 240 | ExternalService.call!(@fuse_name, @retry_opts, fn -> 241 | Process.put(@fuse_name, Process.get(@fuse_name) + 1) 242 | raise "KABOOM!" 243 | end) 244 | rescue 245 | ExternalService.FuseBlownError -> :ok 246 | end 247 | 248 | assert Process.get(@fuse_name) == @fuse_retries + 1 249 | end 250 | 251 | test "raises FuseBlownError when the fuse is blown by retries" do 252 | assert_raise ExternalService.FuseBlownError, inspect(@fuse_name), fn -> 253 | ExternalService.call!(@fuse_name, @retry_opts, fn -> :retry end) 254 | end 255 | end 256 | 257 | test "raises FuseBlownError when the fuse is blown by exceptions" do 258 | assert_raise ExternalService.FuseBlownError, inspect(@fuse_name), fn -> 259 | ExternalService.call!(@fuse_name, @retry_opts, fn -> raise "KABOOM!" end) 260 | end 261 | end 262 | 263 | test "raises RetriesExhaustedError when retries are exhausted with :retry" do 264 | assert_raise ExternalService.RetriesExhaustedError, fn -> 265 | ExternalService.call!(@fuse_name, @expiring_retry_options, fn -> :retry end) 266 | end 267 | end 268 | 269 | test "raises RetriesExhaustedError when retries are exhausted with a reason" do 270 | assert_raise ExternalService.RetriesExhaustedError, fn -> 271 | ExternalService.call!(@fuse_name, @expiring_retry_options, fn -> {:retry, "reason"} end) 272 | end 273 | end 274 | 275 | test "propagates original exception when retries are exhausted by an exception" do 276 | assert_raise RuntimeError, "KABOOM!", fn -> 277 | ExternalService.call!(@fuse_name, @expiring_retry_options, fn -> raise "KABOOM!" end) 278 | end 279 | end 280 | 281 | test "returns original result value when given a function that is not retriable" do 282 | res = 283 | ExternalService.call!(@fuse_name, @retry_opts, fn -> 284 | {:error, "reason"} 285 | end) 286 | 287 | assert res == {:error, "reason"} 288 | end 289 | end 290 | 291 | describe "call_async" do 292 | setup do 293 | ExternalService.start(@fuse_name, fuse_strategy: {:standard, @fuse_retries, 10_000}) 294 | end 295 | 296 | test "returns a Task" do 297 | task = ExternalService.call_async(@fuse_name, fn -> :ok end) 298 | assert Task.await(task) == :ok 299 | end 300 | end 301 | 302 | describe "call_async_stream" do 303 | setup do 304 | ExternalService.start(@fuse_name, fuse_strategy: {:standard, @fuse_retries, 10_000}) 305 | end 306 | 307 | def function(:raise), do: raise("KABOOM!") 308 | def function(arg), do: arg 309 | 310 | @enumerable [42, :ok, :retry, :error, {:error, :reason}, :raise] 311 | 312 | test "with no options" do 313 | results = 314 | @enumerable 315 | |> ExternalService.call_async_stream(@fuse_name, &function/1) 316 | |> Enum.to_list() 317 | 318 | assert [ 319 | {:ok, _}, 320 | {:ok, _}, 321 | {:ok, {:error, {:fuse_blown, :"test-fuse"}}}, 322 | {:ok, _}, 323 | {:ok, _}, 324 | {:ok, {:error, {:fuse_blown, :"test-fuse"}}} 325 | ] = results 326 | end 327 | 328 | test "with retry options" do 329 | results = 330 | @enumerable 331 | |> ExternalService.call_async_stream(@fuse_name, @retry_opts, &function/1) 332 | |> Enum.to_list() 333 | 334 | assert [ 335 | {:ok, _}, 336 | {:ok, _}, 337 | {:ok, {:error, {:fuse_blown, :"test-fuse"}}}, 338 | {:ok, _}, 339 | {:ok, _}, 340 | {:ok, {:error, {:fuse_blown, :"test-fuse"}}} 341 | ] = results 342 | end 343 | 344 | @async_opts [max_concurrency: 100, timeout: 10_000] 345 | 346 | test "with async options" do 347 | results = 348 | @enumerable 349 | |> ExternalService.call_async_stream(@fuse_name, @async_opts, &function/1) 350 | |> Enum.to_list() 351 | 352 | assert [ 353 | {:ok, _}, 354 | {:ok, _}, 355 | {:ok, {:error, {:fuse_blown, :"test-fuse"}}}, 356 | {:ok, _}, 357 | {:ok, _}, 358 | {:ok, {:error, {:fuse_blown, :"test-fuse"}}} 359 | ] = results 360 | end 361 | 362 | test "with retry and async options" do 363 | results = 364 | @enumerable 365 | |> ExternalService.call_async_stream(@fuse_name, @retry_opts, @async_opts, &function/1) 366 | |> Enum.to_list() 367 | 368 | assert [ 369 | {:ok, _}, 370 | {:ok, _}, 371 | {:ok, {:error, {:fuse_blown, :"test-fuse"}}}, 372 | {:ok, _}, 373 | {:ok, _}, 374 | {:ok, {:error, {:fuse_blown, :"test-fuse"}}} 375 | ] = results 376 | end 377 | end 378 | end 379 | -------------------------------------------------------------------------------- /test/test_helper.exs: -------------------------------------------------------------------------------- 1 | ExUnit.start() 2 | --------------------------------------------------------------------------------