pysafecircuit


Namepysafecircuit JSON
Version 0.1.1 PyPI version JSON
download
home_pagehttps://github.com/fadedreams/pycircuitbreaker
SummaryThis Python code defines a CircuitBreaker class with configurable failure thresholds and timeouts, managing state transitions and callbacks for open, half-open, and closed states.
upload_time2024-06-29 10:44:16
maintainerNone
docs_urlNone
authorfadedreams7
requires_python<4.0,>=3.8
licenseMIT
keywords circuit breaker error utilities
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            
### pysafecircuit
This Python module provides a CircuitBreaker class that helps in managing failures and timeouts gracefully using the circuit breaker pattern.

### Overview
The CircuitBreaker class manages three states:

- CLOSED: Normal operation state where calls are allowed.
- OPEN: Circuit is open due to excessive failures, and calls are blocked.
- HALF_OPEN: After a timeout, the circuit allows a limited number of calls to determine if the underlying service is available.
### Dependencies
- threading: For thread synchronization using locks.
- time: For pausing execution between retries.
- datetime and timedelta: For handling timeout calculations.
- typing: For type annotations to specify callback function signatures.

### Example Usage
```py
import time
import random
from datetime import datetime, timedelta
from typing import Callable, Optional
from pysafecircuit import CircuitBreaker

def example_function():
    # Simulate some operation that may fail
    if random.random() < 0.5:
        return Exception("an error occurred")
    return None

def main():
    # Create a new circuit breaker with max_failures=3, timeout=5 seconds, pause_time=1 second, and max_consecutive_successes=2
    cb = CircuitBreaker(max_failures=3, timeout=5, pause_time=1, max_consecutive_successes=2)

    # Set up the callbacks
    cb.set_on_open(lambda: print("Circuit breaker opened!"))
    cb.set_on_close(lambda: print("Circuit breaker closed!"))
    cb.set_on_half_open(lambda: print("Circuit breaker is half-open, trying again..."))

    # Execute the function with circuit breaker protection
    for i in range(20):
        err = cb.execute(example_function)
        if err:
            print(f"Attempt {i+1} failed: {err}")
        else:
            print(f"Attempt {i+1} succeeded")
        time.sleep(1)  # Simulate some delay between attempts

if __name__ == "__main__":
    main()

```
### Features
- State Management: Tracks the state of the circuit (CLOSED, OPEN, HALF_OPEN).
- Callbacks: Allows setting callbacks for when the circuit breaker transitions between states (set_on_open, set_on_close, set_on_half_open).
- Retry Logic: Implements retry logic with configurable parameters (max_failures, timeout, pause_time, max_consecutive_successes).

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/fadedreams/pycircuitbreaker",
    "name": "pysafecircuit",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<4.0,>=3.8",
    "maintainer_email": null,
    "keywords": "circuit breaker, error, utilities",
    "author": "fadedreams7",
    "author_email": "fadedreams7@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/9d/d6/79c53c485904e9f1669e6d1dab145d58905534e30be769ff0af4e9ad714d/pysafecircuit-0.1.1.tar.gz",
    "platform": null,
    "description": "\n### pysafecircuit\nThis Python module provides a CircuitBreaker class that helps in managing failures and timeouts gracefully using the circuit breaker pattern.\n\n### Overview\nThe CircuitBreaker class manages three states:\n\n- CLOSED: Normal operation state where calls are allowed.\n- OPEN: Circuit is open due to excessive failures, and calls are blocked.\n- HALF_OPEN: After a timeout, the circuit allows a limited number of calls to determine if the underlying service is available.\n### Dependencies\n- threading: For thread synchronization using locks.\n- time: For pausing execution between retries.\n- datetime and timedelta: For handling timeout calculations.\n- typing: For type annotations to specify callback function signatures.\n\n### Example Usage\n```py\nimport time\nimport random\nfrom datetime import datetime, timedelta\nfrom typing import Callable, Optional\nfrom pysafecircuit import CircuitBreaker\n\ndef example_function():\n    # Simulate some operation that may fail\n    if random.random() < 0.5:\n        return Exception(\"an error occurred\")\n    return None\n\ndef main():\n    # Create a new circuit breaker with max_failures=3, timeout=5 seconds, pause_time=1 second, and max_consecutive_successes=2\n    cb = CircuitBreaker(max_failures=3, timeout=5, pause_time=1, max_consecutive_successes=2)\n\n    # Set up the callbacks\n    cb.set_on_open(lambda: print(\"Circuit breaker opened!\"))\n    cb.set_on_close(lambda: print(\"Circuit breaker closed!\"))\n    cb.set_on_half_open(lambda: print(\"Circuit breaker is half-open, trying again...\"))\n\n    # Execute the function with circuit breaker protection\n    for i in range(20):\n        err = cb.execute(example_function)\n        if err:\n            print(f\"Attempt {i+1} failed: {err}\")\n        else:\n            print(f\"Attempt {i+1} succeeded\")\n        time.sleep(1)  # Simulate some delay between attempts\n\nif __name__ == \"__main__\":\n    main()\n\n```\n### Features\n- State Management: Tracks the state of the circuit (CLOSED, OPEN, HALF_OPEN).\n- Callbacks: Allows setting callbacks for when the circuit breaker transitions between states (set_on_open, set_on_close, set_on_half_open).\n- Retry Logic: Implements retry logic with configurable parameters (max_failures, timeout, pause_time, max_consecutive_successes).\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "This Python code defines a CircuitBreaker class with configurable failure thresholds and timeouts, managing state transitions and callbacks for open, half-open, and closed states.",
    "version": "0.1.1",
    "project_urls": {
        "Homepage": "https://github.com/fadedreams/pycircuitbreaker",
        "Repository": "https://github.com/fadedreams/pycircuitbreaker"
    },
    "split_keywords": [
        "circuit breaker",
        " error",
        " utilities"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "4ee4e809f9054165227354182dea5d797ae10105c433e5d62e4a42949b4c492a",
                "md5": "80d1459f990dd6adafa38439b7365a5f",
                "sha256": "cd9835594c20f74a8805d5d80c9ccd3a29ae1c70da375fb6bae39d9f1ee60ade"
            },
            "downloads": -1,
            "filename": "pysafecircuit-0.1.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "80d1459f990dd6adafa38439b7365a5f",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4.0,>=3.8",
            "size": 4276,
            "upload_time": "2024-06-29T10:44:14",
            "upload_time_iso_8601": "2024-06-29T10:44:14.968965Z",
            "url": "https://files.pythonhosted.org/packages/4e/e4/e809f9054165227354182dea5d797ae10105c433e5d62e4a42949b4c492a/pysafecircuit-0.1.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "9dd679c53c485904e9f1669e6d1dab145d58905534e30be769ff0af4e9ad714d",
                "md5": "58117645031c70780eaed7c77bebff5b",
                "sha256": "1f74706df58ce97818f0d3ad9fa5508cad4bac571d1df8cdcc9eeebe8de7db1d"
            },
            "downloads": -1,
            "filename": "pysafecircuit-0.1.1.tar.gz",
            "has_sig": false,
            "md5_digest": "58117645031c70780eaed7c77bebff5b",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4.0,>=3.8",
            "size": 2609,
            "upload_time": "2024-06-29T10:44:16",
            "upload_time_iso_8601": "2024-06-29T10:44:16.498122Z",
            "url": "https://files.pythonhosted.org/packages/9d/d6/79c53c485904e9f1669e6d1dab145d58905534e30be769ff0af4e9ad714d/pysafecircuit-0.1.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-06-29 10:44:16",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "fadedreams",
    "github_project": "pycircuitbreaker",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "pysafecircuit"
}
        
Elapsed time: 4.67147s