message-van 0.2.4__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.
Files changed (41) hide show
  1. message_van-0.2.4/.github/workflows/publish.yml +96 -0
  2. message_van-0.2.4/.gitignore +173 -0
  3. message_van-0.2.4/.python-version +1 -0
  4. message_van-0.2.4/LICENSE.txt +10 -0
  5. message_van-0.2.4/PKG-INFO +17 -0
  6. message_van-0.2.4/README.md +5 -0
  7. message_van-0.2.4/docs/img/icon.png +0 -0
  8. message_van-0.2.4/docs/img/logo.png +0 -0
  9. message_van-0.2.4/pyproject.toml +144 -0
  10. message_van-0.2.4/requirements-dev.lock +84 -0
  11. message_van-0.2.4/requirements.lock +23 -0
  12. message_van-0.2.4/src/message_van/__init__.py +12 -0
  13. message_van-0.2.4/src/message_van/adapters/__init__.py +8 -0
  14. message_van-0.2.4/src/message_van/adapters/config_adapter.py +28 -0
  15. message_van-0.2.4/src/message_van/adapters/mappers/__init__.py +6 -0
  16. message_van-0.2.4/src/message_van/adapters/mappers/user_config_mapper.py +5 -0
  17. message_van-0.2.4/src/message_van/adapters/models/__init__.py +6 -0
  18. message_van-0.2.4/src/message_van/adapters/models/user_config.py +9 -0
  19. message_van-0.2.4/src/message_van/adapters/signature_adapter.py +119 -0
  20. message_van-0.2.4/src/message_van/adapters/util/__init__.py +6 -0
  21. message_van-0.2.4/src/message_van/adapters/util/toml_parser.py +20 -0
  22. message_van-0.2.4/src/message_van/config.py +3 -0
  23. message_van-0.2.4/src/message_van/domain/__init__.py +0 -0
  24. message_van-0.2.4/src/message_van/domain/exceptions/__init__.py +8 -0
  25. message_van-0.2.4/src/message_van/domain/exceptions/already_registered_handler_error.py +11 -0
  26. message_van-0.2.4/src/message_van/domain/exceptions/unknown_handler_error.py +10 -0
  27. message_van-0.2.4/src/message_van/domain/models/__init__.py +32 -0
  28. message_van-0.2.4/src/message_van/domain/models/base/__init__.py +18 -0
  29. message_van-0.2.4/src/message_van/domain/models/base/command.py +5 -0
  30. message_van-0.2.4/src/message_van/domain/models/base/command_handler.py +14 -0
  31. message_van-0.2.4/src/message_van/domain/models/base/event.py +5 -0
  32. message_van-0.2.4/src/message_van/domain/models/base/event_handler.py +14 -0
  33. message_van-0.2.4/src/message_van/domain/models/base/message.py +5 -0
  34. message_van-0.2.4/src/message_van/domain/models/base/message_handler.py +14 -0
  35. message_van-0.2.4/src/message_van/domain/models/handler_signature.py +12 -0
  36. message_van-0.2.4/src/message_van/domain/models/message_handler_type.py +6 -0
  37. message_van-0.2.4/src/message_van/domain/models/message_handlers.py +69 -0
  38. message_van-0.2.4/src/message_van/domain/models/message_van.py +59 -0
  39. message_van-0.2.4/src/message_van/domain/models/unit_of_work.py +16 -0
  40. message_van-0.2.4/src/message_van/service_layer/__init__.py +6 -0
  41. message_van-0.2.4/src/message_van/service_layer/service.py +29 -0
