taskqueue-toolkit 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 (28) hide show
  1. taskqueue_toolkit-0.1.0/LICENSE +202 -0
  2. taskqueue_toolkit-0.1.0/PKG-INFO +163 -0
  3. taskqueue_toolkit-0.1.0/README.md +128 -0
  4. taskqueue_toolkit-0.1.0/pyproject.toml +92 -0
  5. taskqueue_toolkit-0.1.0/pyproject.toml.orig +84 -0
  6. taskqueue_toolkit-0.1.0/src/taskqueue_toolkit/__init__.py +0 -0
  7. taskqueue_toolkit-0.1.0/src/taskqueue_toolkit/outbox/__init__.py +0 -0
  8. taskqueue_toolkit-0.1.0/src/taskqueue_toolkit/outbox/orm.py +47 -0
  9. taskqueue_toolkit-0.1.0/src/taskqueue_toolkit/outbox/relay.py +59 -0
  10. taskqueue_toolkit-0.1.0/src/taskqueue_toolkit/outbox/repository.py +107 -0
  11. taskqueue_toolkit-0.1.0/src/taskqueue_toolkit/py.typed +0 -0
  12. taskqueue_toolkit-0.1.0/src/taskqueue_toolkit/queue/__init__.py +0 -0
  13. taskqueue_toolkit-0.1.0/src/taskqueue_toolkit/queue/aws_session.py +19 -0
  14. taskqueue_toolkit-0.1.0/src/taskqueue_toolkit/queue/dsn.py +147 -0
  15. taskqueue_toolkit-0.1.0/src/taskqueue_toolkit/queue/factory.py +94 -0
  16. taskqueue_toolkit-0.1.0/src/taskqueue_toolkit/queue/pubsub.py +162 -0
  17. taskqueue_toolkit-0.1.0/src/taskqueue_toolkit/queue/rabbitmq.py +74 -0
  18. taskqueue_toolkit-0.1.0/src/taskqueue_toolkit/queue/redis_streams.py +117 -0
  19. taskqueue_toolkit-0.1.0/src/taskqueue_toolkit/queue/registry.py +53 -0
  20. taskqueue_toolkit-0.1.0/src/taskqueue_toolkit/queue/sns.py +162 -0
  21. taskqueue_toolkit-0.1.0/src/taskqueue_toolkit/queue/sqs.py +103 -0
  22. taskqueue_toolkit-0.1.0/src/taskqueue_toolkit/queue/task_queue.py +62 -0
  23. taskqueue_toolkit-0.1.0/src/taskqueue_toolkit/testing/__init__.py +58 -0
  24. taskqueue_toolkit-0.1.0/src/taskqueue_toolkit/testing/pubsub.py +149 -0
  25. taskqueue_toolkit-0.1.0/src/taskqueue_toolkit/testing/rabbitmq.py +135 -0
  26. taskqueue_toolkit-0.1.0/src/taskqueue_toolkit/testing/redis_streams.py +141 -0
  27. taskqueue_toolkit-0.1.0/src/taskqueue_toolkit/testing/sns.py +155 -0
  28. taskqueue_toolkit-0.1.0/src/taskqueue_toolkit/testing/sqs.py +109 -0
