probirka 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,18 @@
1
+ root = true
2
+
3
+ [*]
4
+ charset = utf-8
5
+ end_of_line = lf
6
+ trim_trailing_whitespace = true
7
+ insert_final_newline = true
8
+ indent_style = space
9
+ indent_size = 2
10
+
11
+ [*.py]
12
+ indent_size = 4
13
+
14
+ [{Makefile,**.mk}]
15
+ indent_style = tab
16
+
17
+ [*.{md,txt,rst}]
18
+ trim_trailing_whitespace = false
@@ -0,0 +1,25 @@
1
+ ---
2
+ name: 👷🏼 pypi
3
+
4
+ on:
5
+ release:
6
+ types: [ created ]
7
+
8
+ jobs:
9
+ build:
10
+ runs-on: ubuntu-latest
11
+ steps:
12
+ - uses: actions/checkout@v4
13
+ - name: Extract branch name
14
+ shell: bash
15
+ run: |
16
+ echo "##[set-output name=ver;]$(echo ${GITHUB_REF#refs/*/})"
17
+ id: extract_name_and_version
18
+ - run: sed -i 's/0.0.0/'"${{ steps.extract_name_and_version.outputs.ver }}"'/' pyproject.toml
19
+ - run: head -n 10 pyproject.toml
20
+ - run: sed -i 's/0.0.0/'"${{ steps.extract_name_and_version.outputs.ver }}"'/' probirka/__init__.py
21
+ - uses: astral-sh/setup-uv@v4
22
+ - run: uv python install 3.12
23
+ - run: uv sync --all-extras --dev
24
+ - run: uv build
25
+ - run: uv publish --username __token__ --password ${{ secrets.PYPI_TOKEN }}
@@ -0,0 +1,29 @@
1
+ ---
2
+ name: 🧐 test
3
+
4
+ on:
5
+ pull_request:
6
+ branches: [ main ]
7
+
8
+ jobs:
9
+ tests:
10
+ runs-on: ubuntu-latest
11
+ strategy:
12
+ matrix:
13
+ just-trigger:
14
+ - "lint"
15
+ - "tests"
16
+ python-version:
17
+ - "3.8"
18
+ - "3.9"
19
+ - "3.10"
20
+ - "3.11"
21
+ - "3.12"
22
+ - "3.13"
23
+ steps:
24
+ - uses: actions/checkout@v4
25
+ - uses: extractions/setup-just@v2
26
+ - uses: astral-sh/setup-uv@v4
27
+ - run: uv python install ${{ matrix.python-version }}
28
+ - run: uv sync --all-extras --dev
29
+ - run: just ${{ matrix.just-trigger }}
@@ -0,0 +1,164 @@
1
+ .python-version
2
+ .idea/
3
+ # Byte-compiled / optimized / DLL files
4
+ __pycache__/
5
+ *.py[cod]
6
+ *$py.class
7
+
8
+ # C extensions
9
+ *.so
10
+
11
+ # Distribution / packaging
12
+ .Python
13
+ build/
14
+ develop-eggs/
15
+ dist/
16
+ downloads/
17
+ eggs/
18
+ .eggs/
19
+ lib/
20
+ lib64/
21
+ parts/
22
+ sdist/
23
+ var/
24
+ wheels/
25
+ share/python-wheels/
26
+ *.egg-info/
27
+ .installed.cfg
28
+ *.egg
29
+ MANIFEST
30
+
31
+ # PyInstaller
32
+ # Usually these files are written by a python script from a template
33
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
34
+ *.manifest
35
+ *.spec
36
+
37
+ # Installer logs
38
+ pip-log.txt
39
+ pip-delete-this-directory.txt
40
+
41
+ # Unit test / coverage reports
42
+ htmlcov/
43
+ .tox/
44
+ .nox/
45
+ .coverage
46
+ .coverage.*
47
+ .cache
48
+ nosetests.xml
49
+ coverage.xml
50
+ *.cover
51
+ *.py,cover
52
+ .hypothesis/
53
+ .pytest_cache/
54
+ cover/
55
+
56
+ # Translations
57
+ *.mo
58
+ *.pot
59
+
60
+ # Django stuff:
61
+ *.log
62
+ local_settings.py
63
+ db.sqlite3
64
+ db.sqlite3-journal
65
+
66
+ # Flask stuff:
67
+ instance/
68
+ .webassets-cache
69
+
70
+ # Scrapy stuff:
71
+ .scrapy
72
+
73
+ # Sphinx documentation
74
+ docs/_build/
75
+
76
+ # PyBuilder
77
+ .pybuilder/
78
+ target/
79
+
80
+ # Jupyter Notebook
81
+ .ipynb_checkpoints
82
+
83
+ # IPython
84
+ profile_default/
85
+ ipython_config.py
86
+
87
+ # pyenv
88
+ # For a library or package, you might want to ignore these files since the code is
89
+ # intended to run in multiple environments; otherwise, check them in:
90
+ # .python-version
91
+
92
+ # pipenv
93
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
94
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
95
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
96
+ # install all needed dependencies.
97
+ #Pipfile.lock
98
+
99
+ # poetry
100
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
101
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
102
+ # commonly ignored for libraries.
103
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
104
+ #poetry.lock
105
+
106
+ # pdm
107
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
108
+ #pdm.lock
109
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
110
+ # in version control.
111
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
112
+ .pdm.toml
113
+ .pdm-python
114
+ .pdm-build/
115
+
116
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
117
+ __pypackages__/
118
+
119
+ # Celery stuff
120
+ celerybeat-schedule
121
+ celerybeat.pid
122
+
123
+ # SageMath parsed files
124
+ *.sage.py
125
+
126
+ # Environments
127
+ .env
128
+ .venv
129
+ env/
130
+ venv/
131
+ ENV/
132
+ env.bak/
133
+ venv.bak/
134
+
135
+ # Spyder project settings
136
+ .spyderproject
137
+ .spyproject
138
+
139
+ # Rope project settings
140
+ .ropeproject
141
+
142
+ # mkdocs documentation
143
+ /site
144
+
145
+ # mypy
146
+ .mypy_cache/
147
+ .dmypy.json
148
+ dmypy.json
149
+
150
+ # Pyre type checker
151
+ .pyre/
152
+
153
+ # pytype static type analyzer
154
+ .pytype/
155
+
156
+ # Cython debug symbols
157
+ cython_debug/
158
+
159
+ # PyCharm
160
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
161
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
162
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
163
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
164
+ #.idea/
@@ -0,0 +1,31 @@
1
+ ---
2
+ default_install_hook_types:
3
+ - pre-commit
4
+
5
+ repos:
6
+ - repo: local
7
+ hooks:
8
+ - id: mypy
9
+ name: mypy
10
+ entry: python -m mypy
11
+ language: system
12
+ 'types_or': [ python, pyi ]
13
+ - repo: https://github.com/astral-sh/ruff-pre-commit
14
+ rev: "v0.8.1"
15
+ hooks:
16
+ - id: ruff
17
+ args: [ --fix, --unsafe-fixes ]
18
+ - id: ruff-format
19
+ - repo: https://github.com/pre-commit/pre-commit-hooks
20
+ rev: "v5.0.0"
21
+ hooks:
22
+ - id: check-added-large-files
23
+ - id: check-merge-conflict
24
+ - id: detect-private-key
25
+ - id: check-json
26
+ - id: check-toml
27
+ - id: check-yaml
28
+ - id: double-quote-string-fixer
29
+ - id: end-of-file-fixer
30
+ - id: trailing-whitespace
31
+ exclude: ^.+(\.md)$
probirka-0.3.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 KODE LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,33 @@
1
+ Metadata-Version: 2.3
2
+ Name: probirka
3
+ Version: 0.3.0
4
+ Summary: Python 3 library to write simple asynchronous health checks (probes)
5
+ Project-URL: Repository, https://github.com/appKODE/probirka
6
+ Author-email: KODE <slurm@kode.ru>
7
+ License: MIT
8
+ Keywords: health-check,monitoring,probes
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: Programming Language :: Python :: 3 :: Only
11
+ Classifier: Programming Language :: Python :: 3.8
12
+ Classifier: Programming Language :: Python :: 3.9
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
18
+ Requires-Python: >=3.8
19
+ Description-Content-Type: text/markdown
20
+
21
+ # PROB🧪RKA
22
+
23
+ Python 3 library to write simple asynchronous health checks (probes)
24
+
25
+ [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
26
+ [![PyPI](https://img.shields.io/pypi/v/probirka.svg)](https://pypi.python.org/pypi/probirka)
27
+ [![PyPI](https://img.shields.io/pypi/dm/probirka.svg)](https://pypi.python.org/pypi/probirka)
28
+
29
+ ## Installation
30
+
31
+ ```shell
32
+ pip install probirka
33
+ ```
@@ -0,0 +1,13 @@
1
+ # PROB🧪RKA
2
+
3
+ Python 3 library to write simple asynchronous health checks (probes)
4
+
5
+ [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
6
+ [![PyPI](https://img.shields.io/pypi/v/probirka.svg)](https://pypi.python.org/pypi/probirka)
7
+ [![PyPI](https://img.shields.io/pypi/dm/probirka.svg)](https://pypi.python.org/pypi/probirka)
8
+
9
+ ## Installation
10
+
11
+ ```shell
12
+ pip install probirka
13
+ ```
@@ -0,0 +1,20 @@
1
+ SOURCE_PATH := "probirka"
2
+ TESTS_PATH := "tests"
3
+
4
+ upgrade:
5
+ uv lock --upgrade
6
+
7
+ fmt:
8
+ uv run ruff format {{ SOURCE_PATH }}
9
+
10
+ lint:
11
+ uv run ruff check {{ SOURCE_PATH }}
12
+
13
+ mypy:
14
+ uv run python -m mypy --pretty {{ SOURCE_PATH }}
15
+
16
+ fix:
17
+ uv run ruff check --fix --unsafe-fixes {{ SOURCE_PATH }}
18
+
19
+ tests:
20
+ uv run pytest tests/
@@ -0,0 +1,32 @@
1
+ from contextlib import suppress
2
+
3
+ from probirka._probes import Probe, ProbeBase
4
+ from probirka._probirka import Probirka
5
+ from probirka._results import HealthCheckResult, ProbeResult
6
+
7
+ __title__ = 'probirka'
8
+ __version__ = '0.3.0'
9
+ __url__ = 'https://github.com/appKODE/probirka'
10
+ __author__ = ''
11
+ __author_email__ = ''
12
+ __license__ = ''
13
+
14
+ __all__ = [
15
+ 'HealthCheckResult',
16
+ # types
17
+ 'Probe',
18
+ 'ProbeBase',
19
+ # results
20
+ 'ProbeResult',
21
+ 'Probirka',
22
+ ]
23
+
24
+ with suppress(ImportError):
25
+ from probirka._aiohttp import make_aiohttp_endpoint # noqa
26
+
27
+ __all__.append('make_aiohttp_endpoint')
28
+
29
+ with suppress(ImportError):
30
+ from probirka._fastapi import make_fastapi_endpoint # noqa
31
+
32
+ __all__.append('make_fastapi_endpoint')
@@ -0,0 +1,41 @@
1
+ import json
2
+
3
+ from dataclasses import asdict
4
+ from typing import Any, Callable, Coroutine, List, Optional, Union
5
+
6
+ from aiohttp import web
7
+
8
+ from probirka import Probirka
9
+
10
+
11
+ def make_aiohttp_endpoint(
12
+ probirka: Probirka,
13
+ timeout: Optional[int] = None,
14
+ with_groups: Union[str, List[str]] = '',
15
+ skip_required: bool = False,
16
+ return_results: bool = True,
17
+ success_code: int = 200,
18
+ error_code: int = 500,
19
+ ) -> Callable[[web.Request], Coroutine[Any, Any, web.Response]]:
20
+ async def endpoint(
21
+ _: web.Request,
22
+ ) -> web.Response:
23
+ res = await probirka.run(
24
+ timeout=timeout,
25
+ with_groups=with_groups,
26
+ skip_required=skip_required,
27
+ )
28
+ status_code = success_code if res.ok else error_code
29
+ return (
30
+ web.json_response(
31
+ text=json.dumps(obj=asdict(res), default=str),
32
+ status=status_code,
33
+ )
34
+ if return_results
35
+ else web.Response(
36
+ body='',
37
+ status=status_code,
38
+ )
39
+ )
40
+
41
+ return endpoint
@@ -0,0 +1,29 @@
1
+ from typing import Any, Callable, Coroutine, List, Optional, Union
2
+
3
+ from fastapi import status
4
+ from fastapi.encoders import jsonable_encoder
5
+ from fastapi.responses import JSONResponse, Response
6
+
7
+ from probirka import Probirka
8
+
9
+
10
+ def make_fastapi_endpoint(
11
+ probirka: Probirka,
12
+ timeout: Optional[int] = None,
13
+ with_groups: Union[str, List[str]] = '',
14
+ skip_required: bool = False,
15
+ return_results: bool = True,
16
+ success_code: int = status.HTTP_200_OK,
17
+ error_code: int = status.HTTP_500_INTERNAL_SERVER_ERROR,
18
+ ) -> Callable[[], Coroutine[Any, Any, Response]]:
19
+ async def endpoint() -> Response:
20
+ res = await probirka.run(
21
+ timeout=timeout,
22
+ with_groups=with_groups,
23
+ skip_required=skip_required,
24
+ )
25
+ resp = JSONResponse(jsonable_encoder(res)) if return_results else Response()
26
+ resp.status_code = success_code if res.ok else error_code
27
+ return resp
28
+
29
+ return endpoint
@@ -0,0 +1,81 @@
1
+ from abc import ABC, abstractmethod
2
+ from asyncio import iscoroutinefunction, wait_for
3
+ from datetime import datetime
4
+ from typing import Callable, Optional, Protocol
5
+
6
+ from probirka._results import ProbeResult
7
+
8
+
9
+ class Probe(
10
+ Protocol,
11
+ ):
12
+ async def run_check(
13
+ self,
14
+ ) -> ProbeResult: ...
15
+
16
+
17
+ class ProbeBase(
18
+ ABC,
19
+ ):
20
+ def __init__(
21
+ self,
22
+ name: Optional[str] = None,
23
+ timeout: Optional[int] = None,
24
+ ) -> None:
25
+ self._timeout = timeout
26
+ self._name = name or self.__class__.__name__
27
+
28
+ @abstractmethod
29
+ async def _check(
30
+ self,
31
+ ) -> Optional[bool]:
32
+ raise NotImplementedError
33
+
34
+ async def run_check(
35
+ self,
36
+ ) -> ProbeResult:
37
+ started_at = datetime.now()
38
+ error = None
39
+ task = self._check()
40
+ try:
41
+ result = await wait_for(
42
+ fut=task,
43
+ timeout=self._timeout,
44
+ )
45
+ if result is None:
46
+ result = True
47
+ except Exception as exc:
48
+ result = False
49
+ error = str(exc)
50
+ finally:
51
+ task.close()
52
+ return ProbeResult(
53
+ ok=False if result is None else result,
54
+ started_at=started_at,
55
+ elapsed=datetime.now() - started_at,
56
+ name=self._name,
57
+ error=error,
58
+ )
59
+
60
+
61
+ class CallableProbe(
62
+ ProbeBase,
63
+ ):
64
+ def __init__(
65
+ self,
66
+ func: Callable[[], Optional[bool]],
67
+ name: Optional[str] = None,
68
+ timeout: Optional[int] = None,
69
+ ) -> None:
70
+ self._func = func
71
+ super().__init__(
72
+ name=name or func.__name__,
73
+ timeout=timeout,
74
+ )
75
+
76
+ async def _check(
77
+ self,
78
+ ) -> Optional[bool]:
79
+ if iscoroutinefunction(self._func):
80
+ return await self._func()
81
+ return self._func()
@@ -0,0 +1,110 @@
1
+ from asyncio import gather, wait_for
2
+ from collections import defaultdict
3
+ from datetime import datetime
4
+ from typing import Any, Callable, Dict, List, Optional, Sequence, Union
5
+
6
+ from probirka._probes import CallableProbe, Probe
7
+ from probirka._results import HealthCheckResult, ProbeResult
8
+
9
+
10
+ class Probirka:
11
+ def __init__(
12
+ self,
13
+ ) -> None:
14
+ self._required_probes: List[Probe] = []
15
+ self._optional_probes: Dict[str, List[Probe]] = defaultdict(list)
16
+ self._info: Dict[str, Any] = {}
17
+
18
+ def add_info(
19
+ self,
20
+ name: str,
21
+ value: Any,
22
+ ) -> None:
23
+ self._info[name] = value
24
+
25
+ @property
26
+ def info(
27
+ self,
28
+ ) -> Dict[str, Any]:
29
+ return self._info
30
+
31
+ def add_probes(
32
+ self,
33
+ *probes: Probe,
34
+ groups: Union[str, List[str]] = '',
35
+ ) -> None:
36
+ if groups:
37
+ if isinstance(groups, str):
38
+ groups = [groups]
39
+ for group in groups:
40
+ self._optional_probes[group].extend(probes)
41
+ return
42
+ self._required_probes.extend(probes)
43
+
44
+ def add(
45
+ self,
46
+ name: Optional[str] = None,
47
+ timeout: Optional[int] = None,
48
+ groups: Union[str, List[str]] = '',
49
+ ) -> Callable:
50
+ def _wrapper(
51
+ func: Callable,
52
+ ) -> Any:
53
+ self.add_probes(
54
+ CallableProbe(
55
+ func=func,
56
+ name=name,
57
+ timeout=timeout,
58
+ ),
59
+ groups=groups,
60
+ )
61
+ return func
62
+
63
+ return _wrapper
64
+
65
+ async def _inner_run(
66
+ self,
67
+ with_groups: List[str],
68
+ skip_required: bool,
69
+ ) -> Sequence[ProbeResult]:
70
+ tasks = [] if skip_required else [probe.run_check() for probe in self._required_probes]
71
+ for group in with_groups:
72
+ tasks += [probe.run_check() for probe in self._optional_probes[group]]
73
+ results = await gather(*tasks)
74
+ for coro in tasks:
75
+ coro.close()
76
+ return results
77
+
78
+ async def run(
79
+ self,
80
+ timeout: Optional[int] = None,
81
+ with_groups: Union[str, List[str]] = '',
82
+ skip_required: bool = False,
83
+ ) -> HealthCheckResult:
84
+ if with_groups and isinstance(with_groups, str):
85
+ with_groups = [with_groups]
86
+ started_at = datetime.now()
87
+ fut = self._inner_run(
88
+ with_groups=with_groups, # type: ignore
89
+ skip_required=skip_required,
90
+ )
91
+ results = (
92
+ await wait_for(
93
+ fut=fut,
94
+ timeout=timeout,
95
+ )
96
+ if timeout
97
+ else await fut
98
+ )
99
+ ok = True
100
+ for result in results:
101
+ if result.ok is False:
102
+ ok = False
103
+ break
104
+ return HealthCheckResult(
105
+ ok=ok,
106
+ info=self._info,
107
+ started_at=started_at,
108
+ total_elapsed=datetime.now() - started_at,
109
+ checks=results,
110
+ )
@@ -0,0 +1,21 @@
1
+ from dataclasses import dataclass
2
+ from datetime import datetime, timedelta
3
+ from typing import Any, Dict, Optional, Sequence
4
+
5
+
6
+ @dataclass(frozen=True)
7
+ class ProbeResult:
8
+ ok: bool
9
+ started_at: datetime
10
+ elapsed: timedelta
11
+ name: str
12
+ error: Optional[str]
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class HealthCheckResult:
17
+ ok: bool
18
+ info: Dict[str, Any]
19
+ started_at: datetime
20
+ total_elapsed: timedelta
21
+ checks: Sequence[ProbeResult]