@@ -0,0 +1,96 @@
1
+ name: Build and Publish
2
+
3
+ on:
4
+ push:
5
+ tags:
6
+ - "*"
7
+
8
+ jobs:
9
+ build:
10
+ runs-on: ubuntu-latest
11
+ container:
12
+ image: jfxs/rye
13
+ steps:
14
+ - name: Checkout Repository
15
+ uses: actions/checkout@v4
16
+
17
+ - name: Configure Git (optional, but recommended)
18
+ run: |
19
+ git config --global --add safe.directory /__w/${{ github.event.repository.name }}/${{ github.event.repository.name }}
20
+
21
+ - name: Install dependencies
22
+ run: rye sync
23
+
24
+ - name: Build Package
25
+ run: rye build
26
+
27
+ - name: Store the distribution packages
28
+ uses: actions/upload-artifact@v4
29
+ with:
30
+ name: python-package-distributions
31
+ path: dist/
32
+
33
+ publish-to-pypi:
34
+ name: >-
35
+ Publish Python 🐍 distribution 📦 to PyPI
36
+ if: startsWith(github.ref, 'refs/tags/')
37
+ needs:
38
+ - build
39
+ runs-on: ubuntu-latest
40
+ environment:
41
+ name: pypi
42
+ url: https://pypi.org/p/message-van
43
+ permissions:
44
+ id-token: write
45
+
46
+ steps:
47
+ - name: Download all the dists
48
+ uses: actions/download-artifact@v4
49
+ with:
50
+ name: python-package-distributions
51
+ path: dist/
52
+ - name: Publish distribution 📦 to PyPI
53
+ uses: pypa/gh-action-pypi-publish@release/v1
54
+
55
+ github-release:
56
+ name: >-
57
+ Sign the Python 🐍 distribution 📦 with Sigstore
58
+ and upload them to GitHub Release
59
+ needs:
60
+ - publish-to-pypi
61
+ runs-on: ubuntu-latest
62
+
63
+ permissions:
64
+ contents: write # IMPORTANT: mandatory for making GitHub Releases
65
+ id-token: write # IMPORTANT: mandatory for sigstore
66
+
67
+ steps:
68
+ - name: Download all the dists
69
+ uses: actions/download-artifact@v4
70
+ with:
71
+ name: python-package-distributions
72
+ path: dist/
73
+ - name: Sign the dists with Sigstore
74
+ uses: sigstore/gh-action-sigstore-python@v3.0.0
75
+ with:
76
+ inputs: >-
77
+ ./dist/*.tar.gz
78
+ ./dist/*.whl
79
+ - name: Create GitHub Release
80
+ env:
81
+ GITHUB_TOKEN: ${{ github.token }}
82
+ run: >-
83
+ gh release create
84
+ "$GITHUB_REF_NAME"
85
+ --repo "$GITHUB_REPOSITORY"
86
+ --notes ""
87
+ - name: Upload artifact signatures to GitHub Release
88
+ env:
89
+ GITHUB_TOKEN: ${{ github.token }}
90
+ # Upload to GitHub Release using the `gh` CLI.
91
+ # `dist/` contains the built packages, and the
92
+ # sigstore-produced signatures and certificates.
93
+ run: >-
94
+ gh release upload
95
+ "$GITHUB_REF_NAME" dist/**
96
+ --repo "$GITHUB_REPOSITORY"
@@ -0,0 +1,173 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+
110
+ # pdm
111
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
112
+ #pdm.lock
113
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
114
+ # in version control.
115
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
116
+ .pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
121
+ __pypackages__/
122
+
123
+ # Celery stuff
124
+ celerybeat-schedule
125
+ celerybeat.pid
126
+
127
+ # SageMath parsed files
128
+ *.sage.py
129
+
130
+ # Environments
131
+ .env
132
+ .venv
133
+ env/
134
+ venv/
135
+ ENV/
136
+ env.bak/
137
+ venv.bak/
138
+
139
+ # Spyder project settings
140
+ .spyderproject
141
+ .spyproject
142
+
143
+ # Rope project settings
144
+ .ropeproject
145
+
146
+ # mkdocs documentation
147
+ /site
148
+
149
+ # mypy
150
+ .mypy_cache/
151
+ .dmypy.json
152
+ dmypy.json
153
+
154
+ # Pyre type checker
155
+ .pyre/
156
+
157
+ # pytype static type analyzer
158
+ .pytype/
159
+
160
+ # Cython debug symbols
161
+ cython_debug/
162
+
163
+ # PyCharm
164
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
165
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
166
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
167
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
168
+ #.idea/
169
+
170
+ # PyPI configuration file
171
+ .pypirc
172
+
173
+ .idea/
@@ -0,0 +1 @@
1
+ 3.13.1
@@ -0,0 +1,10 @@
1
+ MIT License
2
+
3
+ Copyright (c) <year> <copyright holders>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
10
+
@@ -0,0 +1,17 @@
1
+ Metadata-Version: 2.4
2
+ Name: message-van
3
+ Version: 0.2.4
4
+ Summary: Python Event-Driven Architecture without the Administration.
5
+ Author-email: Thomas Vanhelden <thomas.vanhelden@gmail.com>
6
+ License: MIT
7
+ License-File: LICENSE.txt
8
+ Requires-Python: >=3.10
9
+ Requires-Dist: pydantic==2.10.6
10
+ Requires-Dist: tomli==2.2.1
11
+ Description-Content-Type: text/markdown
12
+
13
+ # Message Van
14
+
15
+ Python Event-Driven Architecture without the Administration.
16
+
17
+ ![alt text](docs/img/icon.png)
@@ -0,0 +1,5 @@
1
+ # Message Van
2
+
3
+ Python Event-Driven Architecture without the Administration.
4
+
5
+ ![alt text](docs/img/icon.png)
Binary file
Binary file
@@ -0,0 +1,144 @@
1
+ [project]
2
+ name = "message-van"
3
+ version = "0.2.4"
4
+ description = "Python Event-Driven Architecture without the Administration."
5
+ authors = [
6
+ { name = "Thomas Vanhelden", email = "thomas.vanhelden@gmail.com" }
7
+ ]
8
+ dependencies = [
9
+ "pydantic==2.10.6",
10
+ "tomli==2.2.1",
11
+ ]
12
+ readme = "README.md"
13
+ requires-python = ">= 3.10"
14
+ license = { text = "MIT" }
15
+
16
+ [build-system]
17
+ requires = ["hatchling"]
18
+ build-backend = "hatchling.build"
19
+
20
+
21
+ [tool.rye]
22
+ managed = true
23
+ dev-dependencies = [
24
+ "ruff==0.9.10",
25
+ "pdbpp==0.10.3",
26
+ "bump-my-version==1.0.2",
27
+ ]
28
+
29
+
30
+ [tool.hatch.metadata]
31
+ allow-direct-references = true
32
+
33
+ [tool.hatch.build.targets.wheel]
34
+ packages = ["src/message_van"]
35
+
36
+
37
+ [tool.bumpversion]
38
+ current_version = "0.2.4"
39
+ parse = "(?P<major>\\d+)\\.(?P<minor>\\d+)\\.(?P<patch>\\d+)"
40
+ serialize = ["{major}.{minor}.{patch}"]
41
+ search = "{current_version}"
42
+ replace = "{new_version}"
43
+ regex = false
44
+ ignore_missing_version = false
45
+ commit = true
46
+ tag = true
47
+ sign_tags = true
48
+ tag_name = "{new_version}"
49
+ tag_message = "Bump version: {current_version} → {new_version}"
50
+ allow_dirty = false
51
+ message = "Bump version: {current_version} → {new_version}"
52
+ commit_args = "--gpg-sign"
53
+
54
+ [[tool.bumpversion.files]]
55
+ filename = "pyproject.toml"
56
+ search = 'version = "{current_version}"'
57
+ replace = 'version = "{new_version}"'
58
+
59
+
60
+ [tool.ruff]
61
+ exclude = [
62
+ ".bzr",
63
+ ".direnv",
64
+ ".eggs",
65
+ ".git",
66
+ ".git-rewrite",
67
+ ".hg",
68
+ ".ipynb_checkpoints",
69
+ ".mypy_cache",
70
+ ".nox",
71
+ ".pants.d",
72
+ ".pyenv",
73
+ ".pytest_cache",
74
+ ".pytype",
75
+ ".ruff_cache",
76
+ ".svn",
77
+ ".tox",
78
+ ".venv",
79
+ ".vscode",
80
+ "__pypackages__",
81
+ "_build",
82
+ "buck-out",
83
+ "build",
84
+ "dist",
85
+ "node_modules",
86
+ "site-packages",
87
+ "venv",
88
+ ]
89
+
90
+ line-length = 79
91
+ indent-width = 4
92
+
93
+ target-version = "py312"
94
+
95
+ [tool.ruff.lint]
96
+ select = ["E4", "E7", "E9", "F"]
97
+ ignore = []
98
+
99
+ fixable = ["ALL"]
100
+ unfixable = []
101
+
102
+ dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
103
+
104
+ [tool.ruff.format]
105
+ quote-style = "double"
106
+
107
+ indent-style = "space"
108
+
109
+ skip-magic-trailing-comma = false
110
+
111
+ line-ending = "auto"
112
+
113
+ docstring-code-format = false
114
+
115
+ docstring-code-line-length = "dynamic"
116
+
117
+
118
+ [tool.pytest.ini_options]
119
+ minversion = "8.0"
120
+ asyncio_mode = "auto"
121
+ addopts = [
122
+ "-ra",
123
+ "-q",
124
+ "-vv",
125
+ "-s",
126
+ "--disable-warnings",
127
+ "--strict-markers",
128
+ "--cache-clear",
129
+ "--cov=.",
130
+ "--cov-report=xml",
131
+ "--cov-report=html",
132
+ "--cov=append",
133
+ "--cov-config=.coveragerc"
134
+ ]
135
+ markers = [
136
+ "unit: Unit tests.",
137
+ "integration: Integration tests.",
138
+ "e2e: End-to-End tests.",
139
+ "asyncio: Async functions."
140
+ ]
141
+ python_files = ["test_*.py", "*_test.py"]
142
+ python_classes = ["Test"]
143
+ python_functions = ["test"]
144
+ pythonpath = [".", "src"]
@@ -0,0 +1,84 @@
1
+ # generated by rye
2
+ # use `rye lock` or `rye sync` to update this lockfile
3
+ #
4
+ # last locked with the following flags:
5
+ # pre: false
6
+ # features: []
7
+ # all-features: false
8
+ # with-sources: false
9
+ # generate-hashes: false
10
+ # universal: false
11
+
12
+ -e file:.
13
+ annotated-types==0.7.0
14
+ # via pydantic
15
+ anyio==4.8.0
16
+ # via httpx
17
+ attrs==25.1.0
18
+ # via wmctrl
19
+ bracex==2.5.post1
20
+ # via wcmatch
21
+ bump-my-version==1.0.2
22
+ certifi==2025.1.31
23
+ # via httpcore
24
+ # via httpx
25
+ click==8.1.8
26
+ # via bump-my-version
27
+ # via rich-click
28
+ fancycompleter==0.9.1
29
+ # via pdbpp
30
+ h11==0.14.0
31
+ # via httpcore
32
+ httpcore==1.0.7
33
+ # via httpx
34
+ httpx==0.28.1
35
+ # via bump-my-version
36
+ idna==3.10
37
+ # via anyio
38
+ # via httpx
39
+ markdown-it-py==3.0.0
40
+ # via rich
41
+ mdurl==0.1.2
42
+ # via markdown-it-py
43
+ pdbpp==0.10.3
44
+ prompt-toolkit==3.0.50
45
+ # via questionary
46
+ pydantic==2.10.6
47
+ # via bump-my-version
48
+ # via message-van
49
+ # via pydantic-settings
50
+ pydantic-core==2.27.2
51
+ # via pydantic
52
+ pydantic-settings==2.8.1
53
+ # via bump-my-version
54
+ pygments==2.19.1
55
+ # via pdbpp
56
+ # via rich
57
+ pyrepl==0.9.0
58
+ # via fancycompleter
59
+ python-dotenv==1.0.1
60
+ # via pydantic-settings
61
+ questionary==2.1.0
62
+ # via bump-my-version
63
+ rich==13.9.4
64
+ # via bump-my-version
65
+ # via rich-click
66
+ rich-click==1.8.8
67
+ # via bump-my-version
68
+ ruff==0.9.10
69
+ sniffio==1.3.1
70
+ # via anyio
71
+ tomli==2.2.1
72
+ # via message-van
73
+ tomlkit==0.13.2
74
+ # via bump-my-version
75
+ typing-extensions==4.12.2
76
+ # via pydantic
77
+ # via pydantic-core
78
+ # via rich-click
79
+ wcmatch==10.0
80
+ # via bump-my-version
81
+ wcwidth==0.2.13
82
+ # via prompt-toolkit
83
+ wmctrl==0.5
84
+ # via pdbpp
@@ -0,0 +1,23 @@
1
+ # generated by rye
2
+ # use `rye lock` or `rye sync` to update this lockfile
3
+ #
4
+ # last locked with the following flags:
5
+ # pre: false
6
+ # features: []
7
+ # all-features: false
8
+ # with-sources: false
9
+ # generate-hashes: false
10
+ # universal: false
11
+
12
+ -e file:.
13
+ annotated-types==0.7.0
14
+ # via pydantic
15
+ pydantic==2.10.6
16
+ # via message-van
17
+ pydantic-core==2.27.2
18
+ # via pydantic
19
+ tomli==2.2.1
20
+ # via message-van
21
+ typing-extensions==4.12.2
22
+ # via pydantic
23
+ # via pydantic-core
@@ -0,0 +1,12 @@
1
+ from .domain.models import MessageVan
2
+ from .domain.models.message_van import init_handlers
3
+ from .service_layer import load_handlers
4
+
5
+
6
+ message_handlers = load_handlers()
7
+ init_handlers(message_handlers)
8
+
9
+
10
+ __all__ = [
11
+ "MessageVan",
12
+ ]
@@ -0,0 +1,8 @@
1
+ from .config_adapter import ConfigAdapter
2
+ from .signature_adapter import SignatureAdapter
3
+
4
+
5
+ __all__ = [
6
+ "ConfigAdapter",
7
+ "SignatureAdapter",
8
+ ]
@@ -0,0 +1,28 @@
1
+ from pathlib import Path
2
+
3
+ from message_van.adapters.mappers import dict_to_user_config
4
+ from message_van.adapters.models import UserConfig
5
+ from message_van.adapters.util import get_toml_parser
6
+ from message_van.config import USER_CONFIG_KEY
7
+
8
+
9
+ class ConfigAdapter:
10
+ _parser = get_toml_parser()
11
+
12
+ def __init__(self, config_path: Path):
13
+ self.config_path = config_path
14
+
15
+ def get(self) -> UserConfig:
16
+ config_dict = self._get()
17
+
18
+ return dict_to_user_config(config_dict)
19
+
20
+ def _get(self) -> dict:
21
+ pyproject_dict = self._get_pyproject_dict()
22
+
23
+ return pyproject_dict["tool"][USER_CONFIG_KEY]
24
+
25
+ def _get_pyproject_dict(self) -> dict:
26
+ contents = self.config_path.read_text()
27
+
28
+ return self._parser.loads(contents)
@@ -0,0 +1,6 @@
1
+ from .user_config_mapper import dict_to_user_config
2
+
3
+
4
+ __all__ = [
5
+ "dict_to_user_config",
6
+ ]
@@ -0,0 +1,5 @@
1
+ from message_van.adapters.models import UserConfig
2
+
3
+
4
+ def dict_to_user_config(config_dict: dict) -> UserConfig:
5
+ return UserConfig.model_validate(config_dict)
@@ -0,0 +1,6 @@
1
+ from .user_config import UserConfig
2
+
3
+
4
+ __all__ = [
5
+ "UserConfig",
6
+ ]
@@ -0,0 +1,9 @@
1
+ from pathlib import Path
2
+
3
+ from pydantic import BaseModel, Field
4
+
5
+ from message_van.config import HANDLERS_PATH_KEY
6
+
7
+
8
+ class UserConfig(BaseModel):
9
+ handlers_path: Path = Field(alias=HANDLERS_PATH_KEY)
@@ -0,0 +1,119 @@
1
+ import os
2
+ import importlib.util
3
+ import inspect
4
+ from collections.abc import Generator
5
+ from pathlib import Path
6
+ from typing import Any, List, Callable
7
+
8
+
9
+ from message_van.domain.models import (
10
+ Command,
11
+ Message,
12
+ MessageHandlerType,
13
+ MessageHandlerSignature,
14
+ )
15
+
16
+
17
+ class SignatureAdapter:
18
+ def __init__(self, path: Path):
19
+ self.path = path
20
+
21
+ def list(self) -> Generator[MessageHandlerSignature]:
22
+ module_paths = self.get_module_paths()
23
+ modules = self.import_modules(module_paths)
24
+
25
+ for func in list_modules(modules):
26
+ yield get_signature(func)
27
+
28
+ def get_module_paths(self) -> List[Path]:
29
+ return [module_path for module_path in self.list_module_paths()]
30
+
31
+ def list_module_paths(self) -> Generator[Path]:
32
+ for root_path, file_name in self.list_file_names():
33
+ if _is_module(file_name):
34
+ yield root_path / Path(file_name)
35
+
36
+ def list_file_names(self) -> Generator[tuple]:
37
+ for root, _, file_names in os.walk(self.path):
38
+ root_path = Path(root)
39
+
40
+ for file_name in file_names:
41
+ yield root_path, file_name
42
+
43
+ def import_modules(self, module_paths: List[Path]) -> Generator:
44
+ for file_path in module_paths:
45
+ yield self.import_module(file_path)
46
+
47
+ def import_module(self, file_path: str) -> Any:
48
+ module_name = os.path.relpath(file_path, self.path).replace(
49
+ os.sep, "."
50
+ )[:-3]
51
+ spec = importlib.util.spec_from_file_location(module_name, file_path)
52
+ module = importlib.util.module_from_spec(spec)
53
+ spec.loader.exec_module(module)
54
+
55
+ return module
56
+
57
+
58
+ def _is_module(file_name: str) -> bool:
59
+ return file_name.endswith(".py")
60
+
61
+
62
+ def list_modules(modules: list) -> Generator[Callable]:
63
+ for module in modules:
64
+ for func in list_public_functions(module):
65
+ yield func
66
+
67
+
68
+ def list_public_functions(module) -> Generator[Callable]:
69
+ for func in _list_functions(module):
70
+ if _is_public_function(func):
71
+ yield func
72
+
73
+
74
+ def _list_functions(module) -> Generator[Callable]:
75
+ for _, func in inspect.getmembers(module, inspect.isfunction):
76
+ yield func
77
+
78
+
79
+ def _is_public_function(func: Callable) -> bool:
80
+ name = func.__name__
81
+
82
+ return not name.startswith("_")
83
+
84
+
85
+ def get_signature(func) -> MessageHandlerSignature:
86
+ param = get_message_param(func)
87
+
88
+ return MessageHandlerSignature(
89
+ message_class_name=get_class_name(param),
90
+ message_handler=func,
91
+ type=get_handler_type(param),
92
+ )
93
+
94
+
95
+ def get_message_param(func):
96
+ for param in list_params(func):
97
+ if is_message_param(param):
98
+ return param
99
+
100
+
101
+ def list_params(func) -> Generator:
102
+ signature = inspect.signature(func)
103
+
104
+ yield from signature.parameters.values()
105
+
106
+
107
+ def is_message_param(param):
108
+ return issubclass(param.annotation, Message)
109
+
110
+
111
+ def get_class_name(param):
112
+ return param.annotation.__name__
113
+
114
+
115
+ def get_handler_type(param) -> MessageHandlerType:
116
+ if issubclass(param.annotation, Command):
117
+ return MessageHandlerType.COMMAND
118
+
119
+ return MessageHandlerType.EVENT
@@ -0,0 +1,6 @@
1
+ from .toml_parser import get_toml_parser
2
+
3
+
4
+ __all__ = [
5
+ "get_toml_parser",
6
+ ]
@@ -0,0 +1,20 @@
1
+ import sys
2
+ from types import ModuleType
3
+
4
+
5
+ MIN_PYTHON_VERSION_FOR_TOMLI = (3, 11)
6
+
7
+
8
+ def get_toml_parser() -> ModuleType:
9
+ if _is_python_version_compatible_with_tomllib():
10
+ import tomllib
11
+ else:
12
+ import tomli as tomllib
13
+
14
+ return tomllib
15
+
16
+
17
+ def _is_python_version_compatible_with_tomllib() -> bool:
18
+ current_python_version = sys.version_info
19
+
20
+ return current_python_version >= MIN_PYTHON_VERSION_FOR_TOMLI
@@ -0,0 +1,3 @@
1
+ USER_CONFIG_KEY = "message-van"
2
+
3
+ HANDLERS_PATH_KEY = "handlers-path"
File without changes
@@ -0,0 +1,8 @@
1
+ from .already_registered_handler_error import AlreadyRegisteredHandlerError
2
+ from .unknown_handler_error import UnknownHandlerError
3
+
4
+
5
+ __all__ = [
6
+ "AlreadyRegisteredHandlerError",
7
+ "UnknownHandlerError",
8
+ ]
@@ -0,0 +1,11 @@
1
+ _MSG_TEMPLATE = "Handler {handler} is already registered for {type}."
2
+
3
+
4
+ class AlreadyRegisteredHandlerError(Exception):
5
+ def __init__(self, existing_handler, handler_type):
6
+ self.existing_handler = existing_handler
7
+ self.handler_type = handler_type
8
+
9
+ msg = _MSG_TEMPLATE.format(handler=existing_handler, type=handler_type)
10
+
11
+ super().__init__(msg)
@@ -0,0 +1,10 @@
1
+ _MSG_TEMPLATE = "No handler registered for {type}."
2
+
3
+
4
+ class UnknownHandlerError(Exception):
5
+ def __init__(self, handler_type):
6
+ self.handler_type = handler_type
7
+
8
+ msg = _MSG_TEMPLATE.format(type=handler_type)
9
+
10
+ super().__init__(msg)
@@ -0,0 +1,32 @@
1
+ from .base import (
2
+ Command,
3
+ CommandHandler,
4
+ Event,
5
+ EventHandler,
6
+ Message,
7
+ MessageHandler,
8
+ )
9
+
10
+ from .message_handler_type import MessageHandlerType
11
+
12
+ from .handler_signature import MessageHandlerSignature
13
+
14
+ from .message_handlers import MessageHandlers
15
+ from .unit_of_work import UnitOfWork
16
+
17
+ from .message_van import MessageVan
18
+
19
+
20
+ __all__ = [
21
+ "Command",
22
+ "CommandHandler",
23
+ "Event",
24
+ "EventHandler",
25
+ "Message",
26
+ "MessageHandler",
27
+ "MessageHandlers",
28
+ "MessageHandlerSignature",
29
+ "MessageHandlerType",
30
+ "MessageVan",
31
+ "UnitOfWork",
32
+ ]
@@ -0,0 +1,18 @@
1
+ from .message import Message
2
+
3
+ from .command import Command
4
+ from .event import Event
5
+ from .message_handler import MessageHandler
6
+
7
+ from .command_handler import CommandHandler
8
+ from .event_handler import EventHandler
9
+
10
+
11
+ __all__ = [
12
+ "Command",
13
+ "CommandHandler",
14
+ "Event",
15
+ "EventHandler",
16
+ "MessageHandler",
17
+ "Message",
18
+ ]
@@ -0,0 +1,5 @@
1
+ from . import Message
2
+
3
+
4
+ class Command(Message):
5
+ """Base Command class."""
@@ -0,0 +1,14 @@
1
+ from typing import TYPE_CHECKING, Any, Awaitable, Callable
2
+
3
+ from . import Command
4
+
5
+
6
+ if TYPE_CHECKING:
7
+ from message_van.domain.models import MessageVan
8
+
9
+ message_van_type = MessageVan
10
+ else:
11
+ message_van_type = "MessageVan"
12
+
13
+
14
+ CommandHandler = Callable[[Command, message_van_type], Awaitable[Any]]
@@ -0,0 +1,5 @@
1
+ from . import Message
2
+
3
+
4
+ class Event(Message):
5
+ """Base Event class."""
@@ -0,0 +1,14 @@
1
+ from typing import TYPE_CHECKING, Awaitable, Callable
2
+
3
+ from . import Event
4
+
5
+
6
+ if TYPE_CHECKING:
7
+ from message_van.domain.models import MessageVan
8
+
9
+ message_van_type = MessageVan
10
+ else:
11
+ message_van_type = "MessageVan"
12
+
13
+
14
+ EventHandler = Callable[[Event, "MessageVan"], Awaitable[None]]
@@ -0,0 +1,5 @@
1
+ from pydantic import BaseModel
2
+
3
+
4
+ class Message(BaseModel):
5
+ """Base Message class."""
@@ -0,0 +1,14 @@
1
+ from typing import TYPE_CHECKING, Any, Awaitable, Callable
2
+
3
+ from . import Message
4
+
5
+
6
+ if TYPE_CHECKING:
7
+ from message_van.domain.models import MessageVan
8
+
9
+ message_van_type = MessageVan
10
+ else:
11
+ message_van_type = "MessageVan"
12
+
13
+
14
+ MessageHandler = Callable[[Message, message_van_type], Awaitable[Any | None]]
@@ -0,0 +1,12 @@
1
+ from typing import Callable
2
+
3
+ from pydantic import BaseModel
4
+
5
+
6
+ from . import MessageHandlerType
7
+
8
+
9
+ class MessageHandlerSignature(BaseModel):
10
+ message_class_name: str
11
+ message_handler: Callable
12
+ type: MessageHandlerType
@@ -0,0 +1,6 @@
1
+ from enum import Enum
2
+
3
+
4
+ class MessageHandlerType(Enum):
5
+ COMMAND = 0
6
+ EVENT = 1
@@ -0,0 +1,69 @@
1
+ from collections import defaultdict
2
+
3
+ from message_van.domain.exceptions import UnknownHandlerError
4
+ from message_van.domain.models import (
5
+ Command,
6
+ CommandHandler,
7
+ Event,
8
+ EventHandler,
9
+ MessageHandlerSignature,
10
+ MessageHandlerType,
11
+ Message,
12
+ )
13
+
14
+
15
+ class MessageHandlers:
16
+ _command_handlers: dict[str, CommandHandler]
17
+ _event_handlers: dict[str, list[EventHandler]]
18
+
19
+ def __init__(self):
20
+ self._command_handlers = {}
21
+ self._event_handlers = defaultdict(list)
22
+
23
+ def get_handler_for_command(self, command: Command) -> CommandHandler:
24
+ command_name = _get_message_name(command)
25
+
26
+ return self._get_handler_for_command(command_name)
27
+
28
+ def _get_handler_for_command(self, command_name: str) -> CommandHandler:
29
+ try:
30
+ return self._command_handlers[command_name]
31
+ except KeyError:
32
+ raise UnknownHandlerError(command_name)
33
+
34
+ def get_handlers_for_event(self, event: Event) -> list[EventHandler]:
35
+ event_name = _get_message_name(event)
36
+
37
+ return self._get_handlers_for_event(event_name)
38
+
39
+ def _get_handlers_for_event(self, event_name: str) -> list[EventHandler]:
40
+ try:
41
+ return self._event_handlers[event_name]
42
+ except KeyError:
43
+ raise UnknownHandlerError(event_name)
44
+
45
+ def register(self, signature: MessageHandlerSignature) -> None:
46
+ type_ = signature.type
47
+ class_name = signature.message_class_name
48
+ handler = signature.message_handler
49
+
50
+ if type_ == MessageHandlerType.COMMAND:
51
+ self._register_command(class_name, handler)
52
+ else:
53
+ self._register_event(class_name, handler)
54
+
55
+ def _register_command(
56
+ self,
57
+ class_name: str,
58
+ handler: CommandHandler,
59
+ ) -> None:
60
+ self._command_handlers[class_name] = handler
61
+
62
+ def _register_event(self, class_name: str, handler: EventHandler) -> None:
63
+ self._event_handlers[class_name].append(handler)
64
+
65
+
66
+ def _get_message_name(message: Message) -> str:
67
+ message_class = message.__class__
68
+
69
+ return message_class.__name__
@@ -0,0 +1,59 @@
1
+ from asyncio import create_task, gather
2
+ from types import TracebackType
3
+ from typing import Any
4
+
5
+ from message_van.domain.models import CommandHandler, EventHandler
6
+ from message_van.domain.models.base import Command, Event, Message
7
+
8
+ from . import UnitOfWork, MessageHandlers
9
+
10
+
11
+ class MessageVan:
12
+ uow: UnitOfWork
13
+
14
+ _message_handlers: MessageHandlers
15
+
16
+ def __init__(self, unit_of_work: UnitOfWork):
17
+ self.unit_of_work = unit_of_work
18
+
19
+ async def __aenter__(self) -> "MessageVan":
20
+ self.uow = await self.unit_of_work.__aenter__()
21
+
22
+ return self
23
+
24
+ async def __aexit__(
25
+ self,
26
+ exc_type: type[BaseException] | None,
27
+ exc_val: BaseException | None,
28
+ exc_tb: TracebackType | None,
29
+ ) -> bool | None:
30
+ await self.unit_of_work.__aexit__(exc_type, exc_val, exc_tb)
31
+
32
+ async def publish(self, message: Message) -> Any | None:
33
+ if isinstance(message, Command):
34
+ return await self.publish_command(message)
35
+
36
+ await self.publish_event(message)
37
+
38
+ async def publish_command(self, command: Command) -> Any:
39
+ handler = self._get_handler_for_command(command)
40
+
41
+ return await handler(command, self)
42
+
43
+ async def publish_event(self, event: Event) -> None:
44
+ tasks = [
45
+ create_task(handler(event, self))
46
+ for handler in self._get_handlers_for_event(event)
47
+ ]
48
+
49
+ await gather(*tasks)
50
+
51
+ def _get_handler_for_command(self, command: Command) -> CommandHandler:
52
+ return self._message_handlers.get_handler_for_command(command)
53
+
54
+ def _get_handlers_for_event(self, event: Event) -> list[EventHandler]:
55
+ return self._message_handlers.get_handlers_for_event(event)
56
+
57
+
58
+ def init_handlers(message_handlers: MessageHandlers) -> None:
59
+ MessageVan._message_handlers = message_handlers
@@ -0,0 +1,16 @@
1
+ from abc import ABC, abstractmethod
2
+ from types import TracebackType
3
+
4
+
5
+ class UnitOfWork(ABC):
6
+ @abstractmethod
7
+ async def __aenter__(self) -> "UnitOfWork":
8
+ """Enter the Unit of Work, and return its value."""
9
+
10
+ async def __aexit__(
11
+ self,
12
+ exc_type: type[BaseException] | None,
13
+ exc_val: BaseException | None,
14
+ exc_tb: TracebackType | None,
15
+ ) -> bool | None:
16
+ """Handle termination of the Unit of Work."""
@@ -0,0 +1,6 @@
1
+ from .service import load_handlers
2
+
3
+
4
+ __all__ = [
5
+ "load_handlers",
6
+ ]
@@ -0,0 +1,29 @@
1
+ from pathlib import Path
2
+
3
+
4
+ def load_handlers():
5
+ from message_van.adapters import SignatureAdapter
6
+ from message_van.domain.models import (
7
+ MessageHandlers,
8
+ )
9
+
10
+ message_handlers = MessageHandlers()
11
+
12
+ path = _get_handlers_path()
13
+ signatures = SignatureAdapter(path)
14
+
15
+ for signature in signatures.list():
16
+ message_handlers.register(signature)
17
+
18
+ return message_handlers
19
+
20
+
21
+ def _get_handlers_path() -> Path:
22
+ from message_van.adapters import ConfigAdapter
23
+
24
+ pyproject_path = Path("pyproject.toml")
25
+ config_adapter = ConfigAdapter(pyproject_path)
26
+
27
+ config = config_adapter.get()
28
+
29
+ return config.handlers_path