dramatiq-sqs 0.2.0__tar.gz → 0.3.0.dev2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,111 @@
1
+ Metadata-Version: 2.4
2
+ Name: dramatiq-sqs
3
+ Version: 0.3.0.dev2
4
+ Summary: An Amazon SQS broker for Dramatiq.
5
+ Keywords: dramatiq,sqs
6
+ Author: Bogdan Paul Popa, Mikhail Bulash
7
+ License-Expression: Apache-2.0
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Classifier: Topic :: System :: Distributed Computing
17
+ Requires-Dist: boto3
18
+ Requires-Dist: dramatiq
19
+ Maintainer: Mikhail Bulash
20
+ Requires-Python: >=3.10
21
+ Project-URL: Repository, https://github.com/Bogdanp/dramatiq_sqs
22
+ Description-Content-Type: text/markdown
23
+
24
+ # dramatiq_sqs
25
+
26
+ A [Dramatiq] broker that can be used with [Amazon SQS].
27
+
28
+ This backend has a number of limitations compared to the built-in
29
+ Redis and RMQ backends:
30
+
31
+ * the max amount of time messages can be delayed by is 15 minutes,
32
+ * messages can be at most 1MiB large and
33
+ * messages must be processed within 12 hours of being pulled,
34
+ otherwise they will be redelivered.
35
+
36
+ The backend uses [boto3] under the hood. For details on how
37
+ authorization works, check out its [docs].
38
+
39
+
40
+ ## Installation
41
+
42
+ pip install dramatiq_sqs
43
+
44
+
45
+ ## Usage
46
+
47
+ ``` python
48
+ import dramatiq
49
+
50
+ from dramatiq.middleware import AgeLimit, TimeLimit, Callbacks, Pipelines, Prometheus, Retries
51
+ from dramatiq_sqs import SQSBroker
52
+
53
+ broker = SQSBroker(
54
+ namespace="dramatiq_sqs_tests",
55
+ middleware=[
56
+ Prometheus(),
57
+ AgeLimit(),
58
+ TimeLimit(),
59
+ Callbacks(),
60
+ Pipelines(),
61
+ Retries(min_backoff=1000, max_backoff=900000, max_retries=96),
62
+ ],
63
+ )
64
+ dramatiq.set_broker(broker)
65
+ ```
66
+
67
+
68
+ ## Usage with [ElasticMQ]
69
+
70
+ ``` python
71
+ broker = SQSBroker(
72
+ # ...
73
+ endpoint_url="http://127.0.0.1:9324",
74
+ )
75
+ ```
76
+
77
+ ## Example IAM Policy
78
+
79
+ Here are the IAM permissions needed by Dramatiq:
80
+
81
+ ``` json
82
+ {
83
+ "Version": "2012-10-17",
84
+ "Statement": [
85
+ {
86
+ "Effect": "Allow",
87
+ "Action": [
88
+ "sqs:CreateQueue",
89
+ "sqs:ReceiveMessage",
90
+ "sqs:DeleteMessage",
91
+ "sqs:DeleteMessageBatch",
92
+ "sqs:SendMessage",
93
+ "sqs:SendMessageBatch"
94
+ ],
95
+ "Resource": ["*"]
96
+ }
97
+ ]
98
+ }
99
+ ```
100
+
101
+ ## License
102
+
103
+ `dramatiq_sqs` is licensed under Apache 2.0.
104
+
105
+
106
+ [Dramatiq]: https://dramatiq.io
107
+ [Amazon SQS]: https://aws.amazon.com/sqs/
108
+ [boto3]: https://boto3.readthedocs.io/en/latest/
109
+ [docs]: https://boto3.readthedocs.io/en/latest/guide/quickstart.html#configuration
110
+ [LICENSE]: https://github.com/Bogdanp/dramatiq_sqs/blob/master/LICENSE
111
+ [ElasticMQ]: https://github.com/adamw/elasticmq
@@ -6,9 +6,9 @@ This backend has a number of limitations compared to the built-in
6
6
  Redis and RMQ backends:
7
7
 
8
8
  * the max amount of time messages can be delayed by is 15 minutes,
9
- * messages can be at most 256KiB large and
10
- * messages must be processed within 2 hours of being pulled, otherwise
11
- they will be redelivered.
9
+ * messages can be at most 1MiB large and
10
+ * messages must be processed within 12 hours of being pulled,
11
+ otherwise they will be redelivered.
12
12
 
