cauli 0.1.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.
Files changed (53) hide show
  1. cauli-0.1.0/LICENSE-APACHE +201 -0
  2. cauli-0.1.0/LICENSE-MIT +21 -0
  3. cauli-0.1.0/PKG-INFO +87 -0
  4. cauli-0.1.0/README.md +51 -0
  5. cauli-0.1.0/cauli/__init__.py +42 -0
  6. cauli-0.1.0/cauli/_codec.py +230 -0
  7. cauli-0.1.0/cauli/_context.py +153 -0
  8. cauli-0.1.0/cauli/_exec.py +914 -0
  9. cauli-0.1.0/cauli/_hooks.py +29 -0
  10. cauli-0.1.0/cauli/app.py +993 -0
  11. cauli-0.1.0/cauli/beat.py +908 -0
  12. cauli-0.1.0/cauli/contrib/__init__.py +2 -0
  13. cauli-0.1.0/cauli/contrib/django.py +345 -0
  14. cauli-0.1.0/cauli/contrib/fastapi.py +30 -0
  15. cauli-0.1.0/cauli/contrib/sqlalchemy.py +266 -0
  16. cauli-0.1.0/cauli/exceptions.py +84 -0
  17. cauli-0.1.0/cauli/py.typed +1 -0
  18. cauli-0.1.0/cauli/result.py +316 -0
  19. cauli-0.1.0/cauli/schedules.py +649 -0
  20. cauli-0.1.0/cauli/task.py +383 -0
  21. cauli-0.1.0/cauli.egg-info/PKG-INFO +87 -0
  22. cauli-0.1.0/cauli.egg-info/SOURCES.txt +51 -0
  23. cauli-0.1.0/cauli.egg-info/dependency_links.txt +1 -0
  24. cauli-0.1.0/cauli.egg-info/entry_points.txt +2 -0
  25. cauli-0.1.0/cauli.egg-info/requires.txt +14 -0
  26. cauli-0.1.0/cauli.egg-info/top_level.txt +1 -0
  27. cauli-0.1.0/pyproject.toml +103 -0
  28. cauli-0.1.0/setup.cfg +4 -0
  29. cauli-0.1.0/tests/test_async_enqueue.py +289 -0
  30. cauli-0.1.0/tests/test_async_pending_cap.py +147 -0
  31. cauli-0.1.0/tests/test_beat.py +1031 -0
  32. cauli-0.1.0/tests/test_beat_ha.py +246 -0
  33. cauli-0.1.0/tests/test_codec.py +233 -0
  34. cauli-0.1.0/tests/test_contrib_django.py +455 -0
  35. cauli-0.1.0/tests/test_contrib_sqlalchemy.py +324 -0
  36. cauli-0.1.0/tests/test_countdown.py +56 -0
  37. cauli-0.1.0/tests/test_direct_call.py +54 -0
  38. cauli-0.1.0/tests/test_enqueue_many.py +234 -0
  39. cauli-0.1.0/tests/test_envelope.py +62 -0
  40. cauli-0.1.0/tests/test_exceptions.py +57 -0
  41. cauli-0.1.0/tests/test_exec.py +387 -0
  42. cauli-0.1.0/tests/test_fork_server.py +420 -0
  43. cauli-0.1.0/tests/test_hooks.py +251 -0
  44. cauli-0.1.0/tests/test_max_envelope_bytes.py +110 -0
  45. cauli-0.1.0/tests/test_options.py +289 -0
  46. cauli-0.1.0/tests/test_packaging.py +57 -0
  47. cauli-0.1.0/tests/test_readme.py +67 -0
  48. cauli-0.1.0/tests/test_result.py +373 -0
  49. cauli-0.1.0/tests/test_schedules.py +551 -0
  50. cauli-0.1.0/tests/test_scheduling_options.py +371 -0
  51. cauli-0.1.0/tests/test_signature_validation.py +111 -0
  52. cauli-0.1.0/tests/test_task_decorator_typing.py +55 -0
  53. cauli-0.1.0/tests/test_task_def.py +180 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 the cauli contributors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 the cauli contributors
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.
cauli-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,87 @@
1
+ Metadata-Version: 2.4
2
+ Name: cauli
3
+ Version: 0.1.0
4
+ Summary: Python client for cauli, a Rust background worker runtime for Python task queues
5
+ Author: the cauli contributors
6
+ License: MIT OR Apache-2.0
7
+ Project-URL: Homepage, https://github.com/bilalwork31-cyber/Cauli
8
+ Project-URL: Repository, https://github.com/bilalwork31-cyber/Cauli
9
+ Project-URL: Issues, https://github.com/bilalwork31-cyber/Cauli/issues
10
+ Keywords: task-queue,background-jobs,redis,worker,async
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Topic :: System :: Distributed Computing
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE-MIT
25
+ License-File: LICENSE-APACHE
26
+ Requires-Dist: redis>=5
27
+ Requires-Dist: msgspec>=0.18
28
+ Requires-Dist: tzdata
29
+ Requires-Dist: cauli-worker==0.1.0; sys_platform == "linux" and platform_python_implementation == "CPython" and (platform_machine == "x86_64" or platform_machine == "aarch64") and python_version < "3.15"
30
+ Provides-Extra: dev
31
+ Requires-Dist: pytest>=8; extra == "dev"
32
+ Provides-Extra: django
33
+ Requires-Dist: django>=4.2; extra == "django"
34
+ Provides-Extra: speed
35
+ Dynamic: license-file
36
+
37
+ # cauli (Python client)
38
+
39
+ Python client for **cauli**, a Rust background worker runtime for Python task queues.
40
+ Define tasks in Python, enqueue from any web framework, execute on the Rust worker.
41
+
42
+ ## Install
43
+
44
+ pip install cauli # Python >= 3.10 (deps: redis>=5, msgspec)
45
+
46
+ That also installs the `cauli-worker` binary, but only where its wheels exist:
47
+ Linux (glibc) on x86_64 or aarch64, CPython 3.10 through 3.14. Anywhere else, a
48
+ macOS laptop, Windows, PyPy, a CPython newer than the release matrix, the worker
49
+ requirement is dropped rather than failing the install: the client still lands
50
+ and enqueueing still works, there is simply no `cauli-worker` to run. Two
51
+ targets fail the install instead, because no marker can describe them: musl
52
+ (Alpine) and the free threaded build. For those, and for enqueue only web dynos
53
+ that never run a worker, see `PROTOCOL.md` section 13.4.
54
+
55
+ ## Define an app and tasks (myproj/tasks.py)
56
+
57
+ from cauli import Cauli
58
+
59
+ app = Cauli(redis_url="redis://localhost:6379/0", default_queue="default")
60
+
61
+ @app.task()
62
+ async def send_email(to: str) -> str:
63
+ ... # io task: runs on the worker's asyncio loop
64
+ return "sent"
65
+
66
+ @app.task(kind="cpu", timeout=120, soft_timeout=60, max_retries=5)
67
+ def crunch(n: int) -> int: # cpu task: runs in a child Python process
68
+ return sum(i * i for i in range(n))
69
+
70
+ ## Enqueue from Django, FastAPI, or Flask
71
+
72
+ from myproj.tasks import send_email
73
+
74
+ r = send_email.delay("a@b.com")
75
+ r = send_email.apply_async(args=("a@b.com",), countdown=30, queue="emails",
76
+ idempotency_key="welcome:a@b.com")
77
+ r.status() # "pending" | "success" | "failure" | "duplicate" | "expired"
78
+ r.get(timeout=10) # value on success; raises TaskFailedError / TimeoutError
79
+
80
+ Tasks stay directly callable for tests: `crunch(10)` runs inline, no broker needed.
81
+
82
+ ## Run the worker (Rust binary)
83
+
84
+ cauli-worker -A myproj.tasks:app -c 50 -Q default,emails
85
+
86
+ The URL falls back to env `CAULI_REDIS_URL`, then `redis://localhost:6379/0`.
87
+ See `PROTOCOL.md` in the repo root for the full wire contract.
cauli-0.1.0/README.md ADDED
@@ -0,0 +1,51 @@
1
+ # cauli (Python client)
2
+
3
+ Python client for **cauli**, a Rust background worker runtime for Python task queues.
4
+ Define tasks in Python, enqueue from any web framework, execute on the Rust worker.
5
+
6
+ ## Install
7
+
8
+ pip install cauli # Python >= 3.10 (deps: redis>=5, msgspec)
9
+
10
+ That also installs the `cauli-worker` binary, but only where its wheels exist:
11
+ Linux (glibc) on x86_64 or aarch64, CPython 3.10 through 3.14. Anywhere else, a
12
+ macOS laptop, Windows, PyPy, a CPython newer than the release matrix, the worker
13
+ requirement is dropped rather than failing the install: the client still lands
14
+ and enqueueing still works, there is simply no `cauli-worker` to run. Two
15
+ targets fail the install instead, because no marker can describe them: musl
16
+ (Alpine) and the free threaded build. For those, and for enqueue only web dynos
17
+ that never run a worker, see `PROTOCOL.md` section 13.4.
18
+
19
+ ## Define an app and tasks (myproj/tasks.py)
20
+
21
+ from cauli import Cauli
22
+
23
+ app = Cauli(redis_url="redis://localhost:6379/0", default_queue="default")
24
+
25
+ @app.task()
26
+ async def send_email(to: str) -> str:
27
+ ... # io task: runs on the worker's asyncio loop
28
+ return "sent"
29
+
30
+ @app.task(kind="cpu", timeout=120, soft_timeout=60, max_retries=5)
31
+ def crunch(n: int) -> int: # cpu task: runs in a child Python process
32
+ return sum(i * i for i in range(n))
33
+
34
+ ## Enqueue from Django, FastAPI, or Flask
35
+
36
+ from myproj.tasks import send_email
37
+
38
+ r = send_email.delay("a@b.com")
39
+ r = send_email.apply_async(args=("a@b.com",), countdown=30, queue="emails",
40
+ idempotency_key="welcome:a@b.com")
41
+ r.status() # "pending" | "success" | "failure" | "duplicate" | "expired"
42
+ r.get(timeout=10) # value on success; raises TaskFailedError / TimeoutError
43
+
44
+ Tasks stay directly callable for tests: `crunch(10)` runs inline, no broker needed.
45
+
46
+ ## Run the worker (Rust binary)
47
+
48
+ cauli-worker -A myproj.tasks:app -c 50 -Q default,emails
49
+
50
+ The URL falls back to env `CAULI_REDIS_URL`, then `redis://localhost:6379/0`.
51
+ See `PROTOCOL.md` in the repo root for the full wire contract.
@@ -0,0 +1,42 @@
1
+ """cauli: Python client for the cauli Rust background worker runtime.
2
+
3
+ Define tasks with ``@app.task(...)``, enqueue with ``.delay()`` /
4
+ ``.apply_async()``, read results with ``AsyncResult``. The heavy lifting
5
+ (execution, retries, timeouts) happens in the Rust ``cauli-worker`` process.
6
+ See PROTOCOL.md for the full wire contract.
7
+ """
8
+
9
+ from cauli._context import TaskContext, current_task
10
+ from cauli.app import AsyncCauli, Cauli
11
+ from cauli.exceptions import Retry, SoftTimeLimitExceeded, TaskFailedError
12
+ from cauli.result import AsyncResult
13
+ from cauli.schedules import (
14
+ CrontabSchedule,
15
+ IntervalSchedule,
16
+ Schedule,
17
+ ScheduleEntry,
18
+ crontab,
19
+ interval,
20
+ )
21
+ from cauli.task import TaskDef
22
+
23
+ __version__ = "0.1.0"
24
+
25
+ __all__ = [
26
+ "Cauli",
27
+ "AsyncCauli",
28
+ "Retry",
29
+ "SoftTimeLimitExceeded",
30
+ "TaskFailedError",
31
+ "AsyncResult",
32
+ "TaskDef",
33
+ "TaskContext",
34
+ "current_task",
35
+ "Schedule",
36
+ "ScheduleEntry",
37
+ "IntervalSchedule",
38
+ "CrontabSchedule",
39
+ "crontab",
40
+ "interval",
41
+ "__version__",
42
+ ]
@@ -0,0 +1,230 @@
1
+ """cauli._codec: JSON encode/decode, backed by msgspec.
2
+
3
+ The wire format is plain JSON (PROTOCOL.md sections 2, 5.1, 8); this module
4
+ only decides HOW that JSON is produced and parsed, never WHAT crosses the
5
+ wire.
6
+
7
+ msgspec is a hard requirement, not an accelerator. There is deliberately no
8
+ stdlib ``json`` fallback: a fallback means the slow path can silently survive
9
+ in production, and — worse here — the two backends did not agree. They
10
+ disagreed on lone surrogates, on dict-key coercion (the stdlib silently turns
11
+ ``{1: "a"}`` into ``{"1": "a"}`` while msgspec rejects a ``bool`` key
12
+ outright), and on which exception type surfaces. One implementation means one
13
+ set of semantics to reason about and to test.
14
+
15
+ Note that msgspec is PERMISSIVE where the stdlib is strict, so the validation
16
+ walk below is load-bearing rather than belt-and-braces. Measured against
17
+ msgspec 0.21: it encodes ``NaN``/``Infinity`` to ``null`` (silently corrupting
18
+ the value), accepts ``set`` (as an array) and ``bytes`` (as base64), and
19
+ coerces int dict keys to strings. All of those must be rejected to keep the
20
+ protocol honest, so ``_validate_json_types`` walks the object tree first and
21
+ enforces the JSON type set. What msgspec does handle correctly on its own is a
22
+ lone surrogate, which raises ``UnicodeEncodeError`` at encode time.
23
+
24
+ ``encode`` returns ``bytes``; call sites either hand that straight to redis
25
+ (which accepts bytes) or funnel it through :func:`encode_str` /
26
+ :func:`encode_bytes`. ``decode`` accepts ``bytes`` or ``str``.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import math
32
+ from typing import Any
33
+
34
+ try:
35
+ import msgspec
36
+ import msgspec.json as _msgspec_json
37
+ except ImportError as exc: # pragma: no cover - environment error, not logic
38
+ raise ImportError(
39
+ "cauli requires msgspec. Install it with: pip install msgspec\n"
40
+ "(it is a declared dependency, so `pip install cauli` normally brings "
41
+ "it in; this usually means an editable/partial install)"
42
+ ) from exc
43
+
44
+ __all__ = [
45
+ "backend",
46
+ "encode",
47
+ "encode_str",
48
+ "encode_bytes",
49
+ "decode",
50
+ "ENCODE_ERRORS",
51
+ "DECODE_ERRORS",
52
+ ]
53
+
54
+ backend = "msgspec"
55
+
56
+ # Exception tuples call sites catch around encode()/decode().
57
+ #
58
+ # `msgspec.MsgspecError` is listed explicitly and is NOT redundant:
59
+ # `msgspec.DecodeError` subclasses ValueError, but `msgspec.EncodeError` does
60
+ # NOT (its MRO is EncodeError -> MsgspecError -> Exception). Catching only
61
+ # (TypeError, ValueError) would therefore let a raw encode failure escape
62
+ # every guarded call site.
63
+ #
64
+ # TypeError covers unsupported types, ValueError covers the non-finite float
65
+ # rejection and UnicodeEncodeError (lone surrogates), and RecursionError
66
+ # covers a self-referential or pathologically deep object tree — the validator
67
+ # below recurses without cycle detection, and RecursionError is neither a
68
+ # ValueError nor a TypeError, so it has to be named.
69
+ ENCODE_ERRORS: tuple = (TypeError, ValueError, RecursionError, msgspec.MsgspecError)
70
+ DECODE_ERRORS: tuple = (TypeError, ValueError, RecursionError, msgspec.MsgspecError)
71
+
72
+ _encoder = _msgspec_json.Encoder()
73
+ _decoder = _msgspec_json.Decoder()
74
+
75
+ # Tail of a non-JSON-type rejection. The point of naming the set inline is
76
+ # that a Celery refugee arrives with a UUID primary key or a datetime, and the
77
+ # error should say once what the wire format actually takes.
78
+ _ALLOWED = "allowed types: str, int, float, bool, None, list, tuple, dict with str keys"
79
+
80
+
81
+ def _push_path(exc: BaseException, segment: object) -> None:
82
+ """Record one location segment on an in-flight validation failure.
83
+
84
+ Segments are attached to the exception as the walk unwinds, so they arrive
85
+ innermost-first and :func:`_render_path` reverses them. Carrying the
86
+ location on the exception rather than threading a path string down the
87
+ walk keeps the success path — which runs on every single enqueue — free of
88
+ the per-element string building that would otherwise cost more than the
89
+ type checks it annotates.
90
+
91
+ Only the plain ``TypeError``/``ValueError`` raised by this module are
92
+ annotated, so :func:`encode` can rebuild the message as ``type(exc)(msg)``
93
+ without ever meeting an exception class that takes other constructor
94
+ arguments.
95
+ """
96
+ if type(exc) is not TypeError and type(exc) is not ValueError:
97
+ return
98
+ path = getattr(exc, "_cauli_path", None)
99
+ if path is None:
100
+ exc._cauli_path = [segment] # type: ignore[attr-defined]
101
+ else:
102
+ path.append(segment)
103
+
104
+
105
+ def _render_path(segments: list[Any]) -> str:
106
+ """Render innermost-first segments as e.g. ``args[0]['meta']``.
107
+
108
+ The outermost segment is a top-level envelope field (``args``, ``kwargs``,
109
+ a result key), so it reads bare; everything under it is subscripted.
110
+ """
111
+ parts: list[str] = []
112
+ for i, seg in enumerate(reversed(segments)):
113
+ if isinstance(seg, str):
114
+ parts.append(seg if i == 0 else f"[{seg!r}]")
115
+ else:
116
+ parts.append(f"[{seg}]")
117
+ return "".join(parts)
118
+
119
+
120
+ def _validate_json_types(obj: Any) -> None:
121
+ """Reject anything outside the JSON type set, non-finite floats, and
122
+ non-str dict keys.
123
+
124
+ Not optional: msgspec would otherwise silently encode ``NaN``/``Infinity``
125
+ as ``null``, accept a ``set`` as an array and ``bytes`` as base64, and
126
+ coerce int dict keys — all of which would put values on the wire that the
127
+ protocol does not define. Exact-type checks come first because the common
128
+ case is plain builtins.
129
+
130
+ Dict keys must be ``str``. Coercing them (as the stdlib does) is a footgun
131
+ in its own right: ``{1: "a", "1": "b"}`` would silently collapse to a
132
+ single entry.
133
+
134
+ Every container re-raises a failure from below after recording its own key
135
+ or index, so :func:`encode` can say WHICH argument was rejected rather than
136
+ only naming the type. ``RecursionError`` is deliberately not annotated: a
137
+ cyclic object has no finite path to report, and running more code at the
138
+ depth limit only invites a second one.
139
+ """
140
+ t = type(obj)
141
+ if t is str or t is int or t is bool or obj is None:
142
+ return
143
+ if t is float:
144
+ if math.isfinite(obj):
145
+ return
146
+ raise ValueError("Out of range float values are not JSON compliant")
147
+ if t is dict:
148
+ for k, v in obj.items():
149
+ if type(k) is not str:
150
+ raise TypeError(f"dict keys must be str, got {type(k).__name__}")
151
+ try:
152
+ _validate_json_types(v)
153
+ except (TypeError, ValueError) as exc:
154
+ _push_path(exc, k)
155
+ raise
156
+ return
157
+ if t is list or t is tuple:
158
+ for i, v in enumerate(obj):
159
+ try:
160
+ _validate_json_types(v)
161
+ except (TypeError, ValueError) as exc:
162
+ _push_path(exc, i)
163
+ raise
164
+ return
165
+ # Subclasses of the builtin scalar/container types (rare path).
166
+ if isinstance(obj, (str, int)):
167
+ return
168
+ if isinstance(obj, float):
169
+ if math.isfinite(obj):
170
+ return
171
+ raise ValueError("Out of range float values are not JSON compliant")
172
+ if isinstance(obj, dict):
173
+ for k, v in obj.items():
174
+ if not isinstance(k, str):
175
+ raise TypeError(f"dict keys must be str, got {type(k).__name__}")
176
+ try:
177
+ _validate_json_types(v)
178
+ except (TypeError, ValueError) as exc:
179
+ _push_path(exc, k)
180
+ raise
181
+ return
182
+ if isinstance(obj, (list, tuple)):
183
+ for i, v in enumerate(obj):
184
+ try:
185
+ _validate_json_types(v)
186
+ except (TypeError, ValueError) as exc:
187
+ _push_path(exc, i)
188
+ raise
189
+ return
190
+ raise TypeError(
191
+ f"Object of type {t.__name__} is not JSON serializable ({_ALLOWED})"
192
+ )
193
+
194
+
195
+ def encode(obj: Any) -> bytes:
196
+ """Encode ``obj`` as compact UTF-8 JSON bytes.
197
+
198
+ Raises for non-JSON types (TypeError), NaN/Infinity and lone surrogates
199
+ (ValueError), per :data:`ENCODE_ERRORS`. A rejection from inside a
200
+ container carries its location, e.g. ``args[0]: Object of type UUID is not
201
+ JSON serializable (allowed types: ...)``.
202
+ """
203
+ try:
204
+ _validate_json_types(obj)
205
+ except (TypeError, ValueError) as exc:
206
+ segments = getattr(exc, "_cauli_path", None)
207
+ if not segments:
208
+ raise
209
+ raise type(exc)(f"{_render_path(segments)}: {exc}") from exc
210
+ return _encoder.encode(obj)
211
+
212
+
213
+ def decode(data: bytes | str) -> Any:
214
+ """Parse JSON from bytes or str. Raises on malformed input."""
215
+ return _decoder.decode(data)
216
+
217
+
218
+ def encode_str(obj: Any) -> str:
219
+ """:func:`encode`, as ``str`` (for text-stream transports)."""
220
+ return encode(obj).decode("utf-8")
221
+
222
+
223
+ def encode_bytes(obj: Any) -> bytes:
224
+ """:func:`encode`, as ``bytes`` (for byte-stream transports).
225
+
226
+ Identical to :func:`encode` now that msgspec is the only backend; kept as
227
+ a named entry point so the cpu child's socket path states its intent (and
228
+ so it stays correct if a backend returning ``str`` is ever reintroduced).
229
+ """
230
+ return encode(obj)