{"id":13995651,"url":"https://github.com/Kitura/CircuitBreaker","last_synced_at":"2025-07-22T22:31:40.679Z","repository":{"id":56645614,"uuid":"74045030","full_name":"Kitura/CircuitBreaker","owner":"Kitura","description":"A Swift Circuit Breaker library – Improves application stability and reliability.","archived":false,"fork":false,"pushed_at":"2022-06-30T23:04:18.000Z","size":1319,"stargazers_count":45,"open_issues_count":2,"forks_count":12,"subscribers_count":28,"default_branch":"master","last_synced_at":"2024-04-20T17:43:47.980Z","etag":null,"topics":["bulkhead","circuit-breaker","swift"],"latest_commit_sha":null,"homepage":"","language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Kitura.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-11-17T16:20:47.000Z","updated_at":"2024-01-15T20:35:34.000Z","dependencies_parsed_at":"2022-08-15T22:31:28.735Z","dependency_job_id":null,"html_url":"https://github.com/Kitura/CircuitBreaker","commit_stats":null,"previous_names":["ibm-swift/circuitbreaker"],"tags_count":17,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Kitura%2FCircuitBreaker","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Kitura%2FCircuitBreaker/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Kitura%2FCircuitBreaker/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Kitura%2FCircuitBreaker/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Kitura","download_url":"https://codeload.github.com/Kitura/CircuitBreaker/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":227190271,"owners_count":17745238,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bulkhead","circuit-breaker","swift"],"created_at":"2024-08-09T14:03:31.945Z","updated_at":"2024-11-29T18:30:46.978Z","avatar_url":"https://github.com/Kitura.png","language":"Swift","funding_links":[],"categories":["Swift"],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\n    \u003ca href=\"http://kitura.io/\"\u003e\n        \u003cimg src=\"https://raw.githubusercontent.com/Kitura/Kitura/master/Sources/Kitura/resources/kitura-bird.svg?sanitize=true\" height=\"100\" alt=\"Kitura\"\u003e\n    \u003c/a\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n    \u003ca href=\"https://kitura.github.io/CircuitBreaker/index.html\"\u003e\n    \u003cimg src=\"https://img.shields.io/badge/apidoc-CircuitBreaker-1FBCE4.svg?style=flat\" alt=\"APIDoc\"\u003e\n    \u003c/a\u003e\n    \u003ca href=\"https://travis-ci.org/Kitura/CircuitBreaker\"\u003e\n    \u003cimg src=\"https://travis-ci.org/Kitura/CircuitBreaker.svg?branch=master\" alt=\"Build Status - Master\"\u003e\n    \u003c/a\u003e\n    \u003cimg src=\"https://img.shields.io/badge/os-macOS-green.svg?style=flat\" alt=\"macOS\"\u003e\n    \u003cimg src=\"https://img.shields.io/badge/os-linux-green.svg?style=flat\" alt=\"Linux\"\u003e\n    \u003cimg src=\"https://img.shields.io/badge/license-Apache2-blue.svg?style=flat\" alt=\"Apache 2\"\u003e\n    \u003ca href=\"http://swift-at-ibm-slack.mybluemix.net/\"\u003e\n    \u003cimg src=\"http://swift-at-ibm-slack.mybluemix.net/badge.svg\" alt=\"Slack Status\"\u003e\n    \u003c/a\u003e\n\u003c/p\u003e\n\n# CircuitBreaker\nThe Circuit Breaker design pattern is used to increase application stability, improve response times and prevent the application from making constant failing requests. This library provides the tools needed to bring Circuit Breaker logic to your Swift applications.\n\n![Circuit Breaker Diagram](resources/circuitBreakerDiagram.png)\n\n## Swift version\nThe latest version of CircuitBreaker works with the `5.1` and newer version of the Swift binaries. You can download this version of the Swift binaries by following this [link](https://swift.org/download/#releases).\n\n## Getting Started\n\nAdd `CircuitBreaker` to the dependencies within your application's `Package.swift` file. Substitute `\"x.x.x\"` with the latest `CircuitBreaker` [release](https://github.com/Kitura/CircuitBreaker/releases).\n\n```swift\n.package(url: \"https://github.com/Kitura/CircuitBreaker.git\", from: \"x.x.x\")\n```\nAdd `CircuitBreaker` to your target's dependencies:\n\n```Swift\n.target(name: \"example\", dependencies: [\"CircuitBreaker\"]),\n```\n\nImport the package inside your application:\n\n```swift\nimport CircuitBreaker\n```\n\n### Usage\n\nThe CircuitBreaker state is based on timeouts and user defined failures (quite useful when the function you are circuit breaking makes an asynchronous call). To use the CircuitBreaker in your application code you need to do the following:\n\n- Define a fallback function with the signature `(BreakerError, (fallbackArg1, fallbackArg2, ...)) -\u003e Void`:\n\n```swift\nfunc myFallback(err: BreakerError, msg: String) {\n    // The fallback will be called if one of the below occurs:\n    //  1. The request does not return before the specified timeout\n    //  2. CircuitBreaker is currently in Open state and set to fail fast.\n    //  3. There was an error in the user's called context function (networking error, etc.)\n    Log.verbose(\"Error: \\(err)\")\n    Log.verbose(\"Message: \\(msg)\")\n}\n```\n\n- Extend BreakerError by defining your own error handling to be used in your context function:\n\n```swift\nextension BreakerError {\n    public static let encodingURLError = BreakerError(reason: \"URL could not be created\")\n    public static let networkingError = BreakerError(reason: \"There was an error, while sending the request\")\n    public static let jsonDecodingError = BreakerError(reason: \"Could not decode result into JSON\")\n}\n```\n\n- Create a context function for the logic you intend to circuit break (this allows you to alert the CircuitBreaker of a failure or a success). A context function receives an `Invocation` object as its parameter. An instance of the `Invocation` class states:\n    - The parameter types that must be passed to the context function.\n    - The return type from the execution of the context function.\n    - The parameter type used as the second argument for the fallback closure.\n\n```swift\nfunc myContextFunction(invocation: Invocation\u003c(String), String\u003e) {\n  let requestParam = invocation.commandArgs\n  // Create HTTP request\n  guard let url = URL(string: \"http://myserver.net/path/\\(requestParam)\") else {\n    // Something went wrong\n\n    invocation.notifyFailure(error: .encodingURLError)\n    return\n  }\n\n  var req = URLRequest(url: url)\n  req.httpMethod = \"GET\"\n  let session = URLSession.shared\n\n  // Perform the request\n  session.dataTask(with: req) { result, res, err in\n    guard let result = result else {\n      // Failed getting a result from the server\n\n      invocation.notifyFailure(error: .networkingError)\n      return\n    }\n\n    // Convert results to a JSON object\n    guard let json = (try? JSONSerialization.jsonObject(with: result, options: [])) as? [String: Any] else {\n      invocation.notifyFailure(error: .jsonDecodingError)\n      return\n    }\n    // Process JSON data\n\n    invocation.notifySuccess()\n  }.resume()\n}\n```\n\n- Create a CircuitBreaker instance for each context function (e.g. endpoint) you wish to circuit break. The CircuitBreaker instance must specify a name for the circuit breaker, the endpoint to circuit break and the fallback function. Optional configurations include: group, timeout, resetTimeout, maxFailures, rollingWindow and bulkhead, for further details about these configuration options see the [API reference](https://kitura.github.io/CircuitBreaker/index.html).\n\n```swift\nlet breaker = CircuitBreaker(name: \"Circuit1\", command: myContextFunction, fallback: myFallback)\n```\n\n- Invoke the call to the endpoint by calling the CircuitBreaker `run()` method. You should pass the corresponding arguments for the context command and fallback closures. In this sample, `myContextFunction` takes a string as its parameter while `myFallback` takes a string as its second parameter:\n\n```swift\nlet requestParam: String = \"myRequestParams\"\nbreaker.run(commandArgs: requestParam, fallbackArgs: \"Something went wrong.\")\n```\n\n#### Full Implementation\n\n```swift\nextension BreakerError {\n    public static let encodingURLError = BreakerError(reason: \"URL could not be created\")\n    public static let networkingError = BreakerError(reason: \"There was an error, while sending the request\")\n    public static let jsonDecodingError = BreakerError(reason: \"Could not decode result into JSON\")\n}\n\nfunc myFallback(err: BreakerError, msg: String) {\n    // The fallback will be called if one of the below occurs:\n    //  1. The request does not return before the specified timeout\n    //  2. CircuitBreaker is currently in Open state and set to fail fast.\n    //  3. There was an error in the user's called context function (networking error, etc.)\n    Log.verbose(\"Error: \\(err)\")\n    Log.verbose(\"Message: \\(msg)\")\n}\n\nfunc myContextFunction(invocation: Invocation\u003c(String), String\u003e) {\n  let requestParam = invocation.commandArgs\n  // Create HTTP request\n  guard let url = URL(string: \"http://mysever.net/path/\\(requestParam)\") else {\n    // Something went wrong...\n\n    invocation.notifyFailure(error: .encodingURLError)\n  }\n\n  var req = URLRequest(url: url)\n  req.httpMethod = \"GET\"\n  let session = URLSession.shared\n\n  // Perform Request\n  session.dataTask(with: req) { result, res, err in\n    guard let result = result else {\n      // Failed getting a result from the server\n\n      invocation.notifyFailure(error: .networkingError)\n      return\n    }\n\n    // Convert results to a JSON object\n    guard let json = (try? JSONSerialization.jsonObject(with: result, options: [])) as? [String: Any] else {\n        invocation.notifyFailure(error: .jsonDecodingError)\n        return\n    }\n    // Process JSON data\n\n    invocation.notifySuccess()\n  }.resume()\n}\n\nlet breaker = CircuitBreaker(name: \"Circuit1\", command: myContextFunction, fallback: myFallback)\n\nlet requestParam: String = \"myRequestParams\"\nbreaker.run(commandArgs: requestParam, fallbackArgs: \"Something went wrong.\")\n```\n\n#### Statistics\n\nThe following statistics will be tracked for the CircuitBreaker instance:\n\n##### Tracked Statistics\n * Total Requests\n * Concurrent Requests\n * Rejected Requests\n * Successful Responses\n * Average Execution Response Time\n * Average Total Response Time\n * Failed Responses\n * Total Timeouts\n * Total Latency\n * Total Execution Latency\n * Hystrix Compliant Snapshot\n\nThe example code below shows how to log a snapshot of the statistics and how to create\n a Hystrix compliant snapshot.\n\n```swift\n// Create CircuitBreaker\nlet breaker = CircuitBreaker(name: \"Circuit1\", command: myFunction, fallback: myFallback)\n\n// Invoke breaker call\nbreaker.run(commandArgs: (a: 10, b: 20), fallbackArgs: \"Something went wrong.\")\n\n// Log statistics snapshot\nbreaker.logSnapshot()\n\n// Hystrix compliant snapshot\nlet snapshot = breaker.snapshot\n```\n\n#### Observing statistics\nThe CircuitBreaker library provides an interface for observing new CircuitBreaker instances in order to register and track statistics changes. In the initialization of a CircuitBreaker instance, the linked monitors are notified of its instantiation allowing them to begin tracking the instance's statistics. The CircuitBreaker instance exposes a Hystrix compliant statistics snapshot to the monitor which can then be processed accordingly.  See the API documentation for more information.\n\n## API Documentation\nFor more information visit our [API reference](https://kitura.github.io/CircuitBreaker/index.html).\n\n## Community\nWe love to talk server-side Swift, and Kitura. Join our [Slack](http://swift-at-ibm-slack.mybluemix.net/) to meet the team!\n\n## License\nThis Swift package is licensed under Apache 2.0. Full license text is available in [LICENSE](https://github.com/Kitura/CircuitBreaker/blob/master/LICENSE).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FKitura%2FCircuitBreaker","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FKitura%2FCircuitBreaker","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FKitura%2FCircuitBreaker/lists"}