13
13
  The backend uses [boto3] under the hood. For details on how
14
14
  authorization works, check out its [docs].
@@ -77,8 +77,7 @@ Here are the IAM permissions needed by Dramatiq:
77
77
 
78
78
  ## License
79
79
 
80
- dramatiq_sqs is licensed under Apache 2.0. Please see
81
- [LICENSE] for licensing details.
80
+ `dramatiq_sqs` is licensed under Apache 2.0.
82
81
 
83
82
 
84
83
  [Dramatiq]: https://dramatiq.io
@@ -0,0 +1,35 @@
1
+ [project]
2
+ name = "dramatiq-sqs"
3
+ description = "An Amazon SQS broker for Dramatiq."
4
+ license = "Apache-2.0"
5
+ keywords = ["dramatiq", "sqs"]
6
+ readme = "README.md"
7
+ authors = [{ name = "Bogdan Paul Popa" }, { name = "Mikhail Bulash" }]
8
+ maintainers = [{ name = "Mikhail Bulash" }]
9
+ classifiers = [
10
+ "Development Status :: 3 - Alpha",
11
+ "License :: OSI Approved :: Apache Software License",
12
+ "Programming Language :: Python :: 3",
13
+ "Programming Language :: Python :: 3.10",
14
+ "Programming Language :: Python :: 3.11",
15
+ "Programming Language :: Python :: 3.12",
16
+ "Programming Language :: Python :: 3.13",
17
+ "Programming Language :: Python :: 3.14",
18
+ "Topic :: System :: Distributed Computing",
19
+ ]
20
+ version = "0.3.0.dev2"
21
+ requires-python = ">=3.10"
22
+ dependencies = ["boto3", "dramatiq"]
23
+
24
+ [project.urls]
25
+ Repository = "https://github.com/Bogdanp/dramatiq_sqs"
26
+
27
+ [dependency-groups]
28
+ dev = ["flake8", "flake8-quotes", "isort", "mypy", "pytest", "pytest-cov"]
29
+
30
+ [build-system]
31
+ requires = ["uv_build>=0.9.8,<0.10.0"]
32
+ build-backend = "uv_build"
33
+
34
+ [tool.uv]
35
+ required-version = ">=0.9.8"
@@ -0,0 +1,10 @@
1
+ import importlib.metadata
2
+
3
+ from .broker import SQSBroker
4
+
5
+ __version__ = importlib.metadata.version("dramatiq_sqs")
6
+
7
+ __all__ = [
8
+ "SQSBroker",
9
+ "__version__",
10
+ ]
@@ -8,23 +8,29 @@ import boto3
8
8
  import dramatiq
9
9
  from dramatiq.logging import get_logger
10
10
 
11
+ # SQS quotas:
12
+ # https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/quotas-messages.html
13
+
11
14
  #: The max number of bytes in a message.
12
- MAX_MESSAGE_SIZE = 256 * 1024
15
+ MAX_MESSAGE_SIZE_BYTES = 1024 * 1024
13
16
 
14
17
  #: The min and max number of seconds messages may be retained for.
15
- MIN_MESSAGE_RETENTION = 60
16
- MAX_MESSAGE_RETENTION = 14 * 86400
18
+ MIN_MESSAGE_RETENTION_SECONDS = 60
19
+ MAX_MESSAGE_RETENTION_SECONDS = 14 * 86400
20
+
21
+ #: The maximum number of seconds SQS will wait for the message to be acked before
22
+ #: redelivering it.
23
+ MAX_VISIBILITY_TIMEOUT_SECONDS = 12 * 3600
17
24
 
18
- #: The maximum amount of time SQS will wait before redelivering a
19
- #: message. This is also the maximum amount of time that a message can
20
- #: be delayed for.
21
- MAX_VISIBILITY_TIMEOUT = 2 * 3600
25
+ #: The maximum number of seconds a message can be delayed for.
26
+ MAX_DELAY_SECONDS = 15 * 60
22
27
 
23
28
  #: The max number of messages that may be prefetched at a time.
24
29
  MAX_PREFETCH = 10
25
30
 
