daprmq-client 0.0.0a4__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 (46) hide show
  1. daprmq_client-0.0.0a4/.gitignore +122 -0
  2. daprmq_client-0.0.0a4/LICENSE +202 -0
  3. daprmq_client-0.0.0a4/PKG-INFO +41 -0
  4. daprmq_client-0.0.0a4/README.md +19 -0
  5. daprmq_client-0.0.0a4/docs/CLIENT_SDK.md +215 -0
  6. daprmq_client-0.0.0a4/perf/__init__.py +0 -0
  7. daprmq_client-0.0.0a4/perf/__main__.py +139 -0
  8. daprmq_client-0.0.0a4/perf/metrics.py +287 -0
  9. daprmq_client-0.0.0a4/perf/options.py +77 -0
  10. daprmq_client-0.0.0a4/perf/profiles.py +249 -0
  11. daprmq_client-0.0.0a4/perf/records.py +183 -0
  12. daprmq_client-0.0.0a4/perf/scenarios.py +445 -0
  13. daprmq_client-0.0.0a4/perf/tests/__init__.py +0 -0
  14. daprmq_client-0.0.0a4/perf/tests/test_metrics.py +220 -0
  15. daprmq_client-0.0.0a4/perf/tests/test_profiles.py +79 -0
  16. daprmq_client-0.0.0a4/perf/tests/test_records.py +130 -0
  17. daprmq_client-0.0.0a4/pyproject.toml +39 -0
  18. daprmq_client-0.0.0a4/scripts/generate_grpc.py +45 -0
  19. daprmq_client-0.0.0a4/src/daprmq_client/__init__.py +88 -0
  20. daprmq_client-0.0.0a4/src/daprmq_client/client.py +741 -0
  21. daprmq_client-0.0.0a4/src/daprmq_client/errors.py +95 -0
  22. daprmq_client-0.0.0a4/src/daprmq_client/grpc/__init__.py +0 -0
  23. daprmq_client-0.0.0a4/src/daprmq_client/grpc/daprmq_pb2.py +137 -0
  24. daprmq_client-0.0.0a4/src/daprmq_client/grpc/daprmq_pb2.pyi +489 -0
  25. daprmq_client-0.0.0a4/src/daprmq_client/grpc/daprmq_pb2_grpc.py +655 -0
  26. daprmq_client-0.0.0a4/src/daprmq_client/queue_consumer.py +235 -0
  27. daprmq_client-0.0.0a4/src/daprmq_client/session_queue_consumer.py +224 -0
  28. daprmq_client-0.0.0a4/src/daprmq_client/types.py +134 -0
  29. daprmq_client-0.0.0a4/tests/__init__.py +0 -0
  30. daprmq_client-0.0.0a4/tests/fake_grpc_stub.py +76 -0
  31. daprmq_client-0.0.0a4/tests/fake_transport.py +27 -0
  32. daprmq_client-0.0.0a4/tests/integration/__init__.py +0 -0
  33. daprmq_client-0.0.0a4/tests/integration/conftest.py +40 -0
  34. daprmq_client-0.0.0a4/tests/integration/stack.py +290 -0
  35. daprmq_client-0.0.0a4/tests/integration/test_queue_consumer.py +200 -0
  36. daprmq_client-0.0.0a4/tests/integration/test_queue_stream.py +78 -0
  37. daprmq_client-0.0.0a4/tests/integration/test_retries_and_readiness.py +48 -0
  38. daprmq_client-0.0.0a4/tests/integration/test_session_queue_consumer.py +83 -0
  39. daprmq_client-0.0.0a4/tests/test_client.py +282 -0
  40. daprmq_client-0.0.0a4/tests/test_consume.py +160 -0
  41. daprmq_client-0.0.0a4/tests/test_consume_session.py +212 -0
  42. daprmq_client-0.0.0a4/tests/test_package.py +38 -0
  43. daprmq_client-0.0.0a4/tests/test_queue_consumer.py +283 -0
  44. daprmq_client-0.0.0a4/tests/test_retry.py +266 -0
  45. daprmq_client-0.0.0a4/tests/test_session_queue_consumer.py +408 -0
  46. daprmq_client-0.0.0a4/tests/test_wait_for_ready.py +92 -0
