django-queuebie 0.3.6__py3-none-any.whl

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,192 @@
1
+ Metadata-Version: 2.4
2
+ Name: django-queuebie
3
+ Version: 0.3.6
4
+ Summary: A simple and synchronous message queue for commands and events for Django
5
+ Project-URL: Homepage, https://github.com/ambient-innovation/django-queuebie/
6
+ Project-URL: Documentation, https://django-queuebie.readthedocs.io/en/latest/index.html
7
+ Project-URL: Maintained by, https://ambient.digital/
8
+ Project-URL: Bugtracker, https://github.com/ambient-innovation/django-queuebie/issues
9
+ Project-URL: Changelog, https://django-queuebie.readthedocs.io/en/latest/features/changelog.html
10
+ Author-email: Ambient Digital <hello@ambient.digital>
11
+ License: MIT License
12
+
13
+ Copyright (c) 2025 Ambient Innovation: GmbH
14
+
15
+ Permission is hereby granted, free of charge, to any person obtaining a copy
16
+ of this software and associated documentation files (the "Software"), to deal
17
+ in the Software without restriction, including without limitation the rights
18
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
19
+ copies of the Software, and to permit persons to whom the Software is
20
+ furnished to do so, subject to the following conditions:
21
+
22
+ The above copyright notice and this permission notice shall be included in all
23
+ copies or substantial portions of the Software.
24
+
25
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
30
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31
+ SOFTWARE.
32
+ License-File: LICENSE
33
+ License-File: LICENSE.md
34
+ Classifier: Development Status :: 4 - Beta
35
+ Classifier: Environment :: Web Environment
36
+ Classifier: Framework :: Django
37
+ Classifier: Framework :: Django :: 4.2
38
+ Classifier: Framework :: Django :: 5.1
39
+ Classifier: Framework :: Django :: 5.2
40
+ Classifier: Intended Audience :: Developers
41
+ Classifier: License :: OSI Approved :: MIT License
42
+ Classifier: Natural Language :: English
43
+ Classifier: Operating System :: OS Independent
44
+ Classifier: Programming Language :: Python
45
+ Classifier: Programming Language :: Python :: 3
46
+ Classifier: Programming Language :: Python :: 3.10
47
+ Classifier: Programming Language :: Python :: 3.11
48
+ Classifier: Programming Language :: Python :: 3.12
49
+ Classifier: Programming Language :: Python :: 3.13
50
+ Classifier: Topic :: Utilities
51
+ Requires-Python: >=3.10
52
+ Requires-Dist: django>=4.2
53
+ Description-Content-Type: text/markdown
54
+
55
+ [![PyPI release](https://img.shields.io/pypi/v/django-queuebie.svg)](https://pypi.org/project/django-queuebie/)
56
+ [![Downloads](https://static.pepy.tech/badge/django-queuebie)](https://pepy.tech/project/django-queuebie)
57
+ [![Coverage](https://img.shields.io/badge/Coverage-100.0%25-success)](https://github.com/ambient-innovation/django-queuebie/actions?workflow=CI)
58
+ [![Linting](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
59
+ [![Coding Style](https://img.shields.io/badge/code%20style-Ruff-000000.svg)](https://github.com/astral-sh/ruff)
60
+ [![Documentation Status](https://readthedocs.org/projects/django-queuebie/badge/?version=latest)](https://django-queuebie.readthedocs.io/en/latest/?badge=latest)
61
+
62
+ A simple and synchronous message queue for commands and events for Django.
63
+
64
+ [PyPI](https://pypi.org/project/django-queuebie/) | [GitHub](https://github.com/ambient-innovation/django-queuebie) | [Full documentation](https://django-queuebie.readthedocs.io/en/latest/index.html)
65
+
66
+ Creator & Maintainer: [Ambient Digital](https://ambient.digital/)
67
+
68
+ ## Features
69
+
70
+ * Split up your business logic in commands and events
71
+ * Commands are imperatives telling your system what to do, events reflect that something has happened
72
+ * Register light-weight functions via a decorator to listen to your commands and events
73
+ * Message handlers receive the context of the message (command or event), providing an explicit API
74
+ * No magic, no side effects since the queue works synchronously
75
+
76
+ ```python
77
+ import dataclasses
78
+
79
+ from queuebie.runner import handle_message
80
+ from queuebie.messages import Command, Event
81
+ from queuebie import message_registry
82
+
83
+
84
+ # Example command
85
+ @dataclasses.dataclass(kw_only=True)
86
+ class BuyProduct(Command):
87
+ product_id: int
88
+ customer_id: int
89
+ price: float
90
+ currency: str
91
+
92
+
93
+ # Example event
94
+ @dataclasses.dataclass(kw_only=True)
95
+ class ProductBought(Event):
96
+ product_id: int
97
+ customer_id: int
98
+
99
+
100
+ # Example handler
101
+ @message_registry.register_command(BuyProduct)
102
+ def handle_buy_product(context: BuyProduct) -> Event:
103
+ # Here lives your business logic
104
+
105
+ return ProductBought(
106
+ product_id=context.product_id,
107
+ customer_id=context.customer_id,
108
+ )
109
+
110
+
111
+ # Start queue and process messages
112
+ handle_message(
113
+ BuyProduct(
114
+ product_id=product.id,
115
+ customer_id=customer.id,
116
+ price=12.99,
117
+ currency="EUR",
118
+ )
119
+ )
120
+ ```
121
+
122
+ ## Installation
123
+
124
+ - Install the package via pip:
125
+
126
+ `pip install django_queuebie`
127
+
128
+ or via uv:
129
+
130
+ `uv add django_queuebie`
131
+
132
+ - Add module to `INSTALLED_APPS` within the main django `settings.py`:
133
+
134
+ ```python
135
+ INSTALLED_APPS = (
136
+ # ...
137
+ "queuebie",
138
+ )
139
+ ```
140
+
141
+ ### Publish to ReadTheDocs.io
142
+
143
+ - Fetch the latest changes in GitHub mirror and push them
144
+ - Trigger new build at ReadTheDocs.io (follow instructions in admin panel at RTD) if the GitHub webhook is not yet set
145
+ up.
146
+
147
+ ### Preparation and building
148
+
149
+ This package uses [uv](https://github.com/astral-sh/uv) for dependency management and building.
150
+
151
+ - Update documentation about new/changed functionality
152
+
153
+ - Update the `CHANGES.md`
154
+
155
+ - Increment version in main `__init__.py`
156
+
157
+ - Create pull request / merge to "main"
158
+
159
+ - This project uses uv to publish to PyPI. This will create distribution files in the `dist/` directory.
160
+
161
+ ```bash
162
+ uv build
163
+ ```
164
+
165
+ ### Publishing to PyPI
166
+
167
+ To publish to the production PyPI:
168
+
169
+ ```bash
170
+ uv publish
171
+ ```
172
+
173
+ To publish to TestPyPI first (recommended for testing):
174
+
175
+ ```bash
176
+ uv publish --publish-url https://test.pypi.org/legacy/
177
+ ```
178
+
179
+ You can then test the installation from TestPyPI:
180
+
181
+ ```bash
182
+ uv pip install --index-url https://test.pypi.org/simple/ ambient-package-update
183
+ ```
184
+
185
+ ### Maintenance
186
+
187
+ Please note that this package supports the [ambient-package-update](https://pypi.org/project/ambient-package-update/).
188
+ So you don't have to worry about the maintenance of this package. This updater is rendering all important
189
+ configuration and setup files. It works similar to well-known updaters like `pyupgrade` or `django-upgrade`.
190
+
191
+ To run an update, refer to the [documentation page](https://pypi.org/project/ambient-package-update/)
192
+ of the "ambient-package-update".
@@ -0,0 +1,18 @@
1
+ queuebie/__init__.py,sha256=_updQVD0CxDYYJ-6lQyY6icYwXfB8Lih6hlxK9_r_Rk,233
2
+ queuebie/apps.py,sha256=dTNk2xGvasXJncLUbbIjVQZrX7VYQsIdv_7ToFPy5b8,477
3
+ queuebie/database_blocker.py,sha256=8yszE7wSfVJJ-IdTB-xO4qDLk5AI1k2pjkKVYM4JDi8,766
4
+ queuebie/exceptions.py,sha256=B_vsZBEMqpWsxUp5RrokabiZOYfNEbV0nGxhhX0o5NY,711
5
+ queuebie/logger.py,sha256=OWO9yiNxfnhUqejoR6RCUueKSWYzsMtfUBCmxAuAksk,244
6
+ queuebie/messages.py,sha256=JcC7QxWzWllxDkwbYGefhaL1YWT_froOXa1NDugbGCM,1022
7
+ queuebie/registry.py,sha256=ipD7i2jtookHAYU1iVXII071SaaHLiNmA81-Pf6sKkY,6163
8
+ queuebie/runner.py,sha256=yAVxNEPj400Y9rOLBr_3HrThnoremlBpoPFG-sK_J5k,2626
9
+ queuebie/settings.py,sha256=CAUldgjCH-coTIAPctaYDRWmoZXb2NcWZlaMBxec0Nw,850
10
+ queuebie/utils.py,sha256=aeHOkILLpPrkA9bnDmsR1YF40KLdSlKqk15ItmLTZW4,997
11
+ queuebie/management/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
+ queuebie/management/commands/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
13
+ queuebie/management/commands/clear_queuebie_registry.py,sha256=Vx4JLSo9-i7gK0YeNP5F_50TsyjEP4i4plYK_byHj3I,392
14
+ django_queuebie-0.3.6.dist-info/METADATA,sha256=l07peQktrO71P8csgbIIcTuc7gbxPmr6BMEjBhb0NMo,6937
15
+ django_queuebie-0.3.6.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
16
+ django_queuebie-0.3.6.dist-info/licenses/LICENSE,sha256=VCMRQqZBDEG5HsJdp-Ps6a3-GFnpQZPzitGMRUHdgso,1093
17
+ django_queuebie-0.3.6.dist-info/licenses/LICENSE.md,sha256=SiLpAPFRchFM_cDmWQIdItf_xPR6jeYCAaNUgpKWxV8,1102
18
+ django_queuebie-0.3.6.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Ambient Digital
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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Ambient Innovation: GmbH
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.
queuebie/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """A simple and synchronous message queue for commands and events for Django"""
2
+
3
+ __version__ = "0.3.6"
4
+
5
+ from queuebie.registry import MessageRegistry
6
+
7
+ # Initialise global message registry
8
+ message_registry = MessageRegistry()
queuebie/apps.py ADDED
@@ -0,0 +1,15 @@
1
+ from django.apps import AppConfig
2
+
3
+ from queuebie import message_registry
4
+
5
+
6
+ class QueuebieConfig(AppConfig):
7
+ default_auto_field = "django.db.models.BigAutoField"
8
+ name = "queuebie"
9
+
10
+ def ready(self):
11
+ super().ready()
12
+
13
+ # Register all decorated functions before they get imported by something else which will break the
14
+ # registration process since decorators are only executed the first time
15
+ message_registry.autodiscover()
@@ -0,0 +1,25 @@
1
+ from unittest.mock import patch
2
+
3
+ from django.db import connections
4
+
5
+
6
+ class DatabaseAccessDeniedError(RuntimeError):
7
+ def __init__(self):
8
+ super().__init__("Database access is disabled in this context.")
9
+
10
+
11
+ class BlockDatabaseAccess:
12
+ def __enter__(self):
13
+ # Patcht alle aktiven DB-Verbindungen, sodass jede Query fehlschlägt
14
+ self.patches = [
15
+ patch.object(connections[alias], "cursor", side_effect=self._raise_error) for alias in connections
16
+ ]
17
+ for p in self.patches:
18
+ p.start()
19
+
20
+ def __exit__(self, exc_type, exc_value, traceback):
21
+ for p in self.patches:
22
+ p.stop()
23
+
24
+ def _raise_error(self, *args, **kwargs):
25
+ raise DatabaseAccessDeniedError()
queuebie/exceptions.py ADDED
@@ -0,0 +1,17 @@
1
+ class RegisterWrongMessageTypeError(TypeError):
2
+ def __init__(self, *, message_name: str, decoratee_name: str):
3
+ super().__init__(
4
+ f'Trying to register message function of wrong type: "{message_name}" on handler "{decoratee_name}".'
5
+ )
6
+
7
+
8
+ class RegisterOutOfScopeCommandError(TypeError):
9
+ def __init__(self, *, message_name: str, decoratee_name: str):
10
+ super().__init__(
11
+ f'Trying to register a command from another scope/app: "{message_name}" on handler "{decoratee_name}".'
12
+ )
13
+
14
+
15
+ class InvalidMessageTypeError(TypeError):
16
+ def __init__(self, *, class_name: str):
17
+ super().__init__(f'"{class_name}" is not an Event or Command')
queuebie/logger.py ADDED
@@ -0,0 +1,10 @@
1
+ import logging
2
+
3
+ from queuebie.settings import get_queuebie_logger_name
4
+
5
+
6
+ def get_logger() -> logging.Logger:
7
+ """
8
+ Returns an instance of a queuebie Django logger
9
+ """
10
+ return logging.getLogger(get_queuebie_logger_name())
File without changes
File without changes
@@ -0,0 +1,13 @@
1
+ from django.core.cache import cache
2
+ from django.core.management.base import BaseCommand
3
+
4
+ from queuebie.logger import get_logger
5
+ from queuebie.settings import get_queuebie_cache_key
6
+
7
+
8
+ class Command(BaseCommand):
9
+ def handle(self, *args, **options):
10
+ cache.delete(get_queuebie_cache_key())
11
+
12
+ logger = get_logger()
13
+ logger.info("Queuebie registry cleared.")
queuebie/messages.py ADDED
@@ -0,0 +1,39 @@
1
+ import abc
2
+ import uuid
3
+
4
+
5
+ class Message(abc.ABC):
6
+ """
7
+ Base class for all commands and events.
8
+ """
9
+
10
+ uuid: str
11
+
12
+ def __post_init__(self):
13
+ super().__init__()
14
+ # Hier kannst du zusätzliche Initialisierungslogik hinzufügen, falls nötig
15
+ self.uuid = str(uuid.uuid4())
16
+
17
+ def __str__(self) -> str:
18
+ return f"{self.__class__} ({self.uuid})"
19
+
20
+ @classmethod
21
+ def module_path(cls) -> str:
22
+ return f"{cls.__module__}.{cls.__qualname__}"
23
+
24
+
25
+ class Command(Message):
26
+ """
27
+ Commands are messages which prompt the system to do something.
28
+ Are always written in present tense: "CreateInvoice".
29
+ Every instance has to be decorated as "@dataclass(kw_only=True)".
30
+ # todo: check that messages are dataclasses?
31
+ """
32
+
33
+
34
+ class Event(Message):
35
+ """
36
+ Events are the results of a command.
37
+ Are always written in past tense: "InvoiceCreated".
38
+ Every instance has to be decorated as "@dataclass(kw_only=True)".
39
+ """
queuebie/registry.py ADDED
@@ -0,0 +1,153 @@
1
+ import dataclasses
2
+ import importlib
3
+ import json
4
+ import os
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ from django.apps import apps
9
+ from django.core.cache import cache
10
+
11
+ from queuebie.exceptions import RegisterOutOfScopeCommandError, RegisterWrongMessageTypeError
12
+ from queuebie.logger import get_logger
13
+ from queuebie.messages import Command, Event
14
+ from queuebie.settings import get_queuebie_app_base_path, get_queuebie_cache_key, get_queuebie_strict_mode
15
+ from queuebie.utils import is_part_of_app, unique_append_to_inner_list
16
+
17
+
18
+ @dataclasses.dataclass(kw_only=True)
19
+ class FunctionDefinition:
20
+ module: str
21
+ name: str
22
+
23
+
24
+ class MessageRegistry:
25
+ """
26
+ Singleton for registering messages classes in.
27
+ """
28
+
29
+ # TODO: make message registry generic and put in toolbox
30
+ _instance: "MessageRegistry" = None
31
+
32
+ def __init__(self):
33
+ self.command_dict: dict = {}
34
+ self.event_dict: dict = {}
35
+
36
+ def __new__(cls, *args, **kwargs):
37
+ if not cls._instance:
38
+ cls._instance = super().__new__(cls)
39
+ return cls._instance
40
+
41
+ def register_command(self, *, command: type[Command]):
42
+ def decorator(decoratee):
43
+ # Ensure that registered message is of correct type
44
+ if not (issubclass(command, Command)):
45
+ raise RegisterWrongMessageTypeError(message_name=command.__name__, decoratee_name=decoratee.__name__)
46
+
47
+ if get_queuebie_strict_mode() and not is_part_of_app(function=decoratee, class_type=command):
48
+ raise RegisterOutOfScopeCommandError(message_name=command.__name__, decoratee_name=decoratee.__name__)
49
+
50
+ # Add decoratee to dependency list
51
+ function_definition = dataclasses.asdict(
52
+ FunctionDefinition(module=decoratee.__module__, name=decoratee.__name__)
53
+ )
54
+ self.command_dict = unique_append_to_inner_list(
55
+ data=self.command_dict, key=command.module_path(), value=function_definition
56
+ )
57
+
58
+ logger = get_logger()
59
+ logger.debug("Registered command '%s'", decoratee.__name__)
60
+
61
+ # Return decoratee
62
+ return decoratee
63
+
64
+ return decorator
65
+
66
+ def register_event(self, *, event: type[Event]):
67
+ # TODO: create a generic registry function and "inherit" here from it
68
+ def decorator(decoratee):
69
+ # Ensure that registered message is of correct type
70
+ if not (issubclass(event, Event)):
71
+ raise RegisterWrongMessageTypeError(message_name=event.__name__, decoratee_name=decoratee.__name__)
72
+
73
+ # Add decoratee to dependency list
74
+ function_definition = dataclasses.asdict(
75
+ FunctionDefinition(module=decoratee.__module__, name=decoratee.__name__)
76
+ )
77
+ self.event_dict = unique_append_to_inner_list(
78
+ data=self.event_dict, key=event.module_path(), value=function_definition
79
+ )
80
+
81
+ logger = get_logger()
82
+ logger.debug("Registered event '%s'", decoratee.__name__)
83
+
84
+ # Return decoratee
85
+ return decoratee
86
+
87
+ return decorator
88
+
89
+ def autodiscover(self) -> None: # noqa: C901
90
+ """
91
+ Detects message registries which have been registered via the "register_*" decorator.
92
+ """
93
+ # Fetch registered handlers from cache if possible
94
+ self.command_dict, self.event_dict = self._load_handlers_from_cache()
95
+
96
+ # If the handlers were cached, we don't have to go through the file system
97
+ if len(self.command_dict) > 0 and len(self.event_dict) > 0:
98
+ return
99
+
100
+ # Project directory
101
+ project_path = get_queuebie_app_base_path()
102
+ logger = get_logger()
103
+
104
+ for app_config in apps.get_app_configs():
105
+ app_path = Path(app_config.path).resolve()
106
+
107
+ # If it's not a local app, we don't care
108
+ if project_path not in app_path.parents:
109
+ continue
110
+
111
+ for message_type in ("commands", "events"):
112
+ try:
113
+ for module in os.listdir(app_path / "handlers" / message_type):
114
+ if module[-3:] != ".py":
115
+ continue
116
+ module_name = module.replace(".py", "")
117
+ module_path = f"{app_config.name}.handlers.{message_type}.{module_name}"
118
+ sys_module = sys.modules.get(module_path)
119
+ if sys_module:
120
+ importlib.reload(sys_module)
121
+ else:
122
+ importlib.import_module(module_path)
123
+ logger.debug(f'"{module_path}" imported.')
124
+ except FileNotFoundError:
125
+ pass
126
+
127
+ # Log to shell which functions have been detected
128
+ logger.debug("Message autodiscovery running for commands...")
129
+ for command in self.command_dict:
130
+ handler_list = ", ".join(str(x) for x in self.command_dict[command])
131
+ logger.debug(f"* {command}: [{handler_list}]")
132
+ logger.debug("Message autodiscovery running for events...")
133
+ for event in self.event_dict:
134
+ handler_list = ", ".join(str(x) for x in self.event_dict[event])
135
+ logger.debug(f"* {event}: [{handler_list}]")
136
+
137
+ logger.debug(f"{len(self.command_dict) + len(self.event_dict)} message handlers detected.\n")
138
+
139
+ # Update cache
140
+ cache.set(get_queuebie_cache_key(), json.dumps({"commands": self.command_dict, "events": self.event_dict}))
141
+
142
+ def _load_handlers_from_cache(self) -> tuple[dict, dict]:
143
+ """
144
+ Get registered handler definitions from Django cache
145
+ """
146
+ cached_data = cache.get(get_queuebie_cache_key())
147
+ if cached_data is None:
148
+ return {}, {}
149
+ json_data = json.loads(cached_data)
150
+ cached_commands = json_data.get("commands", None)
151
+ cached_events = json_data.get("events", None)
152
+
153
+ return cached_commands, cached_events
queuebie/runner.py ADDED
@@ -0,0 +1,63 @@
1
+ import importlib
2
+ from contextlib import nullcontext
3
+
4
+ from django.db import transaction
5
+
6
+ from queuebie import message_registry
7
+ from queuebie.database_blocker import BlockDatabaseAccess
8
+ from queuebie.exceptions import InvalidMessageTypeError
9
+ from queuebie.logger import get_logger
10
+ from queuebie.messages import Command, Event, Message
11
+ from queuebie.settings import get_queuebie_strict_mode
12
+
13
+
14
+ def handle_message(messages: Message | list[Message]) -> None:
15
+ queue: list[Message] = messages if isinstance(messages, list) else [messages]
16
+
17
+ for message in queue:
18
+ if not isinstance(message, (Command, Event)):
19
+ raise InvalidMessageTypeError(class_name=message.__class__.__name__)
20
+
21
+ # Run auto-registry
22
+ message_registry.autodiscover()
23
+
24
+ with transaction.atomic():
25
+ while queue:
26
+ message = queue.pop(0)
27
+ if isinstance(message, Command):
28
+ handler_list = message_registry.command_dict.get(message.module_path(), [])
29
+ block_db_access = False
30
+ else:
31
+ handler_list = message_registry.event_dict.get(message.module_path(), [])
32
+ block_db_access = True if get_queuebie_strict_mode() else False
33
+
34
+ new_messages = _process_message(handler_list=handler_list, message=message, block_db_access=block_db_access)
35
+ queue.extend(new_messages)
36
+
37
+
38
+ def _process_message(*, handler_list: list, message: [Command, Event], block_db_access: bool) -> list[Message]:
39
+ """
40
+ Handler to process messages of type "Command"
41
+ """
42
+ logger = get_logger()
43
+ messages = []
44
+
45
+ for handler in handler_list:
46
+ try:
47
+ logger.debug(
48
+ f"Handling command '{message.module_path()}' ({message.uuid}) with handler '{handler['name']}'."
49
+ )
50
+ module = importlib.import_module(handler["module"])
51
+ handler_function = getattr(module, handler["name"])
52
+ with BlockDatabaseAccess() if block_db_access else nullcontext():
53
+ handler_messages = handler_function(context=message) or []
54
+ handler_messages = handler_messages if isinstance(handler_messages, list) else [handler_messages]
55
+ if len(handler_messages) > 0:
56
+ messages.extend(handler_messages)
57
+ uuid_list = [f"{m!s}" for m in handler_messages]
58
+ logger.debug(f"New messages: {uuid_list!s}")
59
+ except Exception as e:
60
+ logger.debug(f"Exception handling command {message.module_path()}: {e!s}")
61
+ raise e from e
62
+
63
+ return messages
queuebie/settings.py ADDED
@@ -0,0 +1,32 @@
1
+ from pathlib import Path
2
+
3
+ from django.conf import settings
4
+
5
+
6
+ def get_queuebie_app_base_path() -> Path | str:
7
+ """
8
+ Base path of the application queuebie should look for registered handlers.
9
+ :return:
10
+ """
11
+ return getattr(settings, "QUEUEBIE_APP_BASE_PATH", getattr(settings, "BASE_PATH", None))
12
+
13
+
14
+ def get_queuebie_cache_key() -> str:
15
+ """
16
+ Cache key to store registered handlers in.
17
+ """
18
+ return getattr(settings, "QUEUEBIE_CACHE_KEY", "queuebie")
19
+
20
+
21
+ def get_queuebie_logger_name() -> str:
22
+ """
23
+ Django logger name
24
+ """
25
+ return getattr(settings, "QUEUEBIE_LOGGER_NAME", "queuebie")
26
+
27
+
28
+ def get_queuebie_strict_mode() -> bool:
29
+ """
30
+ Determines if commands are allowed to be imported across Django app borders.
31
+ """
32
+ return getattr(settings, "QUEUEBIE_STRICT_MODE", True)
queuebie/utils.py ADDED
@@ -0,0 +1,30 @@
1
+ from collections.abc import Callable
2
+
3
+ from django.apps import apps
4
+
5
+
6
+ def is_part_of_app(*, function: Callable, class_type: type) -> bool:
7
+ """
8
+ Checks if a class belongs to the same Django app as the given function.
9
+ """
10
+
11
+ # Get the app configurations for the class and function
12
+ class_app_config = apps.get_containing_app_config(class_type.__module__)
13
+ function_app_config = apps.get_containing_app_config(function.__module__)
14
+
15
+ # Check if both belong to the same app
16
+ return class_app_config == function_app_config
17
+
18
+
19
+ def unique_append_to_inner_list(*, data: dict, key: str | int, value) -> dict:
20
+ """
21
+ Inserts "value" in the dictionary "data" on "key".
22
+ If "key" doesn't exist yet, it will create a new list containing "value".
23
+ If "value" at "key" already exists, it won't be appended.
24
+ """
25
+ if key not in data:
26
+ data[key] = [value]
27
+ elif value not in data[key]:
28
+ data[key].append(value)
29
+
30
+ return data