stinger-python-utils 0.1.3__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,210 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
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
+ # uv
30
+ .uv
31
+
32
+ # PyInstaller
33
+ # Usually these files are written by a python script from a template
34
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
35
+ *.manifest
36
+ *.spec
37
+
38
+ # Installer logs
39
+ pip-log.txt
40
+ pip-delete-this-directory.txt
41
+
42
+ # Unit test / coverage reports
43
+ htmlcov/
44
+ .tox/
45
+ .nox/
46
+ .coverage
47
+ .coverage.*
48
+ .cache
49
+ nosetests.xml
50
+ coverage.xml
51
+ *.cover
52
+ *.py.cover
53
+ .hypothesis/
54
+ .pytest_cache/
55
+ cover/
56
+
57
+ # Translations
58
+ *.mo
59
+ *.pot
60
+
61
+ # Django stuff:
62
+ *.log
63
+ local_settings.py
64
+ db.sqlite3
65
+ db.sqlite3-journal
66
+
67
+ # Flask stuff:
68
+ instance/
69
+ .webassets-cache
70
+
71
+ # Scrapy stuff:
72
+ .scrapy
73
+
74
+ # Sphinx documentation
75
+ docs/_build/
76
+
77
+ # PyBuilder
78
+ .pybuilder/
79
+ target/
80
+
81
+ # Jupyter Notebook
82
+ .ipynb_checkpoints
83
+
84
+ # IPython
85
+ profile_default/
86
+ ipython_config.py
87
+
88
+ # pyenv
89
+ # For a library or package, you might want to ignore these files since the code is
90
+ # intended to run in multiple environments; otherwise, check them in:
91
+ # .python-version
92
+
93
+ # pipenv
94
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
95
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
96
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
97
+ # install all needed dependencies.
98
+ #Pipfile.lock
99
+
100
+ # UV
101
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
102
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
103
+ # commonly ignored for libraries.
104
+ #uv.lock
105
+
106
+ # poetry
107
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
108
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
109
+ # commonly ignored for libraries.
110
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
111
+ #poetry.lock
112
+ #poetry.toml
113
+
114
+ # pdm
115
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
116
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
117
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
118
+ #pdm.lock
119
+ #pdm.toml
120
+ .pdm-python
121
+ .pdm-build/
122
+
123
+ # pixi
124
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
125
+ #pixi.lock
126
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
127
+ # in the .venv directory. It is recommended not to include this directory in version control.
128
+ .pixi
129
+
130
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
131
+ __pypackages__/
132
+
133
+ # Celery stuff
134
+ celerybeat-schedule
135
+ celerybeat.pid
136
+
137
+ # SageMath parsed files
138
+ *.sage.py
139
+
140
+ # Environments
141
+ .env
142
+ .envrc
143
+ .venv
144
+ env/
145
+ venv/
146
+ ENV/
147
+ env.bak/
148
+ venv.bak/
149
+
150
+ # Spyder project settings
151
+ .spyderproject
152
+ .spyproject
153
+
154
+ # Rope project settings
155
+ .ropeproject
156
+
157
+ # mkdocs documentation
158
+ /site
159
+
160
+ # mypy
161
+ .mypy_cache/
162
+ .dmypy.json
163
+ dmypy.json
164
+
165
+ # Pyre type checker
166
+ .pyre/
167
+
168
+ # pytype static type analyzer
169
+ .pytype/
170
+
171
+ # Cython debug symbols
172
+ cython_debug/
173
+
174
+ # PyCharm
175
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
176
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
177
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
178
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
179
+ #.idea/
180
+
181
+ # Abstra
182
+ # Abstra is an AI-powered process automation framework.
183
+ # Ignore directories containing user credentials, local state, and settings.
184
+ # Learn more at https://abstra.io/docs
185
+ .abstra/
186
+
187
+ # Visual Studio Code
188
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
189
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
190
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
191
+ # you could uncomment the following to ignore the entire vscode folder
192
+ # .vscode/
193
+
194
+ # Ruff stuff:
195
+ .ruff_cache/
196
+
197
+ # PyPI configuration file
198
+ .pypirc
199
+
200
+ # Cursor
201
+ # Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
202
+ # exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
203
+ # refer to https://docs.cursor.com/context/ignore-files
204
+ .cursorignore
205
+ .cursorindexingignore
206
+
207
+ # Marimo
208
+ marimo/_static/
209
+ marimo/_lsp/
210
+ __marimo__/
@@ -0,0 +1,4 @@
1
+ # Manage Python versions and dependencies with uv
2
+ # https://docs.astral.sh/uv/
3
+
4
+ Python = "3.7"
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Jacob Brunson
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,13 @@
1
+ Metadata-Version: 2.4
2
+ Name: stinger-python-utils
3
+ Version: 0.1.3
4
+ Summary: Common utilities for Stinger Python services.
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.7
8
+ Requires-Dist: pydantic>=2.5.3
9
+ Requires-Dist: pyqttier>=0.2.0
10
+ Description-Content-Type: text/markdown
11
+
12
+ # stinger-python-utils
13
+ Common code needed for stinger python generations
@@ -0,0 +1,2 @@
1
+ # stinger-python-utils
2
+ Common code needed for stinger python generations
@@ -0,0 +1,24 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "stinger-python-utils"
7
+ version = "0.1.3"
8
+ description = "Common utilities for Stinger Python services."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.7"
12
+ dependencies = [
13
+ "pydantic>=2.5.3",
14
+ "pyqttier>=0.2.0",
15
+ ]
16
+
17
+ [tool.uv]
18
+ managed = true
19
+
20
+ [dependency-groups]
21
+ dev = [
22
+ "black>=23.3.0",
23
+ "mypy>=1.4.1",
24
+ ]
@@ -0,0 +1,191 @@
1
+ from pyqttier.message import Message
2
+ from pydantic import BaseModel
3
+ from typing import Union, Optional
4
+ import uuid
5
+
6
+
7
+ class MessageCreator:
8
+
9
+ @classmethod
10
+ def signal_message(cls, topic: str, payload: BaseModel) -> Message:
11
+ return Message(
12
+ topic=topic,
13
+ payload=payload.model_dump_json(by_alias=True).encode("utf-8"),
14
+ qos=1,
15
+ retain=False,
16
+ )
17
+
18
+ @classmethod
19
+ def status_message(
20
+ cls, topic, status_message: BaseModel, expiry_seconds: int
21
+ ) -> Message:
22
+ return Message(
23
+ topic=topic,
24
+ payload=status_message.model_dump_json(by_alias=True).encode("utf-8"),
25
+ qos=1,
26
+ retain=True,
27
+ message_expiry_interval=expiry_seconds,
28
+ )
29
+
30
+ @classmethod
31
+ def error_response_message(
32
+ cls,
33
+ topic: str,
34
+ return_code: int,
35
+ correlation_id: Union[str, bytes, None] = None,
36
+ debug_info: Optional[str] = None,
37
+ ) -> Message:
38
+ """
39
+ This could be used for a response to a request, but where there was an error fulfilling the request.
40
+ """
41
+ msg_obj = Message(
42
+ topic=topic,
43
+ payload=b"{}",
44
+ qos=1,
45
+ retain=False,
46
+ correlation_data=(
47
+ correlation_id.encode("utf-8")
48
+ if isinstance(correlation_id, str)
49
+ else correlation_id
50
+ ),
51
+ user_properties={"ReturnCode": str(return_code)},
52
+ )
53
+ if (
54
+ debug_info is not None and msg_obj.user_properties is not None
55
+ ): # user_properties should never be None here, but checking to satisfy type checker
56
+ msg_obj.user_properties["DebugInfo"] = debug_info
57
+ return msg_obj
58
+
59
+ @classmethod
60
+ def response_message(
61
+ cls,
62
+ response_topic: str,
63
+ response_obj: BaseModel | str | bytes,
64
+ return_code: int,
65
+ correlation_id: Union[str, bytes, None] = None,
66
+ ) -> Message:
67
+ """
68
+ This could be used for a successful response to a request.
69
+ """
70
+ if isinstance(response_obj, BaseModel):
71
+ payload = response_obj.model_dump_json(by_alias=True).encode("utf-8")
72
+ elif isinstance(response_obj, str):
73
+ payload = response_obj.encode("utf-8")
74
+ else:
75
+ payload = response_obj
76
+ msg_obj = Message(
77
+ topic=response_topic,
78
+ payload=payload,
79
+ qos=1,
80
+ retain=False,
81
+ correlation_data=(
82
+ correlation_id.encode("utf-8")
83
+ if isinstance(correlation_id, str)
84
+ else correlation_id
85
+ ),
86
+ user_properties={"ReturnCode": str(return_code)},
87
+ )
88
+ return msg_obj
89
+
90
+ @classmethod
91
+ def property_state_message(
92
+ cls, topic: str, state_obj: BaseModel, state_version: Optional[int] = None
93
+ ) -> Message:
94
+ """
95
+ Creates a retained message representing the state/value of a property.
96
+ """
97
+ msg_obj = Message(
98
+ topic=topic,
99
+ payload=state_obj.model_dump_json(by_alias=True).encode("utf-8"),
100
+ qos=1,
101
+ retain=True,
102
+ content_type="application/json",
103
+ )
104
+ if state_version is not None:
105
+ msg_obj.user_properties = {"PropertyVersion": str(state_version)}
106
+ return msg_obj
107
+
108
+ @classmethod
109
+ def property_update_request_message(
110
+ cls,
111
+ topic: str,
112
+ property_obj: BaseModel,
113
+ version: str,
114
+ response_topic: str,
115
+ correlation_id: Union[str, bytes, None] = None,
116
+ ) -> Message:
117
+ """
118
+ Creates a message representing a request to update a property.
119
+ """
120
+ msg_obj = Message(
121
+ topic=topic,
122
+ payload=property_obj.model_dump_json(by_alias=True).encode("utf-8"),
123
+ qos=1,
124
+ retain=False,
125
+ response_topic=response_topic,
126
+ correlation_data=(
127
+ correlation_id.encode("utf-8")
128
+ if isinstance(correlation_id, str)
129
+ else correlation_id
130
+ ),
131
+ user_properties={"PropertyVersion": str(version)},
132
+ )
133
+ return msg_obj
134
+
135
+ @classmethod
136
+ def property_response_message(
137
+ cls,
138
+ response_topic: str,
139
+ property_obj: BaseModel,
140
+ version: str,
141
+ return_code: int,
142
+ correlation_id: Union[str, bytes, None] = None,
143
+ debug_info: Optional[str] = None,
144
+ ) -> Message:
145
+ """
146
+ Creates a message representing a response to a property update request.
147
+ """
148
+ msg_obj = Message(
149
+ topic=response_topic,
150
+ payload=property_obj.model_dump_json(by_alias=True).encode("utf-8"),
151
+ qos=1,
152
+ retain=False,
153
+ correlation_data=(
154
+ correlation_id.encode("utf-8")
155
+ if isinstance(correlation_id, str)
156
+ else correlation_id
157
+ ),
158
+ user_properties={
159
+ "ReturnCode": str(return_code),
160
+ "PropertyVersion": str(version),
161
+ },
162
+ )
163
+ if (
164
+ debug_info is not None and msg_obj.user_properties is not None
165
+ ): # user_properties should never be None here, but checking to satisfy type checker
166
+ msg_obj.user_properties["DebugInfo"] = debug_info
167
+ return msg_obj
168
+
169
+ @classmethod
170
+ def request_message(
171
+ cls,
172
+ topic: str,
173
+ request_obj: BaseModel,
174
+ response_topic: str,
175
+ correlation_id: Union[str, bytes, None] = None,
176
+ ) -> Message:
177
+ if correlation_id is None:
178
+ correlation_id = str(uuid.uuid4())
179
+ msg_obj = Message(
180
+ topic=topic,
181
+ payload=request_obj.model_dump_json(by_alias=True).encode("utf-8"),
182
+ qos=1,
183
+ retain=False,
184
+ response_topic=response_topic,
185
+ correlation_data=(
186
+ correlation_id.encode("utf-8")
187
+ if isinstance(correlation_id, str)
188
+ else correlation_id
189
+ ),
190
+ )
191
+ return msg_obj
@@ -0,0 +1,151 @@
1
+ from typing import Optional
2
+ from enum import IntEnum
3
+ from pyqttier.message import Message
4
+
5
+
6
+ class MethodReturnCode(IntEnum):
7
+ SUCCESS = 0
8
+ CLIENT_ERROR = 1
9
+ SERVER_ERROR = 2
10
+ TRANSPORT_ERROR = 3
11
+ PAYLOAD_ERROR = 4
12
+ CLIENT_SERIALIZATION_ERROR = 5
13
+ CLIENT_DESERIALIZATION_ERROR = 6
14
+ SERVER_SERIALIZATION_ERROR = 7
15
+ SERVER_DESERIALIZATION_ERROR = 8
16
+ METHOD_NOT_FOUND = 9
17
+ UNAUTHORIZED = 10
18
+ TIMEOUT = 11
19
+ OUT_OF_SYNC = 12
20
+ UNKNOWN_ERROR = 13
21
+ NOT_IMPLEMENTED = 14
22
+ SERVICE_UNAVAILABLE = 15
23
+
24
+
25
+ class StingerMethodException(Exception):
26
+
27
+ def __init__(self, return_code: MethodReturnCode, message: str):
28
+ super().__init__(message)
29
+ self._return_code = return_code
30
+
31
+ @property
32
+ def return_code(self) -> MethodReturnCode:
33
+ return self._return_code
34
+
35
+ def to_response_message(
36
+ self, response_topic: str, correlation_id: Optional[bytes] = None
37
+ ) -> Message:
38
+ return Message(
39
+ topic=response_topic,
40
+ payload=b"{}",
41
+ qos=1,
42
+ retain=False,
43
+ correlation_data=correlation_id,
44
+ user_properties={
45
+ "ReturnCode": str(self._return_code.value),
46
+ "DebugInfo": str(self),
47
+ },
48
+ )
49
+
50
+
51
+ class SuccessStingerMethodException(StingerMethodException):
52
+ def __init__(self, message: str):
53
+ super().__init__(MethodReturnCode.SUCCESS, message)
54
+
55
+
56
+ class ClientErrorStingerMethodException(StingerMethodException):
57
+ def __init__(self, message: str):
58
+ super().__init__(MethodReturnCode.CLIENT_ERROR, message)
59
+
60
+
61
+ class ServerErrorStingerMethodException(StingerMethodException):
62
+ def __init__(self, message: str):
63
+ super().__init__(MethodReturnCode.SERVER_ERROR, message)
64
+
65
+
66
+ class TransportErrorStingerMethodException(StingerMethodException):
67
+ def __init__(self, message: str):
68
+ super().__init__(MethodReturnCode.TRANSPORT_ERROR, message)
69
+
70
+
71
+ class PayloadErrorStingerMethodException(StingerMethodException):
72
+ def __init__(self, message: str):
73
+ super().__init__(MethodReturnCode.PAYLOAD_ERROR, message)
74
+
75
+
76
+ class ClientSerializationErrorStingerMethodException(StingerMethodException):
77
+ def __init__(self, message: str):
78
+ super().__init__(MethodReturnCode.CLIENT_SERIALIZATION_ERROR, message)
79
+
80
+
81
+ class ClientDeserializationErrorStingerMethodException(StingerMethodException):
82
+ def __init__(self, message: str):
83
+ super().__init__(MethodReturnCode.CLIENT_DESERIALIZATION_ERROR, message)
84
+
85
+
86
+ class ServerSerializationErrorStingerMethodException(StingerMethodException):
87
+ def __init__(self, message: str):
88
+ super().__init__(MethodReturnCode.SERVER_SERIALIZATION_ERROR, message)
89
+
90
+
91
+ class ServerDeserializationErrorStingerMethodException(StingerMethodException):
92
+ def __init__(self, message: str):
93
+ super().__init__(MethodReturnCode.SERVER_DESERIALIZATION_ERROR, message)
94
+
95
+
96
+ class MethodNotFoundStingerMethodException(StingerMethodException):
97
+ def __init__(self, message: str):
98
+ super().__init__(MethodReturnCode.METHOD_NOT_FOUND, message)
99
+
100
+
101
+ class UnauthorizedStingerMethodException(StingerMethodException):
102
+ def __init__(self, message: str):
103
+ super().__init__(MethodReturnCode.UNAUTHORIZED, message)
104
+
105
+
106
+ class TimeoutStingerMethodException(StingerMethodException):
107
+ def __init__(self, message: str):
108
+ super().__init__(MethodReturnCode.TIMEOUT, message)
109
+
110
+
111
+ class OutOfSyncStingerMethodException(StingerMethodException):
112
+ def __init__(self, message: str):
113
+ super().__init__(MethodReturnCode.OUT_OF_SYNC, message)
114
+
115
+
116
+ class UnknownErrorStingerMethodException(StingerMethodException):
117
+ def __init__(self, message: str):
118
+ super().__init__(MethodReturnCode.UNKNOWN_ERROR, message)
119
+
120
+
121
+ class NotImplementedStingerMethodException(StingerMethodException):
122
+ def __init__(self, message: str):
123
+ super().__init__(MethodReturnCode.NOT_IMPLEMENTED, message)
124
+
125
+
126
+ class ServiceUnavailableStingerMethodException(StingerMethodException):
127
+ def __init__(self, message: str):
128
+ super().__init__(MethodReturnCode.SERVICE_UNAVAILABLE, message)
129
+
130
+
131
+ def stinger_exception_factory(return_code: int, message: Optional[str] = None):
132
+ exc_classes = {
133
+ 0: SuccessStingerMethodException,
134
+ 1: ClientErrorStingerMethodException,
135
+ 2: ServerErrorStingerMethodException,
136
+ 3: TransportErrorStingerMethodException,
137
+ 4: PayloadErrorStingerMethodException,
138
+ 5: ClientSerializationErrorStingerMethodException,
139
+ 6: ClientDeserializationErrorStingerMethodException,
140
+ 7: ServerSerializationErrorStingerMethodException,
141
+ 8: ServerDeserializationErrorStingerMethodException,
142
+ 9: MethodNotFoundStingerMethodException,
143
+ 10: UnauthorizedStingerMethodException,
144
+ 11: TimeoutStingerMethodException,
145
+ 12: OutOfSyncStingerMethodException,
146
+ 13: UnknownErrorStingerMethodException,
147
+ 14: NotImplementedStingerMethodException,
148
+ 15: ServiceUnavailableStingerMethodException,
149
+ }
150
+ exc_class = exc_classes[return_code]
151
+ return exc_class(message or "")