@@ -0,0 +1,122 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ .Python
7
+ build/
8
+ develop-eggs/
9
+ dist/
10
+ downloads/
11
+ eggs/
12
+ .eggs/
13
+ lib/
14
+ lib64/
15
+ parts/
16
+ sdist/
17
+ var/
18
+ wheels/
19
+ *.egg-info/
20
+ .installed.cfg
21
+ *.egg
22
+ MANIFEST
23
+
24
+ # Virtual environments
25
+ venv/
26
+ env/
27
+ ENV/
28
+ .venv
29
+
30
+ # IDE
31
+ .vscode/
32
+ .idea/
33
+ *.swp
34
+ *.swo
35
+ *.sublime-project
36
+ *.sublime-workspace
37
+
38
+ # OS
39
+ .DS_Store
40
+ .DS_Store?
41
+ ._*
42
+ .Spotlight-V100
43
+ .Trashes
44
+ ehthumbs.db
45
+ Thumbs.db
46
+
47
+ # Environment
48
+ .env.local
49
+
50
+ # Tests
51
+ .pytest_cache/
52
+ .coverage
53
+ htmlcov/
54
+ .tox/
55
+ *.cover
56
+ .hypothesis/
57
+
58
+ # Type checking
59
+ .mypy_cache/
60
+ .dmypy.json
61
+ dmypy.json
62
+
63
+ # Docker
64
+ *.log
65
+
66
+ # Dapr
67
+ .dapr/
68
+ dapr_scheduler/
69
+ dapr/blobstore-data/
70
+
71
+ # .NET
72
+ bin/
73
+ obj/
74
+ *.dll
75
+ *.exe
76
+ *.pdb
77
+ *.cache
78
+ *.suo
79
+ *.user
80
+ *.userosscache
81
+ *.sln.docstates
82
+ *.userprefs
83
+ project.lock.json
84
+ project.fragment.lock.json
85
+ artifacts/
86
+ *.nuget.props
87
+ *.nuget.targets
88
+ .vs/
89
+
90
+ # Perf results: each machine's own history (CI's lives on the perf-results branch)
91
+ /perf-results/
92
+
93
+ # Custom nuget - allow custom nuget packages
94
+ !nuget-local/*.nupkg
95
+
96
+ # Node.js / Dashboard
97
+ dashboard/node_modules/
98
+ dashboard/dist/
99
+ dashboard/npm-debug.log*
100
+ dashboard/yarn-debug.log*
101
+ dashboard/yarn-error.log*
102
+ dashboard/.env
103
+ dashboard/.env.production
104
+ dashboard/.env.local
105
+ dashboard/.env.development.local
106
+ dashboard/.env.test.local
107
+ dashboard/.env.production.local
108
+ dashboard/index-backup.html
109
+
110
+ # Node.js / TypeScript SDK
111
+ sdks/typescript/node_modules/
112
+ sdks/typescript/npm-debug.log*
113
+
114
+ # Java SDK
115
+ sdks/java/target/
116
+
117
+ # Examples
118
+ examples/java/*/target/
119
+ examples/java/*/dependency-reduced-pom.xml
120
+ examples/typescript/*/node_modules/
121
+ examples/typescript/*/npm-debug.log*
122
+ examples/python/*/.venv/
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,41 @@
1
+ Metadata-Version: 2.5
2
+ Name: daprmq-client
3
+ Version: 0.0.0a4
4
+ Summary: Python client SDK for DaprMQ
5
+ Project-URL: Repository, https://github.com/olitomlinson/dapr-mq
6
+ Project-URL: Documentation, https://github.com/olitomlinson/dapr-mq/blob/main/sdks/python/docs/CLIENT_SDK.md
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Requires-Python: >=3.10
10
+ Requires-Dist: grpcio-health-checking>=1.66
11
+ Requires-Dist: grpcio>=1.66
12
+ Requires-Dist: httpx>=0.27
13
+ Requires-Dist: protobuf>=5.27
14
+ Provides-Extra: dev
15
+ Requires-Dist: build>=1.2; extra == 'dev'
16
+ Requires-Dist: grpcio-tools>=1.66; extra == 'dev'
17
+ Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
18
+ Requires-Dist: pytest>=8.3; extra == 'dev'
19
+ Requires-Dist: respx>=0.21; extra == 'dev'
20
+ Requires-Dist: testcontainers>=4.8; extra == 'dev'
21
+ Description-Content-Type: text/markdown
22
+
23
+ # daprmq-client
24
+
25
+ Async Python client SDK for [DaprMQ](https://github.com/olitomlinson/dapr-mq), a FIFO queue built on Dapr actors.
26
+
27
+ ```sh
28
+ pip install daprmq-client --pre
29
+ ```
30
+
31
+ ```python
32
+ from daprmq_client import DaprMQClient, EnqueueItem
33
+
34
+ async with DaprMQClient(http_base_url="http://localhost:8002", grpc_address="localhost:8003") as client:
35
+ await client.enqueue("orders", [EnqueueItem(item={"id": 1})])
36
+ ```
37
+
38
+ DaprMQ is pre-release: versions are `0.0.0aN`, so `pip` needs `--pre` (or an explicit version) to install one.
39
+
40
+ See the [SDK guide](https://github.com/olitomlinson/dapr-mq/blob/main/sdks/python/docs/CLIENT_SDK.md) for
41
+ consumers, sessions, retries and the full API. Licensed under Apache-2.0.
@@ -0,0 +1,19 @@
1
+ # daprmq-client
2
+
3
+ Async Python client SDK for [DaprMQ](https://github.com/olitomlinson/dapr-mq), a FIFO queue built on Dapr actors.
4
+
5
+ ```sh
6
+ pip install daprmq-client --pre
7
+ ```
8
+
9
+ ```python
10
+ from daprmq_client import DaprMQClient, EnqueueItem
11
+
12
+ async with DaprMQClient(http_base_url="http://localhost:8002", grpc_address="localhost:8003") as client:
13
+ await client.enqueue("orders", [EnqueueItem(item={"id": 1})])
14
+ ```
15
+
16
+ DaprMQ is pre-release: versions are `0.0.0aN`, so `pip` needs `--pre` (or an explicit version) to install one.
17
+
18
+ See the [SDK guide](https://github.com/olitomlinson/dapr-mq/blob/main/sdks/python/docs/CLIENT_SDK.md) for
19
+ consumers, sessions, retries and the full API. Licensed under Apache-2.0.
@@ -0,0 +1,215 @@
1
+ # daprmq-client (Python)
2
+
3
+ An async Python client for DaprMQ's HTTP/gRPC API - `DaprMQClient` for direct queue and session operations, plus `SessionQueueConsumer`, a managed multi-session consume loop built on the `ConsumeSession` streaming RPC. Lives at `sdks/python/`, physically separate from the server codebase under `dotnet/`. Built on `httpx` (REST) and `grpc.aio` (streaming) - every public method is a coroutine.
4
+
5
+ ## Install / Reference
6
+
7
+ ```bash
8
+ pip install daprmq-client --pre
9
+ ```
10
+
11
+ DaprMQ is pre-release (`0.0.0aN`), so `--pre` or an explicit version is needed. To work on the SDK itself,
12
+ install from the local path (editable):
13
+
14
+ ```bash
15
+ uv pip install -e path/to/sdks/python
16
+ ```
17
+
18
+ or add it as a path dependency in your own `pyproject.toml`:
19
+
20
+ ```toml
21
+ [project]
22
+ dependencies = ["daprmq-client @ file:///path/to/sdks/python"]
23
+ ```
24
+
25
+ The gRPC stubs under `daprmq_client/grpc/` are generated from the shared proto contract (`dotnet/src/DaprMQ.ApiServer/Protos/daprmq.proto` - the same source of truth the .NET and TypeScript SDKs use) and checked in; re-run `python scripts/generate_grpc.py` from `sdks/python/` after the proto changes.
26
+
27
+ ## Constructing a client
28
+
29
+ ```python
30
+ from daprmq_client import DaprMQClient
31
+
32
+ async with DaprMQClient(
33
+ http_base_url="http://localhost:8002",
34
+ grpc_address="localhost:8003",
35
+ ) as client:
36
+ ... # client.aclose() runs automatically on exit
37
+ ```
38
+
39
+ or without the context manager:
40
+
41
+ ```python
42
+ client = DaprMQClient(http_base_url="http://localhost:8002", grpc_address="localhost:8003")
43
+ try:
44
+ ...
45
+ finally:
46
+ await client.aclose()
47
+ ```
48
+
49
+ `DaprMQClient` is REST-backed for every operation except `consume_session`, which is the one method built on the `ConsumeSession` gRPC streaming RPC - everything else (`enqueue`, `dequeue_locked`, `acknowledge`, `acknowledge_batch`, `extend_lock`, `nack`, `dead_letter`, `accept_session`, `renew_session_lease`, `release_session`) is a plain HTTP call under the hood (via `httpx.AsyncClient`).
50
+
51
+ `grpc_address` is required unless you pass a pre-built `grpc_stub` (e.g. in tests - `http_client`/`grpc_stub` are both DI/test seams). `aclose()` only tears down the `httpx.AsyncClient`/gRPC channel this instance built itself; an `http_client` or `grpc_stub` you supplied yourself is left alone.
52
+
53
+ Errors map to typed exceptions exported alongside the client (`LockNotFoundError`, `LockExpiredError`, `SessionNotFoundError`, `SessionLockedError`, `SessionLeaseExpiredError`, `InvalidLeaseIdError`, `SessionActorUnavailableError`, `NoSessionsAvailableError`, `SessionLostError`, `ValidationError`, `ActorNotFoundError`, `DaprMQUnavailableError`, `DeliveryUnknownError`), all deriving from `DaprMQError`. A `204 No Content` (queue empty / no session available) is not an error - `dequeue_locked`/`accept_session` return `None` instead of raising.
54
+
55
+ ## Retries, failures and waiting for a server
56
+
57
+ Calls ride out a DaprMQ that briefly can't serve them, such as a worker restarting, under the shared
58
+ contract in [RETRIES_AND_READINESS.md](../../testing/RETRIES_AND_READINESS.md). [docs/TIMEOUTS_AND_RETRIES.md](../../../docs/TIMEOUTS_AND_RETRIES.md) covers what to program for, across all SDKs:
59
+
60
+ ```python
61
+ client = DaprMQClient(
62
+ http_base_url=..., grpc_address=...,
63
+ retry=RetryOptions(
64
+ timeout=30.0, # default, in seconds: how long to keep retrying an outage. 0 = off
65
+ auto_idempotency_keys=True, # optional: makes every enqueue safe to retry
66
+ ),
67
+ )
68
+ ```
69
+
70
+ - **Slow is not failed.** A call that reached a busy queue waits its turn for as long as it takes, up to your own cancellation (and a 100 s per-call safety limit). The retry timeout never cuts it short.
71
+ - **Certainly not performed** (the server reports it couldn't serve the call, or the connection was
72
+ refused): retried until `timeout`, then `DaprMQUnavailableError`. Always safe to repeat later.
73
+ - **Outcome unknown** (the connection broke after sending, or no response arrived in time): an
74
+ `enqueue` whose items all have an `idempotency_key`, and `acknowledge_batch`, are retried; anything else raises
75
+ `DeliveryUnknownError` straight away. It carries the `operation`, the `queue_id` and, for enqueue,
76
+ the items' `idempotency_keys`. What to do next:
77
+ - **Enqueue without keys:** re-send and accept a possible duplicate.
78
+ - **`dequeue_locked`:** don't re-send. If it ran, the items come back when their locks expire.
79
+ - **Acknowledge / extend_lock / dead_letter / nack:** re-sending is safe in effect. A `LockNotFoundError`
80
+ then means the first attempt worked.
81
+ - **Cancelling the task** (e.g. `asyncio.wait_for`) stops retrying as normal cancellation.
82
+
83
+ `await client.wait_for_ready()` waits until queue operations can be served (gRPC health service
84
+ `daprmq.DaprMQ.operations`), without writing anything. Bound it with `asyncio.wait_for`. Pass
85
+ `"daprmq.DaprMQ"` to wait only for the server instance itself.
86
+
87
+ ## Basic queue operations
88
+
89
+ ```python
90
+ from daprmq_client import EnqueueItem
91
+
92
+ await client.enqueue("my-queue", [EnqueueItem(item={"task": "send_email"})])
93
+
94
+ result = await client.dequeue_locked("my-queue", ttl_seconds=60)
95
+ if result is not None:
96
+ for item in result.items:
97
+ # ... process item.item ...
98
+ await client.acknowledge("my-queue", item.lock_id)
99
+ ```
100
+
101
+ **Competing consumers.** By default a queue serves one lock at a time - while any item is locked, further locked dequeues come back `locked` (HTTP 423). When several consumers share a queue (e.g. replicas scaled out by KEDA), pass `allow_competing_consumers=True` so each can hold its own locks concurrently.
102
+
103
+ ## Consuming a queue over a stream (`consume`, `QueueConsumer`)
104
+
105
+ `consume` opens a gRPC stream on a plain queue. The server keeps up to `prefetch_count` locked items delivered, refills as they are settled, and renews their locks until they are settled, so there's no polling and no `extend_lock`:
106
+
107
+ ```python
108
+ import contextlib
109
+
110
+ async with contextlib.aclosing(client.consume(
111
+ "my-queue", prefetch_count=50, allow_competing_consumers=True,
112
+ on_settle_failed=lambda lock_id, err: log.warning("settle %s: %s", lock_id, err),
113
+ )) as stream:
114
+ async for delivery in stream:
115
+ # ... process delivery.item; delivery.delivery_count is 1 on a first delivery ...
116
+ await delivery.ack() # or nack() / dead_letter()
117
+ ```
118
+
119
+ A rejected settle doesn't end the stream: it goes to `on_settle_failed`. Leaving the loop, or setting the `cancel` event, half-closes the stream: the server applies the settles already sent and returns every unsettled item straight away (`aclosing` waits for that). Settling afterwards raises `StreamClosedError`.
120
+
121
+ `QueueConsumer` is the recommended way to run a long-lived consumer. It runs your handler over the stream and reopens it with backoff if it breaks:
122
+
123
+ ```python
124
+ from daprmq_client import QueueConsumer, QueueConsumerOptions, QueueMessageContext
125
+
126
+ async def handler(ctx: QueueMessageContext) -> None:
127
+ # ctx.lock_id, ctx.item, ctx.priority, ctx.delivery_count
128
+ await process(ctx.item) # returning acks; raising applies on_handler_error
129
+
130
+ async with QueueConsumer(client, "my-queue", QueueConsumerOptions(max_concurrent_handlers=10), handler):
131
+ ... # run your application
132
+ ```
133
+
134
+ Stopping - `await consumer.stop()`, or leaving the `async with` - stops handing out messages, lets running handlers finish and settle for up to `drain_timeout_seconds`, then closes the stream, so the server returns every message the consumer held but hadn't started straight away. For a job that takes a batch and exits (a KEDA ScaledJob, a cron job), use `dequeue_locked` instead: a stream's prefetch would lock messages the job never handles.
135
+
136
+ | Option | Default | Notes |
137
+ | --- | --- | --- |
138
+ | `max_active_messages` | 100 | The stream's prefetch count: messages locked to this consumer, handled or waiting |
139
+ | `max_concurrent_handlers` | 0 (unlimited) | Bounded by `max_active_messages` |
140
+ | `lock_ttl_seconds` | 30 s | The server renews each lock until its message is settled |
141
+ | `allow_competing_consumers` | `true` | Replicas share the queue |
142
+ | `strict_order` | `false` | Queue order even after a nack: a window of 1, one handler, no competing consumers |
143
+ | `on_handler_error` | `QueueHandlerFailureAction.NACK` | Or `DEAD_LETTER` |
144
+ | `max_retriable_errors_per_sec` | 10 | Paces nacks after handler errors; 0 for unpaced |
145
+ | `min_backoff_seconds` / `max_backoff_seconds` | 1 / 60 | Seconds before reopening a broken stream; doubles per break, resets after a delivery |
146
+ | `drain_timeout_seconds` | 30 s | |
147
+ ## Sessions - manual API
148
+
149
+ For sticky routing, admin tooling, or callers who don't want a managed consume loop:
150
+
151
+ ```python
152
+ lease = await client.accept_session("my-queue", session_id="order-42")
153
+ if lease is not None:
154
+ dequeued = await client.dequeue_locked(f"my-queue-session-{lease.session_id}", lease_id=lease.lease_id)
155
+ # ... acknowledge/extend_lock/dead_letter against the same derived queue id + lease_id ...
156
+ await client.release_session("my-queue", lease.session_id, lease.lease_id)
157
+ ```
158
+
159
+ See [API_REFERENCE.md](../../../docs/API_REFERENCE.md#sessions) and [design/sessions.md](../../../docs/design/sessions.md) for the underlying actor-id convention and lease semantics.
160
+
161
+ ## Sessions - managed consume loop (`SessionQueueConsumer`)
162
+
163
+ `SessionQueueConsumer` is the recommended way to consume sessions: it runs `max_concurrent_sessions` independent slots, each looping over its own `consume_session` stream - claim a session, hand each delivered item to your handler, ack or dead-letter it, repeat until the session drains, then claim another. No manual lease heartbeating is needed; the server renews the lease on its own schedule for as long as the stream stays open.
164
+
165
+ ```python
166
+ from daprmq_client import SessionHandlerFailureAction, SessionQueueConsumer, SessionQueueConsumerOptions
167
+
168
+ options = SessionQueueConsumerOptions(
169
+ max_concurrent_sessions=8,
170
+ lease_seconds=30,
171
+ prefetch_count=1,
172
+ on_handler_exception=SessionHandlerFailureAction.DEAD_LETTER_MESSAGE,
173
+ )
174
+
175
+ async def handler(context):
176
+ # context.session_id, context.lock_id, context.item, context.priority
177
+ await process(context.item)
178
+ # returning normally acks the item; raising triggers on_handler_exception's behavior
179
+
180
+ async with SessionQueueConsumer(client, "my-queue", options, handler):
181
+ ... # consumer.start() ran on entry; consumer.stop() runs on exit
182
+ ```
183
+
184
+ `stop()` stops claiming sessions and closes idle streams at once. A handler that is running finishes and its message is settled (acked, or per `on_handler_exception`) before its stream closes; prefetched messages not yet handled return with their session. Slot tasks still running after `drain_timeout_seconds` (default 30) are cancelled, which raises `CancelledError` in the handler. `stop()` returns once every stream has closed, so the sessions are released by then. A `consume_session` stream stopped by its `cancel` event, by leaving the `async for` (close it with `contextlib.aclosing` to wait), or by an error half-closes: settlements already sent are applied before the session is released, and the call is cancelled only if the server hasn't ended it within 5 s. Settling after that raises `DaprMQError`.
185
+
186
+ `session_idle_timeout_seconds` releases a session once no message has arrived for that long, so the slot moves on to another (default 0 = the server default, `lease_seconds`). Lower it when sessions are short and publishers don't add to them later; it's also a `consume_session` argument.
187
+
188
+ `on_handler_exception` is one of `DEAD_LETTER_MESSAGE` (default), `NACK_MESSAGE` (return the item to the front of the session for redelivery - counts toward the server's max delivery count, past which it is dead-lettered), `ABANDON_SESSION`, or `BOTH`. Session ordering holds only at the default prefetch of 1: with a larger prefetch, items already delivered are handled before a nacked item comes back.
189
+
190
+ `await client.acknowledge_batch(queue_id, lock_ids, lease_id=...)` settles up to 1,000 locks in one call (one actor turn, one state save), typically everything a bulk `dequeue_locked(count=n)` returned. It returns `AcknowledgeBatchResult(items_acknowledged, results)` with one `LockAcknowledgeResult(lock_id, outcome)` per lock in request order; `outcome` is one of the `AcknowledgeOutcome` constants (`ACKNOWLEDGED`, `LOCK_NOT_FOUND`, `LOCK_EXPIRED`, `INVALID_LOCK_ID`). A lock that can't be settled never fails the others; only a whole-call problem raises (`SessionLeaseExpiredError`, `InvalidLeaseIdError`, `ValidationError` for an empty list, more than 1,000 ids or duplicates). An unknown outcome is retried automatically, so after a retry `LOCK_NOT_FOUND` can mean the first attempt already settled that lock.
191
+
192
+ `await client.nack(queue_id, lock_id, lease_id=...)` (and `await delivery.nack()` on a `SessionDelivery`) returns a locked item to its original position; it returns `NackResult(dead_lettered, delivery_count, dlq_id)`.
193
+
194
+ or without the context manager:
195
+
196
+ ```python
197
+ consumer = SessionQueueConsumer(client, "my-queue", options, handler)
198
+ consumer.start()
199
+ # ... run your application ...
200
+ await consumer.stop() # stops claiming, lets in-flight handlers settle, closes streams
201
+ ```
202
+
203
+ `SessionMessageContext` deliberately has no `lease_id` - the `ConsumeSession` wire protocol never exposes one to the client (the server tracks it internally and applies it when calling `acknowledge`/`dead_letter` on your behalf), which is exactly what makes the managed loop simpler than the manual API above.
204
+
205
+ Sticky routing to one specific session: set `target_session_id` alongside `max_concurrent_sessions=1` (any other combination raises `ValueError` - a targeted claim only ever occupies one slot).
206
+
207
+ On a failed claim (no session currently available), a slot backs off with a doubling/cap/reset-on-success shape (`min_backoff_seconds` → `max_backoff_seconds`, reset to `min_backoff_seconds` the moment a claim succeeds).
208
+
209
+ ### Why one shared client
210
+
211
+ **All of a `SessionQueueConsumer`'s `max_concurrent_sessions` slots share the single `DaprMQClient` (and its one gRPC channel) passed into its constructor** - never construct a separate `DaprMQClient` per slot. A gRPC channel multiplexes every RPC, including long-lived streams, over one (or a small number of, if the server's per-connection stream cap is exceeded) underlying HTTP/2 connection - this is what makes running 10s-100s of concurrent `consume_session` streams cheap. Giving each slot its own channel would open that many separate HTTP/2 connections for no benefit - see the "multiplexing many sessions over one stream" discussion in [design/sessions.md](../../../docs/design/sessions.md) for the full reasoning.
212
+
213
+ ## Testing your own code against this SDK
214
+
215
+ `DaprMQClient`'s `http_client`/`grpc_stub` constructor arguments are DI/test seams - substitute a fake `httpx.AsyncTransport` and a fake gRPC stub to exercise code that depends on `DaprMQClient` without a live server. See `sdks/python/tests/fake_transport.py` and `sdks/python/tests/fake_grpc_stub.py` for the pattern this SDK's own test suite uses.
File without changes