26
- #: The min value for WaitTimeSeconds.
27
- MIN_TIMEOUT = int(os.getenv("DRAMATIQ_SQS_MIN_TIMEOUT", "20"))
31
+ #: The max value for WaitTimeSeconds.
32
+ #: https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-short-and-long-polling.html#sqs-long-polling
33
+ MAX_WAIT_TIME_SECONDS = 20
28
34
 
29
35
  #: The number of times a message will be received before being added
30
36
  #: to the dead-letter queue (if enabled).
@@ -38,9 +44,9 @@ class SQSBroker(dramatiq.Broker):
38
44
  Redis and RMQ backends:
39
45
 
40
46
  * the max amount of time messages can be delayed by is 15 minutes,
41
- * messages can be at most 256KiB large,
42
- * messages must be processed within 2 hours of being pulled,
43
- otherwise they will be redelivered.
47
+ * messages can be at most 1MiB large and
48
+ * messages must be processed within 12 hours of being pulled,
49
+ otherwise they will be redelivered.
44
50
 
45
51
  The backend uses boto3_ under the hood. For details on how
46
52
  authorization works, check out its docs_.
@@ -65,22 +71,27 @@ class SQSBroker(dramatiq.Broker):
65
71
  self, *,
66
72
  namespace: Optional[str] = None,
67
73
  middleware: Optional[List[dramatiq.Middleware]] = None,
68
- retention: int = MAX_MESSAGE_RETENTION,
74
+ retention: int = MAX_MESSAGE_RETENTION_SECONDS,
69
75
  dead_letter: bool = False,
70
76
  max_receives: int = MAX_RECEIVES,
77
+ visibility_timeout: Optional[int] = MAX_VISIBILITY_TIMEOUT_SECONDS,
71
78
  tags: Optional[Dict[str, str]] = None,
72
79
  **options,
73
80
  ) -> None:
74
81
  super().__init__(middleware=middleware)
75
82
 
76
- if retention < MIN_MESSAGE_RETENTION or retention > MAX_MESSAGE_RETENTION:
77
- raise ValueError(f"'retention' must be between {MIN_MESSAGE_RETENTION} and {MAX_MESSAGE_RETENTION}.")
83
+ if retention < MIN_MESSAGE_RETENTION_SECONDS or retention > MAX_MESSAGE_RETENTION_SECONDS:
84
+ raise ValueError(
85
+ f"'retention' must be between {MIN_MESSAGE_RETENTION_SECONDS} seconds and "
86
+ f"{MAX_MESSAGE_RETENTION_SECONDS} seconds."
87
+ )
78
88
 
79
89
  self.namespace: Optional[str] = namespace
80
90
  self.retention: str = str(retention)
81
91
  self.queues: Dict[str, Any] = {}
82
92
  self.dead_letter: bool = dead_letter
83
93
  self.max_receives: int = max_receives
94
+ self.visibility_timeout = visibility_timeout
84
95
  self.tags: Optional[Dict[str, str]] = tags
85
96
  self.sqs: Any = boto3.resource("sqs", **options)
86
97
 
@@ -90,7 +101,12 @@ class SQSBroker(dramatiq.Broker):
90
101
 
91
102
  def consume(self, queue_name: str, prefetch: int = 1, timeout: int = 30000) -> dramatiq.Consumer:
92
103
  try:
93
- return self.consumer_class(self.queues[queue_name], prefetch, timeout)
104
+ return self.consumer_class(
105
+ self.queues[queue_name],
106
+ prefetch,
107
+ timeout,
108
+ visibility_timeout=self.visibility_timeout
109
+ )
94
110
  except KeyError: # pragma: no cover
95
111
  raise dramatiq.QueueNotFound(queue_name)
96
112
 
@@ -104,7 +120,8 @@ class SQSBroker(dramatiq.Broker):
104
120
  }
105
121
 
106
122
  self.emit_before("declare_queue", queue_name)