@@ -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 2026 Walid Boughdiri
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,163 @@
1
+ Metadata-Version: 2.4
2
+ Name: taskqueue-toolkit
3
+ Version: 0.1.0
4
+ Summary: Broker-agnostic async task queue (RabbitMQ, SQS, SNS, Redis Streams, Pub/Sub) with a Postgres outbox pattern
5
+ Author: Walid Boughdiri
6
+ Author-email: Walid Boughdiri <walid.boughdiri@gmail.com>
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Topic :: Software Development :: Libraries
15
+ Classifier: Topic :: System :: Distributed Computing
16
+ Classifier: Typing :: Typed
17
+ Requires-Dist: aio-pika>=9.4.0 ; extra == 'all'
18
+ Requires-Dist: redis>=5.0.0 ; extra == 'all'
19
+ Requires-Dist: aioboto3>=13.0.0 ; extra == 'all'
20
+ Requires-Dist: google-cloud-pubsub>=2.21.0 ; extra == 'all'
21
+ Requires-Dist: sqlalchemy[asyncio]>=2.0.36 ; extra == 'all'
22
+ Requires-Dist: aioboto3>=13.0.0 ; extra == 'aws'
23
+ Requires-Dist: sqlalchemy[asyncio]>=2.0.36 ; extra == 'outbox'
24
+ Requires-Dist: google-cloud-pubsub>=2.21.0 ; extra == 'pubsub'
25
+ Requires-Dist: aio-pika>=9.4.0 ; extra == 'rabbitmq'
26
+ Requires-Dist: redis>=5.0.0 ; extra == 'redis-streams'
27
+ Requires-Python: >=3.12
28
+ Provides-Extra: all
29
+ Provides-Extra: aws
30
+ Provides-Extra: outbox
31
+ Provides-Extra: pubsub
32
+ Provides-Extra: rabbitmq
33
+ Provides-Extra: redis-streams
34
+ Description-Content-Type: text/markdown
35
+
36
+ # taskqueue-toolkit
37
+
38
+ Broker-agnostic async task queue for Python — RabbitMQ, SQS, SNS, Redis Streams, and Google Pub/Sub behind one `TaskQueue[T]` interface, plus an optional Postgres-backed outbox pattern.
39
+
40
+ ## Why
41
+
42
+ Publishing/consuming a task shouldn't couple your code to one broker's client library. This package gives you:
43
+
44
+ - **One interface**: `publish(task)`, `consume() -> AsyncIterator[QueuedTask[T]]`, `ack()`/`nack(requeue=...)` — nothing broker-specific (no routing keys, topics, partitions, or consumer groups baked into the contract).
45
+ - **One connection string**: a single DSN's scheme picks the broker; everything else (queue/topic name, region, credentials, emulator endpoint, consumer group) travels as query params on the same string.
46
+ - **Generic over your payload**: `TaskQueue[T]` — bring your own task type and an `encode`/`decode` pair (`T -> bytes` / `bytes -> T`). This package has no opinion on serialization.
47
+ - **An optional outbox pattern**: write a task to Postgres in the same transaction as the state change that produced it, then let a background relay deliver it to the broker — no dual-write race between your database and your broker.
48
+
49
+ ## Install
50
+
51
+ ```bash
52
+ pip install taskqueue-toolkit[rabbitmq] # or: redis-streams, aws, pubsub, outbox, all
53
+ ```
54
+
55
+ ## Usage
56
+
57
+ ```python
58
+ from taskqueue_toolkit.queue.factory import create_task_queue
59
+
60
+ queue = create_task_queue(
61
+ "amqp://guest:guest@localhost:5672/?queue=my.tasks",
62
+ encode=lambda task: task.encode(),
63
+ decode=lambda body: body.decode(),
64
+ )
65
+
66
+ await queue.publish("hello")
67
+
68
+ async for queued in queue.consume():
69
+ print(queued.task)
70
+ await queued.ack()
71
+ ```
72
+
73
+ ### DSN schemes
74
+
75
+ | Scheme | Broker | Example |
76
+ |---|---|---|
77
+ | `amqp` / `amqps` | RabbitMQ | `amqp://guest:guest@host:5672/?queue=my.tasks` |
78
+ | `redis` / `rediss` | Redis Streams | `redis://:password@host:6379/0?stream=my.tasks&group=workers&consumer=worker-1` |
79
+ | `sqs` | Amazon SQS | `sqs://eu-west-3/my.tasks?endpoint_url=...&access_key_id=...&secret_access_key=...` |
80
+ | `sns` | Amazon SNS (fan-out) | `sns://eu-west-3/my-tasks?endpoint_url=...&access_key_id=...&secret_access_key=...` |
81
+ | `pubsub` | Google Pub/Sub | `pubsub://project-id/my-tasks?subscription=my-tasks-subscriber&emulator_host=localhost:8085` |
82
+
83
+ ### Adding a broker this package doesn't ship
84
+
85
+ The five schemes above are built in and checked for exhaustiveness at type-check time — `create_task_queue()` can't silently forget one. For a broker outside that list (Kafka, NATS, ...), register a handler once, at import/startup time, instead of forking the package:
86
+
87
+ ```python
88
+ from taskqueue_toolkit.queue.registry import register_scheme
89
+
90
+
91
+ def build_kafka_queue(dsn, encode, decode):
92
+ return MyKafkaTaskQueue(dsn=dsn, encode=encode, decode=decode)
93
+
94
+
95
+ register_scheme("kafka", build_kafka_queue)
96
+
97
+ queue = create_task_queue("kafka://localhost:9092/my-tasks", encode=..., decode=...)
98
+ ```
99
+
100
+ A handler receives the raw DSN string plus the `encode`/`decode` pair and returns a `TaskQueue[T]` — parsing and construction happen together, so there's a single call to keep in sync, not a parser and a constructor spread across two files.
101
+
102
+ ### Outbox pattern
103
+
104
+ ```python
105
+ from taskqueue_toolkit.outbox.repository import OutboxRepository
106
+ from taskqueue_toolkit.outbox.relay import OutboxRelay
107
+
108
+ outbox = OutboxRepository(session=session, encode=encode, decode=decode)
109
+
110
+ # Inside the same transaction as your domain state change:
111
+ await outbox.enqueue(task)
112
+ await session.commit()
113
+
114
+ # In a background worker/process:
115
+ relay = OutboxRelay(outbox=outbox, task_queue=queue)
116
+ await relay.run_forever()
117
+ ```
118
+
119
+ `OutboxRepository`/`OutboxRelay` are generic over the same `T` as `TaskQueue[T]`. Create the `outbox` table (`taskqueue_toolkit.outbox.orm.Base.metadata`) via your own migration tooling (Alembic, etc.).
120
+
121
+ **Database support**: only **Postgres** is tested and guaranteed — `claim_pending()`'s `SELECT ... FOR UPDATE SKIP LOCKED` concurrency guarantee is verified against a real Postgres in this package's own test suite (multiple relay instances racing to claim the same batch). MySQL 8.0+/MariaDB 10.6+ support the same `SKIP LOCKED` syntax through SQLAlchemy and may well work, but that combination isn't exercised by any test here — treat it as unverified, not supported, until you've validated the concurrent-claim behavior yourself against your actual engine/version. Older MySQL/MariaDB versions don't support `SKIP LOCKED` at all. SQLite works for single-writer tests (no real concurrent locking) but never for this guarantee under load.
122
+
123
+ **No NoSQL support (yet)**: the outbox is built directly on SQLAlchemy (`DeclarativeBase`, `select(...).with_for_update(skip_locked=True)`, `AsyncSession`) — this isn't a dialect difference to configure around, it's a relational, transactional row-locking primitive that document/key-value/wide-column stores (MongoDB, DynamoDB, Redis, Cassandra, ...) don't expose in an equivalent form. Adding NoSQL support is tracked as a future feature — it would need a separate `OutboxRepository` implementation per store family, each with its own concurrency mechanism in place of `SKIP LOCKED` (e.g. MongoDB's atomic `findOneAndUpdate`, DynamoDB's conditional `UpdateItem`), and would only preserve the outbox pattern's core guarantee (the task write and the domain state write land in the same transaction) when the outbox table lives in the same transactional store as the domain data it follows from — an outbox in a different store than your domain data reintroduces the dual-write race this pattern exists to avoid.
124
+
125
+ ### Testing your own code
126
+
127
+ `taskqueue_toolkit.testing` ships an in-memory double for each broker adapter — a real, working implementation of the relevant slice of its SDK (FIFO ordering, ack/nack, consumer groups, fan-out, ...), not a call-recording mock — so you can test code that publishes/consumes tasks without a real RabbitMQ/SQS/SNS/Redis/Pub-Sub:
128
+
129
+ ```python
130
+ from taskqueue_toolkit.queue.rabbitmq import RabbitMqTaskQueue
131
+ from taskqueue_toolkit.testing import FakeRabbitMqBroker
132
+
133
+ broker = FakeRabbitMqBroker()
134
+ queue = RabbitMqTaskQueue(dsn=dsn, encode=encode, decode=decode, connect=broker.connect)
135
+
136
+ await queue.publish("hello")
137
+ async for queued in queue.consume():
138
+ assert queued.task == "hello"
139
+ await queued.ack()
140
+ break
141
+ ```
142
+
143
+ Each adapter constructor takes an injectable client/connection factory for exactly this (`connect=` for RabbitMQ, `client_factory=` for SQS/SNS/Redis Streams, `publisher_factory=`/`subscriber_factory=` for Pub/Sub) — defaulting to the real SDK, so passing nothing behaves exactly as before.
144
+
145
+ | Fake | Inject into | Requires |
146
+ |---|---|---|
147
+ | `FakeRabbitMqBroker` | `RabbitMqTaskQueue(connect=broker.connect)` | nothing extra |
148
+ | `FakeSqsBroker` | `SqsTaskQueue(client_factory=broker.client)` | `[aws]` |
149
+ | `FakeSnsBroker` | `SnsTaskQueue(client_factory=broker.client)` | `[aws]` |
150
+ | `FakeRedisStreamsBroker` | `RedisStreamsTaskQueue(client_factory=broker.client)` | `[redis-streams]` |
151
+ | `FakePubsubBroker` | `PubsubTaskQueue(publisher_factory=broker.publisher, subscriber_factory=broker.subscriber)` | `[pubsub]` |
152
+
153
+ Create one broker instance per test — each owns its own isolated in-memory state, so there's nothing to reset between tests and no risk of one test's queue leaking into another's.
154
+
155
+ ## Development
156
+
157
+ ```bash
158
+ uv sync --all-extras
159
+ uv run pytest
160
+ uv run ruff check .
161
+ uv run ruff format .
162
+ uv run mypy .
163
+ ```
@@ -0,0 +1,128 @@
1
+ # taskqueue-toolkit
2
+
3
+ Broker-agnostic async task queue for Python — RabbitMQ, SQS, SNS, Redis Streams, and Google Pub/Sub behind one `TaskQueue[T]` interface, plus an optional Postgres-backed outbox pattern.
4
+
5
+ ## Why
6
+
7
+ Publishing/consuming a task shouldn't couple your code to one broker's client library. This package gives you:
8
+
9
+ - **One interface**: `publish(task)`, `consume() -> AsyncIterator[QueuedTask[T]]`, `ack()`/`nack(requeue=...)` — nothing broker-specific (no routing keys, topics, partitions, or consumer groups baked into the contract).
10
+ - **One connection string**: a single DSN's scheme picks the broker; everything else (queue/topic name, region, credentials, emulator endpoint, consumer group) travels as query params on the same string.
11
+ - **Generic over your payload**: `TaskQueue[T]` — bring your own task type and an `encode`/`decode` pair (`T -> bytes` / `bytes -> T`). This package has no opinion on serialization.
12
+ - **An optional outbox pattern**: write a task to Postgres in the same transaction as the state change that produced it, then let a background relay deliver it to the broker — no dual-write race between your database and your broker.
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ pip install taskqueue-toolkit[rabbitmq] # or: redis-streams, aws, pubsub, outbox, all
18
+ ```
19
+
20
+ ## Usage
21
+
22
+ ```python
23
+ from taskqueue_toolkit.queue.factory import create_task_queue
24
+
25
+ queue = create_task_queue(
26
+ "amqp://guest:guest@localhost:5672/?queue=my.tasks",
27
+ encode=lambda task: task.encode(),
28
+ decode=lambda body: body.decode(),
29
+ )
30
+
31
+ await queue.publish("hello")
32
+
33
+ async for queued in queue.consume():
34
+ print(queued.task)
35
+ await queued.ack()
36
+ ```
37
+
38
+ ### DSN schemes
39
+
40
+ | Scheme | Broker | Example |
41
+ |---|---|---|
42
+ | `amqp` / `amqps` | RabbitMQ | `amqp://guest:guest@host:5672/?queue=my.tasks` |
43
+ | `redis` / `rediss` | Redis Streams | `redis://:password@host:6379/0?stream=my.tasks&group=workers&consumer=worker-1` |
44
+ | `sqs` | Amazon SQS | `sqs://eu-west-3/my.tasks?endpoint_url=...&access_key_id=...&secret_access_key=...` |
45
+ | `sns` | Amazon SNS (fan-out) | `sns://eu-west-3/my-tasks?endpoint_url=...&access_key_id=...&secret_access_key=...` |
46
+ | `pubsub` | Google Pub/Sub | `pubsub://project-id/my-tasks?subscription=my-tasks-subscriber&emulator_host=localhost:8085` |
47
+
48
+ ### Adding a broker this package doesn't ship
49
+
50
+ The five schemes above are built in and checked for exhaustiveness at type-check time — `create_task_queue()` can't silently forget one. For a broker outside that list (Kafka, NATS, ...), register a handler once, at import/startup time, instead of forking the package:
51
+
52
+ ```python
53
+ from taskqueue_toolkit.queue.registry import register_scheme
54
+
55
+
56
+ def build_kafka_queue(dsn, encode, decode):
57
+ return MyKafkaTaskQueue(dsn=dsn, encode=encode, decode=decode)
58
+
59
+
60
+ register_scheme("kafka", build_kafka_queue)
61
+
62
+ queue = create_task_queue("kafka://localhost:9092/my-tasks", encode=..., decode=...)
63
+ ```
64
+
65
+ A handler receives the raw DSN string plus the `encode`/`decode` pair and returns a `TaskQueue[T]` — parsing and construction happen together, so there's a single call to keep in sync, not a parser and a constructor spread across two files.
66
+
67
+ ### Outbox pattern
68
+
69
+ ```python
70
+ from taskqueue_toolkit.outbox.repository import OutboxRepository
71
+ from taskqueue_toolkit.outbox.relay import OutboxRelay
72
+
73
+ outbox = OutboxRepository(session=session, encode=encode, decode=decode)
74
+
75
+ # Inside the same transaction as your domain state change:
76
+ await outbox.enqueue(task)
77
+ await session.commit()
78
+
79
+ # In a background worker/process:
80
+ relay = OutboxRelay(outbox=outbox, task_queue=queue)
81
+ await relay.run_forever()
82
+ ```
83
+
84
+ `OutboxRepository`/`OutboxRelay` are generic over the same `T` as `TaskQueue[T]`. Create the `outbox` table (`taskqueue_toolkit.outbox.orm.Base.metadata`) via your own migration tooling (Alembic, etc.).
85
+
86
+ **Database support**: only **Postgres** is tested and guaranteed — `claim_pending()`'s `SELECT ... FOR UPDATE SKIP LOCKED` concurrency guarantee is verified against a real Postgres in this package's own test suite (multiple relay instances racing to claim the same batch). MySQL 8.0+/MariaDB 10.6+ support the same `SKIP LOCKED` syntax through SQLAlchemy and may well work, but that combination isn't exercised by any test here — treat it as unverified, not supported, until you've validated the concurrent-claim behavior yourself against your actual engine/version. Older MySQL/MariaDB versions don't support `SKIP LOCKED` at all. SQLite works for single-writer tests (no real concurrent locking) but never for this guarantee under load.
87
+
88
+ **No NoSQL support (yet)**: the outbox is built directly on SQLAlchemy (`DeclarativeBase`, `select(...).with_for_update(skip_locked=True)`, `AsyncSession`) — this isn't a dialect difference to configure around, it's a relational, transactional row-locking primitive that document/key-value/wide-column stores (MongoDB, DynamoDB, Redis, Cassandra, ...) don't expose in an equivalent form. Adding NoSQL support is tracked as a future feature — it would need a separate `OutboxRepository` implementation per store family, each with its own concurrency mechanism in place of `SKIP LOCKED` (e.g. MongoDB's atomic `findOneAndUpdate`, DynamoDB's conditional `UpdateItem`), and would only preserve the outbox pattern's core guarantee (the task write and the domain state write land in the same transaction) when the outbox table lives in the same transactional store as the domain data it follows from — an outbox in a different store than your domain data reintroduces the dual-write race this pattern exists to avoid.
89
+
90
+ ### Testing your own code
91
+
92
+ `taskqueue_toolkit.testing` ships an in-memory double for each broker adapter — a real, working implementation of the relevant slice of its SDK (FIFO ordering, ack/nack, consumer groups, fan-out, ...), not a call-recording mock — so you can test code that publishes/consumes tasks without a real RabbitMQ/SQS/SNS/Redis/Pub-Sub:
93
+
94
+ ```python
95
+ from taskqueue_toolkit.queue.rabbitmq import RabbitMqTaskQueue
96
+ from taskqueue_toolkit.testing import FakeRabbitMqBroker
97
+
98
+ broker = FakeRabbitMqBroker()
99
+ queue = RabbitMqTaskQueue(dsn=dsn, encode=encode, decode=decode, connect=broker.connect)
100
+
101
+ await queue.publish("hello")
102
+ async for queued in queue.consume():
103
+ assert queued.task == "hello"
104
+ await queued.ack()
105
+ break
106
+ ```
107
+
108
+ Each adapter constructor takes an injectable client/connection factory for exactly this (`connect=` for RabbitMQ, `client_factory=` for SQS/SNS/Redis Streams, `publisher_factory=`/`subscriber_factory=` for Pub/Sub) — defaulting to the real SDK, so passing nothing behaves exactly as before.
109
+
110
+ | Fake | Inject into | Requires |
111
+ |---|---|---|
112
+ | `FakeRabbitMqBroker` | `RabbitMqTaskQueue(connect=broker.connect)` | nothing extra |
113
+ | `FakeSqsBroker` | `SqsTaskQueue(client_factory=broker.client)` | `[aws]` |
114
+ | `FakeSnsBroker` | `SnsTaskQueue(client_factory=broker.client)` | `[aws]` |
115
+ | `FakeRedisStreamsBroker` | `RedisStreamsTaskQueue(client_factory=broker.client)` | `[redis-streams]` |
116
+ | `FakePubsubBroker` | `PubsubTaskQueue(publisher_factory=broker.publisher, subscriber_factory=broker.subscriber)` | `[pubsub]` |
117
+
118
+ Create one broker instance per test — each owns its own isolated in-memory state, so there's nothing to reset between tests and no risk of one test's queue leaking into another's.
119
+
120
+ ## Development
121
+
122
+ ```bash
123
+ uv sync --all-extras
124
+ uv run pytest
125
+ uv run ruff check .
126
+ uv run ruff format .
127
+ uv run mypy .
128
+ ```
@@ -0,0 +1,92 @@
1
+ [project]
2
+ name = "taskqueue-toolkit"
3
+ version = "0.1.0"
4
+ description = "Broker-agnostic async task queue (RabbitMQ, SQS, SNS, Redis Streams, Pub/Sub) with a Postgres outbox pattern"
5
+ readme = "README.md"
6
+ license = "Apache-2.0"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.12"
9
+ dependencies = []
10
+ classifiers = [
11
+ "Development Status :: 3 - Alpha",
12
+ "Intended Audience :: Developers",
13
+ "Programming Language :: Python :: 3",
14
+ "Programming Language :: Python :: 3.12",
15
+ "Programming Language :: Python :: 3.13",
16
+ "Topic :: Software Development :: Libraries",
17
+ "Topic :: System :: Distributed Computing",
18
+ "Typing :: Typed",
19
+ ]
20
+
21
+ [[project.authors]]
22
+ name = "Walid Boughdiri"
23
+ email = "walid.boughdiri@gmail.com"
24
+
25
+ [project.optional-dependencies]
26
+ rabbitmq = ["aio-pika>=9.4.0"]
27
+ redis-streams = ["redis>=5.0.0"]
28
+ aws = ["aioboto3>=13.0.0"]
29
+ pubsub = ["google-cloud-pubsub>=2.21.0"]
30
+ outbox = ["sqlalchemy[asyncio]>=2.0.36"]
31
+ all = [
32
+ "aio-pika>=9.4.0",
33
+ "redis>=5.0.0",
34
+ "aioboto3>=13.0.0",
35
+ "google-cloud-pubsub>=2.21.0",
36
+ "sqlalchemy[asyncio]>=2.0.36",
37
+ ]
38
+
39
+ [dependency-groups]
40
+ dev = [
41
+ "pytest>=8.3.0",
42
+ "pytest-asyncio>=0.24.0",
43
+ "pytest-cov>=6.0.0",
44
+ "ruff>=0.7.0",
45
+ "mypy>=1.13.0",
46
+ "aiosqlite>=0.20.0",
47
+ "asyncpg>=0.30.0",
48
+ "types-aiobotocore[sqs,sns]>=2.0.0",
49
+ ]
50
+
51
+ [build-system]
52
+ requires = ["uv_build>=0.11.2,<0.12.0"]
53
+ build-backend = "uv_build"
54
+
55
+ [tool.uv.build-backend]
56
+ module-name = "taskqueue_toolkit"
57
+ module-root = "src"
58
+
59
+ [tool.pytest.ini_options]
60
+ testpaths = ["tests"]
61
+ asyncio_mode = "auto"
62
+
63
+ [tool.ruff]
64
+ line-length = 100
65
+ target-version = "py312"
66
+
67
+ [tool.ruff.lint]
68
+ select = [
69
+ "E",
70
+ "F",
71
+ "I",
72
+ "UP",
73
+ "B",
74
+ "SIM",
75
+ ]
76
+
77
+ [tool.mypy]
78
+ python_version = "3.12"
79
+ strict = true
80
+ disallow_untyped_defs = true
81
+
82
+ [[tool.mypy.overrides]]
83
+ module = "aioboto3"
84
+ ignore_missing_imports = true
85
+
86
+ [[tool.mypy.overrides]]
87
+ module = [
88
+ "google.cloud",
89
+ "google.cloud.pubsub_v1",
90
+ "google.api_core.exceptions",
91
+ ]
92
+ ignore_missing_imports = true
@@ -0,0 +1,84 @@
1
+ [project]
2
+ name = "taskqueue-toolkit"
3
+ version = "0.1.0"
4
+ description = "Broker-agnostic async task queue (RabbitMQ, SQS, SNS, Redis Streams, Pub/Sub) with a Postgres outbox pattern"
5
+ readme = "README.md"
6
+ license = "Apache-2.0"
7
+ license-files = ["LICENSE"]
8
+ authors = [
9
+ { name = "Walid Boughdiri", email = "walid.boughdiri@gmail.com" }
10
+ ]
11
+ requires-python = ">=3.12"
12
+ dependencies = []
13
+ classifiers = [
14
+ "Development Status :: 3 - Alpha",
15
+ "Intended Audience :: Developers",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3.12",
18
+ "Programming Language :: Python :: 3.13",
19
+ "Topic :: Software Development :: Libraries",
20
+ "Topic :: System :: Distributed Computing",
21
+ "Typing :: Typed",
22
+ ]
23
+
24
+ [project.optional-dependencies]
25
+ rabbitmq = ["aio-pika>=9.4.0"]
26
+ redis-streams = ["redis>=5.0.0"]
27
+ aws = ["aioboto3>=13.0.0"]
28
+ pubsub = ["google-cloud-pubsub>=2.21.0"]
29
+ outbox = ["sqlalchemy[asyncio]>=2.0.36"]
30
+ all = [
31
+ "aio-pika>=9.4.0",
32
+ "redis>=5.0.0",
33
+ "aioboto3>=13.0.0",
34
+ "google-cloud-pubsub>=2.21.0",
35
+ "sqlalchemy[asyncio]>=2.0.36",
36
+ ]
37
+
38
+ [dependency-groups]
39
+ dev = [
40
+ "pytest>=8.3.0",
41
+ "pytest-asyncio>=0.24.0",
42
+ "pytest-cov>=6.0.0",
43
+ "ruff>=0.7.0",
44
+ "mypy>=1.13.0",
45
+ "aiosqlite>=0.20.0",
46
+ "asyncpg>=0.30.0",
47
+ "types-aiobotocore[sqs,sns]>=2.0.0",
48
+ ]
49
+
50
+ [build-system]
51
+ requires = ["uv_build>=0.11.2,<0.12.0"]
52
+ build-backend = "uv_build"
53
+
54
+ [tool.uv.build-backend]
55
+ module-name = "taskqueue_toolkit"
56
+ module-root = "src"
57
+
58
+ [tool.pytest.ini_options]
59
+ testpaths = ["tests"]
60
+ asyncio_mode = "auto"
61
+
62
+ [tool.ruff]
63
+ line-length = 100
64
+ target-version = "py312"
65
+
66
+ [tool.ruff.lint]
67
+ select = ["E", "F", "I", "UP", "B", "SIM"]
68
+
69
+ [tool.mypy]
70
+ python_version = "3.12"
71
+ strict = true
72
+ disallow_untyped_defs = true
73
+
74
+ [[tool.mypy.overrides]]
75
+ # aioboto3 ships no py.typed marker and there's no separate types-aioboto3
76
+ # package (unlike aiobotocore, covered by types-aiobotocore above).
77
+ module = "aioboto3"
78
+ ignore_missing_imports = true
79
+
80
+ [[tool.mypy.overrides]]
81
+ # google-cloud-pubsub ships no py.typed marker and there's no separate
82
+ # types-google-cloud-pubsub package.
83
+ module = ["google.cloud", "google.cloud.pubsub_v1", "google.api_core.exceptions"]
84
+ ignore_missing_imports = true