cfq 0.1.0__py3-none-any.whl

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.
cfq/__init__.py ADDED
@@ -0,0 +1,171 @@
1
+ import time
2
+ import asyncio
3
+ import logging
4
+ import inspect
5
+ import contextlib
6
+ from typing import Callable, Any, Awaitable
7
+
8
+ from cloudflare import AsyncCloudflare
9
+ from cloudflare.types.queues.message_pull_response import Message
10
+
11
+
12
+ class CFQ:
13
+ def __init__(
14
+ self,
15
+ api_token: str,
16
+ account_id: str,
17
+ *,
18
+ max_workers: int = 10,
19
+ polling_interval_ms: float = 1_000,
20
+ max_batch_size: int = 10,
21
+ allow_retry: bool = True,
22
+ retry_delay_seconds: int = 0,
23
+ heartbeat_interval_seconds: int = 0,
24
+ **kwargs,
25
+ ):
26
+ self.api_token = api_token
27
+ self.account_id = account_id
28
+ self.max_workers = max_workers
29
+ self.polling_interval_ms = polling_interval_ms
30
+ self.max_batch_size = max_batch_size
31
+ self.allow_retry = allow_retry
32
+ self.retry_delay_seconds = retry_delay_seconds
33
+ self.heartbeat_interval_seconds = heartbeat_interval_seconds
34
+
35
+ self._consumers = {}
36
+ self._poll_workers = []
37
+ self._client = None
38
+ self._heartbeat_task = None
39
+ self.messages_processed = 0
40
+ self._stop_event = asyncio.Event()
41
+
42
+ self.log = kwargs.get('logger') or logging.getLogger('cfq')
43
+
44
+ def consumer(self, queue_id: str, visibility_timeout_ms: int = 60_000):
45
+ def decorator(fn: Callable[[Message], Awaitable[Any]]):
46
+ assert inspect.iscoroutinefunction(fn), 'Consumer function must be a coroutine'
47
+
48
+ if queue_id in self._consumers:
49
+ raise ValueError(f'Duplicate consumer for queue_id={queue_id}')
50
+
51
+ self._consumers[queue_id] = {
52
+ 'fn': fn,
53
+ 'visibility_timeout_ms': visibility_timeout_ms,
54
+ }
55
+
56
+ return fn
57
+
58
+ return decorator
59
+
60
+ async def _poller(
61
+ self,
62
+ visibility_timeout_ms: int,
63
+ fn: Callable[[Message], Awaitable[Any]],
64
+ queue_id: str,
65
+ ) -> None:
66
+ handler_name = getattr(fn, '__name__', str(fn))
67
+ workers = set()
68
+
69
+ while not self._stop_event.is_set():
70
+ resp = await self._client.queues.messages.pull(
71
+ queue_id,
72
+ account_id=self.account_id,
73
+ batch_size=self.max_batch_size,
74
+ visibility_timeout_ms=visibility_timeout_ms,
75
+ )
76
+
77
+ if not resp.messages:
78
+ await asyncio.sleep(self.polling_interval_ms / 1000.0)
79
+ continue
80
+
81
+ self.log.info(
82
+ f'Pulled {len(resp.messages)} message{"s" if len(resp.messages) > 1 else ""} from queue: {queue_id}'
83
+ )
84
+
85
+ for message in resp.messages or []:
86
+ while len(workers) >= self.max_workers:
87
+ done, pending = await asyncio.wait(workers, return_when=asyncio.FIRST_COMPLETED)
88
+ workers = pending
89
+ t = asyncio.create_task(self._handler(message, fn, queue_id, handler_name))
90
+ workers.add(t)
91
+ t.add_done_callback(workers.discard)
92
+
93
+ async def _handler(
94
+ self,
95
+ message: Message,
96
+ fn: Callable[[Message], Awaitable[Any]],
97
+ queue_id: str,
98
+ handler_name: str,
99
+ ) -> None:
100
+ try:
101
+ start = time.perf_counter()
102
+ await fn(message)
103
+ runtime = (time.perf_counter() - start) * 1000
104
+
105
+ self.log.info(f"Task finished | consumer: '{handler_name}' runtime: {runtime:.2f} ms")
106
+
107
+ self.messages_processed += 1
108
+
109
+ await self._client.queues.messages.ack(
110
+ queue_id,
111
+ account_id=self.account_id,
112
+ acks=[{'lease_id': message.lease_id}],
113
+ )
114
+
115
+ except Exception as e:
116
+ if self.allow_retry:
117
+ self.log.info(f'Task failed, retrying | error: {e}')
118
+ await self._client.queues.messages.ack(
119
+ queue_id,
120
+ account_id=self.account_id,
121
+ retries=[
122
+ {
123
+ 'delay_seconds': self.retry_delay_seconds,
124
+ 'lease_id': message.lease_id,
125
+ }
126
+ ],
127
+ )
128
+ else:
129
+ self.log.info(f'Task failed, not retrying | error: {e}')
130
+
131
+ async def _heartbeat_loop(self):
132
+ while not self._stop_event.is_set():
133
+ try:
134
+ await asyncio.wait_for(self._stop_event.wait(), timeout=self.heartbeat_interval_seconds)
135
+ except asyncio.TimeoutError:
136
+ pass
137
+
138
+ self.log.info(
139
+ f'Heartbeat | Processed {self.messages_processed} message{"s" if self.messages_processed > 1 else ""} in last {self.heartbeat_interval_seconds} seconds'
140
+ )
141
+ self.messages_processed = 0
142
+
143
+ async def start(self):
144
+ self._client = AsyncCloudflare(api_token=self.api_token)
145
+ self._stop_event.clear()
146
+
147
+ for queue_id, consumer_info in self._consumers.items():
148
+ coro = self._poller(consumer_info['visibility_timeout_ms'], consumer_info['fn'], queue_id)
149
+ self._poll_workers.append(asyncio.create_task(coro))
150
+
151
+ if self.heartbeat_interval_seconds and self.heartbeat_interval_seconds > 0:
152
+ self._heartbeat_task = asyncio.create_task(self._heartbeat_loop(), name='heartbeat')
153
+
154
+ self.log.info(f'Starting consumer | max workers: {self.max_workers} consumers: {len(self._consumers)}')
155
+
156
+ await asyncio.gather(*self._poll_workers)
157
+
158
+ async def stop(self):
159
+ self._stop_event.set()
160
+
161
+ if self._heartbeat_task:
162
+ self._heartbeat_task.cancel()
163
+ with contextlib.suppress(asyncio.CancelledError):
164
+ await self._heartbeat_task
165
+ self._heartbeat_task = None
166
+
167
+ if self._poll_workers:
168
+ await asyncio.gather(*self._poll_workers, return_exceptions=True)
169
+ self._poll_workers.clear()
170
+
171
+ self._client = None
@@ -0,0 +1,130 @@
1
+ Metadata-Version: 2.4
2
+ Name: cfq
3
+ Version: 0.1.0
4
+ Summary: A high-level Cloudflare Queues consumer library for Python
5
+ Requires-Python: >=3.13
6
+ Description-Content-Type: text/markdown
7
+ License-File: LICENSE
8
+ Requires-Dist: cloudflare>=4.3.1
9
+ Dynamic: license-file
10
+
11
+ # CFQ
12
+
13
+ A high-level Python client for consuming messages from Cloudflare Queues with async workers.
14
+
15
+ ```python
16
+ from cfq import CFQ
17
+
18
+ client = CFQ(
19
+ api_token="your_cloudflare_api_token",
20
+ account_id="your_account_id",
21
+ )
22
+
23
+ @client.consumer(queue_id="your_queue_id")
24
+ async def process_messages(message):
25
+ # Messages will be automatically ACKed on success
26
+ # or sent back to the queue to be retried on exceptions.
27
+
28
+ await client.start()
29
+ ```
30
+
31
+ CFQ's API design is inspired by [TaskIQ](https://github.com/taskiq-python/taskiq) and [Celery](https://github.com/celery/celery), adapted for Cloudflare Queues.
32
+
33
+ ### Installation
34
+
35
+ ```bash
36
+ uv add cfq
37
+ ```
38
+
39
+ ### CFQ Parameters
40
+
41
+ | Parameter | Type | Default | Description |
42
+ |-----------|------|---------|----------------------------------------------|
43
+ | `api_token` | `str` | *required* | Cloudflare API token with Queues permissions |
44
+ | `account_id` | `str` | *required* | Your Cloudflare account identifier |
45
+ | `max_workers` | `int` | `10` | Maximum concurrent message handlers (async workers) |
46
+ | `polling_interval_ms` | `float` | `1000` | Polling interval in milliseconds when queue is empty |
47
+ | `max_batch_size` | `int` | `10` | Messages to pull per request |
48
+ | `allow_retry` | `bool` | `True` | Whether to retry failed messages |
49
+ | `retry_delay_seconds` | `int` | `0` | Delay before retrying failed messages |
50
+ | `heartbeat_interval_seconds` | `int` | `0` | Heartbeat logging interval (0 = disabled) |
51
+ | `logger` | `Logger` | `None` | Custom logger (defaults to "cfq" logger) |
52
+
53
+ ### Consumer Decorator Parameters
54
+
55
+ ```python
56
+ from cloudflare.types.queues.message_pull_response import Message
57
+
58
+ @client.consumer(queue_id="queue_id", visibility_timeout_ms=60000)
59
+ async def my_consumer(message: Message):
60
+ # Your message processing logic
61
+ pass
62
+ ```
63
+
64
+ | Parameter | Type | Default | Description |
65
+ |-----------|------|---------|-------------|
66
+ | `queue_id` | `str` | *required* | The Cloudflare Queue ID to consume from |
67
+ | `visibility_timeout_ms` | `int` | `60000` | Message visibility timeout in milliseconds |
68
+
69
+
70
+ ### Multiple Queue Consumers
71
+
72
+ ```python
73
+ client = CFQ(
74
+ api_token="your_token",
75
+ account_id="your_account_id",
76
+ max_workers=20, # Shared across all consumers
77
+ )
78
+
79
+ @client.consumer(queue_id="email_queue_id")
80
+ async def handle_emails(message: Message):
81
+ # Process email messages
82
+ await send_email(message.body)
83
+
84
+ @client.consumer(queue_id="webhook_queue_id", visibility_timeout_ms=30000)
85
+ async def handle_webhooks(message: Message):
86
+ # Process webhook messages with shorter timeout
87
+ await process_webhook(message.body)
88
+
89
+ await client.start()
90
+ ```
91
+
92
+ ### Custom Configuration Example
93
+
94
+ ```python
95
+ client = CFQ(
96
+ api_token="your_token",
97
+ account_id="your_account_id",
98
+ max_workers=5,
99
+ polling_interval_ms=500, # Poll every 500ms
100
+ max_batch_size=20, # Pull up to 20 messages at once
101
+ allow_retry=True,
102
+ retry_delay_seconds=30, # Wait 30s before retry
103
+ heartbeat_interval_seconds=60, # Log heartbeat every minute
104
+ )
105
+ ```
106
+
107
+ ### Error Handling
108
+
109
+ CFQ automatically handles message acknowledgment and retries:
110
+
111
+ - **Success**: Messages are automatically ACKed after successful processing
112
+ - **Failure with retry enabled**: Failed messages are retried with configurable delay
113
+ - **Failure with retry disabled**: Failed messages are discarded
114
+ - **Worker limits**: New messages wait for available workers when `max_workers` is reached
115
+
116
+ ### Monitoring
117
+
118
+ Enable heartbeat logging to monitor processing rates:
119
+
120
+ ```python
121
+ client = CFQ(
122
+ # ... other config
123
+ heartbeat_interval_seconds=30, # Log every 30 seconds
124
+ )
125
+ ```
126
+
127
+ This will output logs like:
128
+ ```
129
+ INFO:cfq:Heartbeat | Processed 42 messages in last 30 seconds
130
+ ```
@@ -0,0 +1,6 @@
1
+ cfq/__init__.py,sha256=SWMwH0VJCakdeGAMohAs4M8pqvtOftMAmIWI7m-_dk8,5979
2
+ cfq-0.1.0.dist-info/licenses/LICENSE,sha256=FrkuHTRWXnSvs4E2Vgyc8PvfjrZfYHXKnEZvarYxebM,1070
3
+ cfq-0.1.0.dist-info/METADATA,sha256=kP6BdR9FFUc39VhEUKV0BwzWWHXnD9lGEVWS8OWKGhI,4045
4
+ cfq-0.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
5
+ cfq-0.1.0.dist-info/top_level.txt,sha256=4tNBqRuxFOQam3pGamk7-7doAI4IvL4o2poueZilLyU,4
6
+ cfq-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Jacob Padilla
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ cfq