107
- self.queues[queue_name] = self.sqs.create_queue(
123
+
124
+ self.queues[queue_name] = self._get_or_create_queue(
108
125
  QueueName=prefixed_queue_name,
109
126
  Attributes={
110
127
  "MessageRetentionPeriod": self.retention,
@@ -118,7 +135,7 @@ class SQSBroker(dramatiq.Broker):
118
135
 
119
136
  if self.dead_letter:
120
137
  dead_letter_queue_name = f"{prefixed_queue_name}_dlq"
121
- dead_letter_queue = self.sqs.create_queue(
138
+ dead_letter_queue = self._get_or_create_queue(
122
139
  QueueName=dead_letter_queue_name
123
140
  )
124
141
  if self.tags:
@@ -135,20 +152,26 @@ class SQSBroker(dramatiq.Broker):
135
152
  })
136
153
  self.emit_after("declare_queue", queue_name)
137
154
 
155
+ def _get_or_create_queue(self, **kwargs) -> Any:
156
+ try:
157
+ return self.sqs.get_queue_by_name(QueueName=kwargs['QueueName'])
158
+ except self.sqs.meta.client.exceptions.QueueDoesNotExist:
159
+ self.logger.debug(f'Queue does not exist, creating queue with params: {kwargs}')
160
+ return self.sqs.create_queue(**kwargs)
161
+
138
162
  def enqueue(self, message: dramatiq.Message, *, delay: Optional[int] = None) -> dramatiq.Message:
139
163
  queue_name = message.queue_name
140
- if delay is None:
141
- queue = self.queues[queue_name]
142
- delay_seconds = 0
143
- elif delay <= 900000:
144
- queue = self.queues[queue_name]
145
- delay_seconds = int(delay / 1000)
146
- else:
147
- raise ValueError("Messages in SQS cannot be delayed for longer than 15 minutes.")
164
+ queue = self.queues[queue_name]
165
+ delay_seconds = (delay or 0) // 1000
166
+
167
+ if delay_seconds > MAX_DELAY_SECONDS:
168
+ raise ValueError(
169
+ f"Messages in SQS cannot be delayed for longer than {MAX_DELAY_SECONDS} seconds."
170
+ )
148
171
 
149
172
  encoded_message = b64encode(message.encode()).decode()
150
- if len(encoded_message) > MAX_MESSAGE_SIZE:
151
- raise RuntimeError("Messages in SQS can be at most 256KiB large.")
173
+ if len(encoded_message) > MAX_MESSAGE_SIZE_BYTES:
174
+ raise RuntimeError("Messages in SQS can be at most {MAX_MESSAGE_SIZE_BYTES} bytes large.")
152
175
 
153
176
  self.logger.debug("Enqueueing message %r on queue %r.", message.message_id, queue_name)
154
177
  self.emit_before("enqueue", message, delay)
@@ -167,12 +190,34 @@ class SQSBroker(dramatiq.Broker):
167
190
 
168
191
 
169
192
  class SQSConsumer(dramatiq.Consumer):
170
- def __init__(self, queue: Any, prefetch: int, timeout: int) -> None:
193
+ def __init__(
194
+ self,
195
+ queue: Any,
196
+ prefetch: int,
197
+ timeout: int, *,
198
+ visibility_timeout: Optional[int] = None,
199
+ ) -> None:
171
200
  self.logger = get_logger(__name__, type(self))
172
201
  self.queue = queue
173
202
  self.prefetch = min(prefetch, MAX_PREFETCH)
174
- self.visibility_timeout = MAX_VISIBILITY_TIMEOUT
175
- self.timeout = timeout # UNUSED
203
+
204
+ self.visibility_timeout = visibility_timeout
205
+
206
+ if self.visibility_timeout is not None and self.visibility_timeout > MAX_VISIBILITY_TIMEOUT_SECONDS:
207
+ raise ValueError(
208
+ f"The message visibility timeout of {self.visibility_timeout} is higher than "
209
+ f"the maximum supported ({MAX_VISIBILITY_TIMEOUT_SECONDS})."
210
+ )
211
+
212
+
213
+ self.wait_time_seconds = timeout // 1000
214
+
215
+ if self.wait_time_seconds > MAX_WAIT_TIME_SECONDS:
216
+ raise ValueError(
217
+ f"The consumer timeout of {self.wait_time_seconds} is higher than "
218
+ f"the maximum supported ({MAX_WAIT_TIME_SECONDS})."
219
+ )
220
+
176
221
  self.messages: deque = deque()
177
222
  self.message_refc = 0
178
223
 
@@ -185,28 +230,20 @@ class SQSConsumer(dramatiq.Consumer):
185
230
 
186
231
  def requeue(self, messages: Iterable["_SQSMessage"]) -> None:
187
232
  for batch in chunk(messages, chunksize=10):
188
- # Re-enqueue batches of up to 10 messages.
189
- send_response = self.queue.send_messages(Entries=[{
190
- "Id": str(i),
191
- "MessageBody": message._sqs_message.body,
192
- } for i, message in enumerate(batch)])
193
-
194
- # Then delete the ones that were successfully re-enqueued.
195
- # The rest will have to wait until their visibility
196
- # timeout expires.
197
- failed_message_ids = [int(res["Id"]) for res in send_response.get("Failed", [])]
198
- requeued_messages = [m for i, m in enumerate(batch) if i not in failed_message_ids]
199
- self.queue.delete_messages(Entries=[{
233
+ # Setting the VisibilityTimeout to 0 makes the messages immediately visible again.
234
+ response = self.queue.change_message_visibility_batch(Entries=[{
200
235
  "Id": str(i),
201
236
  "ReceiptHandle": message._sqs_message.receipt_handle,
202
- } for i, message in enumerate(requeued_messages)])
237
+ "VisibilityTimeout": 0,
238
+ } for i, message in enumerate(batch)])
203
239
 
240
+ requeued_messages = response.get("Successful", [])
204
241
  self.message_refc -= len(requeued_messages)
205
242
 
206
243
  def __next__(self) -> Optional[dramatiq.Message]:
207
244
  kw = {
208
245
  "MaxNumberOfMessages": self.prefetch,
209
- "WaitTimeSeconds": MIN_TIMEOUT,
246
+ "WaitTimeSeconds": self.wait_time_seconds,
210
247
  }
211
248
  if self.visibility_timeout is not None:
212
249
  kw["VisibilityTimeout"] = self.visibility_timeout
@@ -1,13 +0,0 @@
1
- Copyright 2018 Bogdan Paul Popa
2
-
3
- Licensed under the Apache License, Version 2.0 (the "License");
4
- you may not use this file except in compliance with the License.
5
- You may obtain a copy of the License at
6
-
7
- http://www.apache.org/licenses/LICENSE-2.0
8
-
9
- Unless required by applicable law or agreed to in writing, software
10
- distributed under the License is distributed on an "AS IS" BASIS,
11
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- See the License for the specific language governing permissions and
13
- limitations under the License.
@@ -1,9 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: dramatiq_sqs
3
- Version: 0.2.0
4
- Summary: An Amazon SQS broker for Dramatiq.
5
- Requires-Python: >=3.5
6
- Provides-Extra: dev
7
- License-File: LICENSE
8
-
9
- Visit https://github.com/Bogdanp/dramatiq_sqs for more information.
@@ -1,8 +0,0 @@
1
- from .broker import SQSBroker
2
-
3
- __version__ = "0.2.0"
4
-
5
- __all__ = [
6
- "SQSBroker",
7
- "__version__",
8
- ]
@@ -1,9 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: dramatiq-sqs
3
- Version: 0.2.0
4
- Summary: An Amazon SQS broker for Dramatiq.
5
- Requires-Python: >=3.5
6
- Provides-Extra: dev
7
- License-File: LICENSE
8
-
9
- Visit https://github.com/Bogdanp/dramatiq_sqs for more information.
@@ -1,13 +0,0 @@
1
- LICENSE
2
- README.md
3
- setup.cfg
4
- setup.py
5
- dramatiq_sqs/__init__.py
6
- dramatiq_sqs/broker.py
7
- dramatiq_sqs.egg-info/PKG-INFO
8
- dramatiq_sqs.egg-info/SOURCES.txt
9
- dramatiq_sqs.egg-info/dependency_links.txt
10
- dramatiq_sqs.egg-info/requires.txt
11
- dramatiq_sqs.egg-info/top_level.txt
12
- tests/test_broker.py
13
- tests/test_utils.py
@@ -1,12 +0,0 @@
1
- boto3
2
- dramatiq
3
-
4
- [dev]
5
- bumpversion
6
- flake8
7
- flake8-quotes
8
- isort
9
- mypy
10
- pytest
11
- pytest-cov
12
- twine
@@ -1 +0,0 @@
1
- dramatiq_sqs
@@ -1,18 +0,0 @@
1
- [tool:pytest]
2
- testpaths = tests
3
- addopts = --cov dramatiq_sqs --cov-report html
4
-
5
- [pep8]
6
- max-line-length = 120
7
-
8
- [flake8]
9
- ignore = E402,F403,F811
10
- max-complexity = 20
11
- max-line-length = 120
12
- inline-quotes = double
13
- multiline-quotes = double
14
-
15
- [egg_info]
16
- tag_build =
17
- tag_date = 0
18
-
@@ -1,41 +0,0 @@
1
- import os
2
-
3
- from setuptools import setup
4
-
5
-
6
- def rel(*xs):
7
- return os.path.join(os.path.abspath(os.path.dirname(__file__)), *xs)
8
-
9
-
10
- with open(rel("dramatiq_sqs", "__init__.py"), "r") as f:
11
- version_marker = "__version__ = "
12
- for line in f:
13
- if line.startswith(version_marker):
14
- _, version = line.split(version_marker)
15
- version = version.strip().strip('"')
16
- break
17
- else:
18
- raise RuntimeError("Version marker not found.")
19
-
20
- setup(
21
- name="dramatiq_sqs",
22
- version=version,
23
- description="An Amazon SQS broker for Dramatiq.",
24
- long_description="Visit https://github.com/Bogdanp/dramatiq_sqs for more information.",
25
- packages=["dramatiq_sqs"],
26
- include_package_data=True,
27
- install_requires=["boto3", "dramatiq"],
28
- extras_require={
29
- "dev": [
30
- "bumpversion",
31
- "flake8",
32
- "flake8-quotes",
33
- "isort",
34
- "mypy",
35
- "pytest",
36
- "pytest-cov",
37
- "twine",
38
- ],
39
- },
40
- python_requires=">=3.5",
41
- )
@@ -1,185 +0,0 @@
1
- import json
2
- import time
3
-
4
- import dramatiq
5
- import pytest
6
- from botocore.stub import Stubber
7
-
8
- from dramatiq_sqs import SQSBroker
9
-
10
-
11
- def test_can_enqueue_and_process_messages(broker, worker, queue_name):
12
- # Given that I have an actor that stores incoming messages in a database
13
- db = []
14
-
15
- @dramatiq.actor(queue_name=queue_name)
16
- def do_work(x):
17
- db.append(x)
18
-
19
- # When I send that actor a message
20
- do_work.send(1)
21
-
22
- # And wait for it to be processed
23
- time.sleep(1)
24
-
25
- # Then the db should contain that message
26
- assert db == [1]
27
-
28
-
29
- def test_limits_prefetch_while_if_queue_is_full(broker, worker, queue_name):
30
- # Given that I have an actor that stores incoming messages in a database
31
- db = []
32
-
33
- # Set the worker prefetch limit to 1
34
- worker.queue_prefetch = 1
35
-
36
- # Add delay to actor logic to simulate processing time
37
- @dramatiq.actor(queue_name=queue_name)
38
- def do_work(x):
39
- db.append(x)
40
- time.sleep(10)
41
-
42
- # When I send that actor messages, it'll only prefetch and process a single message
43
- do_work.send(1)
44
- do_work.send(2)
45
-
46
- # Wait for message to be processed
47
- time.sleep(2)
48
-
49
- # Then the db should contain only that message, while it sleeps
50
- assert db == [1]
51
-
52
-
53
- def test_can_enqueue_delayed_messages(broker, worker, queue_name):
54
- # Given that I have an actor that stores incoming messages in a database
55
- db = []
56
-
57
- @dramatiq.actor(queue_name=queue_name)
58
- def do_work(x):
59
- db.append(x)
60
-
61
- # When I send that actor a delayed message
62
- start_time = time.time()
63
- do_work.send_with_options(args=(1,), delay=5000)
64
-
65
- # And poll the database for a result each second
66
- for _ in range(60):
67
- if db:
68
- break
69
-
70
- time.sleep(1)
71
-
72
- # Then the db should contain that message
73
- assert db == [1]
74
-
75
- # And an appropriate amount of time should have passed
76
- delta = time.time() - start_time
77
- assert delta >= 5
78
-
79
-
80
- def test_cant_delay_messages_for_longer_than_15_seconds(broker, queue_name):
81
- # Given that I have an actor
82
- @dramatiq.actor(queue_name=queue_name)
83
- def do_work():
84
- pass
85
-
86
- # When I attempt to send that actor a message farther than 15 minutes into the future
87
- # Then I should get back a ValueError
88
- with pytest.raises(ValueError):
89
- do_work.send_with_options(delay=3600000)
90
-
91
-
92
- def test_cant_enqueue_messages_that_are_too_large(broker, queue_name):
93
- # Given that I have an actor
94
- @dramatiq.actor(queue_name=queue_name)
95
- def do_work(s):
96
- pass
97
-
98
- # When I attempt to send that actor a message that's too large
99
- # Then a RuntimeError should be raised
100
- with pytest.raises(RuntimeError):
101
- do_work.send("a" * 512 * 1024)
102
-
103
-
104
- def test_retention_period_is_validated():
105
- # When I attempt to instantiate a broker with an invalid retention period
106
- # Then a ValueError should be raised
107
- with pytest.raises(ValueError):
108
- SQSBroker(retention=30 * 86400)
109
-
110
-
111
- def test_can_requeue_consumed_messages(broker, queue_name):
112
- # Given that I have an actor
113
- @dramatiq.actor(queue_name=queue_name)
114
- def do_work():
115
- pass
116
-
117
- # When I send that actor a message
118
- do_work.send()
119
-
120
- # And consume the message off the queue
121
- consumer = broker.consume(queue_name)
122
- first_message = next(consumer)
123
-
124
- # And requeue the message
125
- consumer.requeue([first_message])
126
-
127
- # Then I should be able to consume the message again immediately
128
- second_message = next(consumer)
129
- assert first_message == second_message
130
-
131
-
132
- def test_creates_dead_letter_queue():
133
- # Given that I have an SQS broker with dead letters turned on
134
- broker = SQSBroker(
135
- namespace="dramatiq_sqs_tests",
136
- dead_letter=True,
137
- max_receives=20,
138
- )
139
-
140
- # And I've stubbed out all the relevant API calls
141
- stubber = Stubber(broker.sqs.meta.client)
142
- stubber.add_response("create_queue", {"QueueUrl": ""})
143
- stubber.add_response("create_queue", {"QueueUrl": ""})
144
- stubber.add_response("get_queue_attributes", {"Attributes": {"QueueArn": "dlq"}})
145
- stubber.add_response("set_queue_attributes", {}, {
146
- "QueueUrl": "",
147
- "Attributes": {
148
- "RedrivePolicy": json.dumps({
149
- "deadLetterTargetArn": "dlq",
150
- "maxReceiveCount": "20"
151
- })
152
- }
153
- })
154
-
155
- # When I create a queue
156
- # Then a dead-letter queue should be created
157
- # And a redrive policy matching the queue and max receives should be added
158
- with stubber:
159
- broker.declare_queue("test")
160
- stubber.assert_no_pending_responses()
161
-
162
-
163
- def test_tags_queues_on_create():
164
- # Given that I have an SQS broker with tags
165
- broker = SQSBroker(
166
- namespace="dramatiq_sqs_tests",
167
- tags={"key1": "value1", "key2": "value2"}
168
- )
169
-
170
- # And I've stubbed out all the relevant API calls
171
- stubber = Stubber(broker.sqs.meta.client)
172
- stubber.add_response("create_queue", {"QueueUrl": ""})
173
- stubber.add_response("tag_queue", {}, {
174
- "QueueUrl": "",
175
- "Tags": {
176
- "key1": "value1",
177
- "key2": "value2"
178
- }
179
- })
180
-
181
- # When I create a queue
182
- # Then the queue should have the specified tags
183
- with stubber:
184
- broker.declare_queue("test")
185
- stubber.assert_no_pending_responses()
@@ -1,20 +0,0 @@
1
- from dramatiq_sqs.broker import chunk
2
-
3
-
4
- def test_chunk_can_split_iterators_into_chunks():
5
- # Given that I have a range from 0 to 12
6
- xs = range(13)
7
-
8
- # When I pass that range to chunk with a chunksize of 2
9
- chunks = chunk(xs, chunksize=2)
10
-
11
- # Then I should get back these chunks
12
- assert list(chunks) == [
13
- [0, 1],
14
- [2, 3],
15
- [4, 5],
16
- [6, 7],
17
- [8, 9],
18
- [10, 11],
19
- [12]
20
- ]