pushq 0.1.0b3__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.
pushq/__init__.py ADDED
@@ -0,0 +1,58 @@
1
+ """pushq — client for the self-hosted HTTP push task queue.
2
+
3
+ Quickstart::
4
+
5
+ from pushq import Pushq, RateLimits, Retry, Target
6
+
7
+ pq = Pushq("http://localhost:8080", api_key="pq_...")
8
+ pq.upsert_queue(
9
+ "account-42",
10
+ rate_limits=RateLimits(max_dispatches_per_second=10),
11
+ target=Target(base_url="https://api.example.com"),
12
+ )
13
+ pq.create_task(
14
+ "account-42",
15
+ path="/hooks/send-message",
16
+ json_body={"user_id": 1},
17
+ delay_seconds=3600,
18
+ task_id="follow_up_abc", # dedup
19
+ retry=Retry(max_attempts=3), # per-task override
20
+ )
21
+ """
22
+ from ._client import AsyncPushq, Pushq, PushqError
23
+ from ._models import (
24
+ Attempt,
25
+ BatchError,
26
+ BatchResult,
27
+ LastAttempt,
28
+ Page,
29
+ Queue,
30
+ QueueStats,
31
+ RateLimits,
32
+ Retry,
33
+ Target,
34
+ Task,
35
+ )
36
+ from .webhooks import WebhookVerificationError, sign, verify_signature
37
+
38
+ __version__ = "0.1.0-beta.3"
39
+
40
+ __all__ = [
41
+ "Pushq",
42
+ "AsyncPushq",
43
+ "PushqError",
44
+ "RateLimits",
45
+ "Retry",
46
+ "Target",
47
+ "Queue",
48
+ "QueueStats",
49
+ "Task",
50
+ "Attempt",
51
+ "BatchResult",
52
+ "BatchError",
53
+ "LastAttempt",
54
+ "Page",
55
+ "verify_signature",
56
+ "sign",
57
+ "WebhookVerificationError",
58
+ ]
pushq/_client.py ADDED
@@ -0,0 +1,396 @@
1
+ """Sync and async pushq clients on httpx."""
2
+ from __future__ import annotations
3
+
4
+ import base64
5
+ from datetime import datetime, timezone
6
+ from typing import Any, Dict, Iterable, List, Optional, Union
7
+
8
+ import httpx
9
+
10
+ from ._models import (
11
+ Attempt,
12
+ BatchResult,
13
+ Page,
14
+ Queue,
15
+ QueueStats,
16
+ RateLimits,
17
+ Retry,
18
+ Target,
19
+ Task,
20
+ _prune,
21
+ )
22
+
23
+
24
+ class PushqError(Exception):
25
+ """Raised for any non-2xx API response (RFC 9457 problem+json)."""
26
+
27
+ def __init__(self, status: int, code: str, detail: str):
28
+ super().__init__(f"pushq: {code} ({status}): {detail}")
29
+ self.status = status
30
+ self.code = code
31
+ self.detail = detail
32
+
33
+
34
+ def _raise_for(resp: httpx.Response) -> None:
35
+ if resp.is_success:
36
+ return
37
+ code, detail = "internal", resp.text[:200]
38
+ try:
39
+ body = resp.json()
40
+ code = body.get("code", code)
41
+ detail = body.get("detail") or body.get("title") or detail
42
+ except Exception:
43
+ pass
44
+ raise PushqError(resp.status_code, code, detail)
45
+
46
+
47
+ def _queue_config_wire(
48
+ rate_limits: Optional[RateLimits],
49
+ retry: Optional[Retry],
50
+ target: Optional[Target],
51
+ dead_letter_queue: Optional[str],
52
+ state: Optional[str] = None,
53
+ ) -> Dict[str, Any]:
54
+ return _prune(
55
+ state=state,
56
+ rate_limits=rate_limits.to_wire() if rate_limits else None,
57
+ retry=retry.to_wire() if retry else None,
58
+ target=target.to_wire() if target else None,
59
+ dead_letter_queue=dead_letter_queue,
60
+ )
61
+
62
+
63
+ def _task_create_wire(
64
+ *,
65
+ task_id: Optional[str],
66
+ url: Optional[str],
67
+ path: Optional[str],
68
+ method: Optional[str],
69
+ headers: Optional[Dict[str, str]],
70
+ body: Optional[bytes],
71
+ json_body: Any,
72
+ schedule_time: Optional[Union[datetime, str]],
73
+ delay_seconds: Optional[float],
74
+ dispatch_deadline_seconds: Optional[float],
75
+ retry: Optional[Retry],
76
+ ) -> Dict[str, Any]:
77
+ if body is not None and json_body is not None:
78
+ raise ValueError("pushq: provide body or json_body, not both")
79
+ schedule: Optional[str] = None
80
+ if isinstance(schedule_time, datetime):
81
+ dt = schedule_time
82
+ if dt.tzinfo is None:
83
+ dt = dt.replace(tzinfo=timezone.utc)
84
+ schedule = dt.isoformat()
85
+ elif isinstance(schedule_time, str):
86
+ schedule = schedule_time
87
+ return _prune(
88
+ task_id=task_id,
89
+ url=url,
90
+ path=path,
91
+ method=method,
92
+ headers=headers,
93
+ body_base64=base64.b64encode(body).decode() if body is not None else None,
94
+ json_body=json_body,
95
+ schedule_time=schedule,
96
+ delay_seconds=delay_seconds,
97
+ dispatch_deadline_seconds=dispatch_deadline_seconds,
98
+ retry=retry.to_wire() if retry else None,
99
+ )
100
+
101
+
102
+ class Pushq:
103
+ """Synchronous client.
104
+
105
+ >>> pq = Pushq("http://localhost:8080", api_key="pq_...")
106
+ >>> pq.upsert_queue("account-42", rate_limits=RateLimits(max_dispatches_per_second=10))
107
+ >>> pq.create_task("account-42", path="/hooks/send", json_body={"user": 1},
108
+ ... delay_seconds=3600, task_id="follow_up_abc",
109
+ ... retry=Retry(max_attempts=3))
110
+ """
111
+
112
+ def __init__(
113
+ self,
114
+ base_url: str,
115
+ api_key: Optional[str] = None,
116
+ *,
117
+ timeout: float = 30.0,
118
+ client: Optional[httpx.Client] = None,
119
+ ):
120
+ headers = {"Authorization": f"Bearer {api_key}"} if api_key else {}
121
+ self._http = client or httpx.Client(
122
+ base_url=base_url.rstrip("/"), headers=headers, timeout=timeout
123
+ )
124
+
125
+ def close(self) -> None:
126
+ self._http.close()
127
+
128
+ def __enter__(self) -> "Pushq":
129
+ return self
130
+
131
+ def __exit__(self, *exc: Any) -> None:
132
+ self.close()
133
+
134
+ def _req(self, method: str, path: str, json: Any = None, params: Any = None) -> Any:
135
+ resp = self._http.request(method, path, json=json, params=params)
136
+ _raise_for(resp)
137
+ if resp.status_code == 204 or not resp.content:
138
+ return None
139
+ return resp.json()
140
+
141
+ # --- queues ---
142
+
143
+ def upsert_queue(
144
+ self,
145
+ name: str,
146
+ *,
147
+ rate_limits: Optional[RateLimits] = None,
148
+ retry: Optional[Retry] = None,
149
+ target: Optional[Target] = None,
150
+ dead_letter_queue: Optional[str] = None,
151
+ ) -> Queue:
152
+ """Create or replace queue config. Never changes run state; a signing
153
+ secret is kept unless explicitly set (use "" to clear)."""
154
+ wire = _queue_config_wire(rate_limits, retry, target, dead_letter_queue)
155
+ return Queue.from_wire(self._req("PUT", f"/v1/queues/{name}", json=wire))
156
+
157
+ def create_queue(self, name: str, **kwargs: Any) -> Queue:
158
+ wire = _queue_config_wire(
159
+ kwargs.get("rate_limits"), kwargs.get("retry"), kwargs.get("target"),
160
+ kwargs.get("dead_letter_queue"),
161
+ )
162
+ wire["name"] = name
163
+ return Queue.from_wire(self._req("POST", "/v1/queues", json=wire))
164
+
165
+ def get_queue(self, name: str) -> Queue:
166
+ return Queue.from_wire(self._req("GET", f"/v1/queues/{name}"))
167
+
168
+ def patch_queue(
169
+ self,
170
+ name: str,
171
+ *,
172
+ state: Optional[str] = None,
173
+ rate_limits: Optional[RateLimits] = None,
174
+ retry: Optional[Retry] = None,
175
+ target: Optional[Target] = None,
176
+ dead_letter_queue: Optional[str] = None,
177
+ ) -> Queue:
178
+ wire = _queue_config_wire(rate_limits, retry, target, dead_letter_queue, state)
179
+ return Queue.from_wire(self._req("PATCH", f"/v1/queues/{name}", json=wire))
180
+
181
+ def list_queues(
182
+ self,
183
+ *,
184
+ name_prefix: Optional[str] = None,
185
+ page_size: Optional[int] = None,
186
+ page_token: Optional[str] = None,
187
+ ) -> Page:
188
+ w = self._req("GET", "/v1/queues", params=_prune(
189
+ name_prefix=name_prefix, page_size=page_size, page_token=page_token))
190
+ return Page(
191
+ items=[Queue.from_wire(q) for q in w.get("queues", [])],
192
+ next_page_token=w.get("next_page_token"),
193
+ )
194
+
195
+ def delete_queue(self, name: str) -> None:
196
+ self._req("DELETE", f"/v1/queues/{name}")
197
+
198
+ def pause_queue(self, name: str) -> Queue:
199
+ return Queue.from_wire(self._req("POST", f"/v1/queues/{name}:pause"))
200
+
201
+ def resume_queue(self, name: str) -> Queue:
202
+ return Queue.from_wire(self._req("POST", f"/v1/queues/{name}:resume"))
203
+
204
+ def purge_queue(self, name: str) -> Queue:
205
+ """Delete every task created up to now (exact watermark)."""
206
+ return Queue.from_wire(self._req("POST", f"/v1/queues/{name}:purge"))
207
+
208
+ def queue_stats(self, name: str, *, id_prefix: Optional[str] = None) -> QueueStats:
209
+ w = self._req("GET", f"/v1/queues/{name}/stats", params=_prune(id_prefix=id_prefix))
210
+ return QueueStats.from_wire(w)
211
+
212
+ # --- tasks ---
213
+
214
+ def create_task(
215
+ self,
216
+ queue: str,
217
+ *,
218
+ url: Optional[str] = None,
219
+ path: Optional[str] = None,
220
+ method: Optional[str] = None,
221
+ headers: Optional[Dict[str, str]] = None,
222
+ body: Optional[bytes] = None,
223
+ json_body: Any = None,
224
+ schedule_time: Optional[Union[datetime, str]] = None,
225
+ delay_seconds: Optional[float] = None,
226
+ dispatch_deadline_seconds: Optional[float] = None,
227
+ task_id: Optional[str] = None,
228
+ retry: Optional[Retry] = None,
229
+ ) -> Task:
230
+ wire = _task_create_wire(
231
+ task_id=task_id, url=url, path=path, method=method, headers=headers,
232
+ body=body, json_body=json_body, schedule_time=schedule_time,
233
+ delay_seconds=delay_seconds, dispatch_deadline_seconds=dispatch_deadline_seconds,
234
+ retry=retry,
235
+ )
236
+ return Task.from_wire(self._req("POST", f"/v1/queues/{queue}/tasks", json=wire))
237
+
238
+ def create_tasks(self, queue: str, tasks: Iterable[Dict[str, Any]]) -> List[BatchResult]:
239
+ """Batch enqueue (≤500). Each item is the kwargs of create_task."""
240
+ wire = [_task_create_wire(
241
+ task_id=t.get("task_id"), url=t.get("url"), path=t.get("path"),
242
+ method=t.get("method"), headers=t.get("headers"), body=t.get("body"),
243
+ json_body=t.get("json_body"), schedule_time=t.get("schedule_time"),
244
+ delay_seconds=t.get("delay_seconds"),
245
+ dispatch_deadline_seconds=t.get("dispatch_deadline_seconds"),
246
+ retry=t.get("retry"),
247
+ ) for t in tasks]
248
+ w = self._req("POST", f"/v1/queues/{queue}/tasks:batch", json={"tasks": wire})
249
+ return [BatchResult.from_wire(r) for r in w.get("results", [])]
250
+
251
+ def get_task(self, queue: str, task_id: str, *, view: str = "basic") -> Task:
252
+ w = self._req("GET", f"/v1/queues/{queue}/tasks/{task_id}", params={"view": view})
253
+ return Task.from_wire(w)
254
+
255
+ def list_tasks(
256
+ self,
257
+ queue: str,
258
+ *,
259
+ state: Optional[str] = None,
260
+ id_prefix: Optional[str] = None,
261
+ view: Optional[str] = None,
262
+ page_size: Optional[int] = None,
263
+ page_token: Optional[str] = None,
264
+ ) -> Page:
265
+ w = self._req("GET", f"/v1/queues/{queue}/tasks", params=_prune(
266
+ state=state, id_prefix=id_prefix, view=view,
267
+ page_size=page_size, page_token=page_token))
268
+ return Page(
269
+ items=[Task.from_wire(t) for t in w.get("tasks", [])],
270
+ next_page_token=w.get("next_page_token"),
271
+ )
272
+
273
+ def delete_task(self, queue: str, task_id: str) -> None:
274
+ self._req("DELETE", f"/v1/queues/{queue}/tasks/{task_id}")
275
+
276
+ def run_task(self, queue: str, task_id: str) -> Task:
277
+ """Force immediate dispatch (bypasses rate limits and PAUSED)."""
278
+ return Task.from_wire(self._req("POST", f"/v1/queues/{queue}/tasks/{task_id}:run"))
279
+
280
+ def list_attempts(self, queue: str, task_id: str) -> List[Attempt]:
281
+ w = self._req("GET", f"/v1/queues/{queue}/tasks/{task_id}/attempts")
282
+ return [Attempt.from_wire(a) for a in w.get("attempts", [])]
283
+
284
+
285
+ class AsyncPushq:
286
+ """Async twin of Pushq with the same method surface."""
287
+
288
+ def __init__(
289
+ self,
290
+ base_url: str,
291
+ api_key: Optional[str] = None,
292
+ *,
293
+ timeout: float = 30.0,
294
+ client: Optional[httpx.AsyncClient] = None,
295
+ ):
296
+ headers = {"Authorization": f"Bearer {api_key}"} if api_key else {}
297
+ self._http = client or httpx.AsyncClient(
298
+ base_url=base_url.rstrip("/"), headers=headers, timeout=timeout
299
+ )
300
+
301
+ async def aclose(self) -> None:
302
+ await self._http.aclose()
303
+
304
+ async def __aenter__(self) -> "AsyncPushq":
305
+ return self
306
+
307
+ async def __aexit__(self, *exc: Any) -> None:
308
+ await self.aclose()
309
+
310
+ async def _req(self, method: str, path: str, json: Any = None, params: Any = None) -> Any:
311
+ resp = await self._http.request(method, path, json=json, params=params)
312
+ _raise_for(resp)
313
+ if resp.status_code == 204 or not resp.content:
314
+ return None
315
+ return resp.json()
316
+
317
+ async def upsert_queue(
318
+ self,
319
+ name: str,
320
+ *,
321
+ rate_limits: Optional[RateLimits] = None,
322
+ retry: Optional[Retry] = None,
323
+ target: Optional[Target] = None,
324
+ dead_letter_queue: Optional[str] = None,
325
+ ) -> Queue:
326
+ wire = _queue_config_wire(rate_limits, retry, target, dead_letter_queue)
327
+ return Queue.from_wire(await self._req("PUT", f"/v1/queues/{name}", json=wire))
328
+
329
+ async def get_queue(self, name: str) -> Queue:
330
+ return Queue.from_wire(await self._req("GET", f"/v1/queues/{name}"))
331
+
332
+ async def pause_queue(self, name: str) -> Queue:
333
+ return Queue.from_wire(await self._req("POST", f"/v1/queues/{name}:pause"))
334
+
335
+ async def resume_queue(self, name: str) -> Queue:
336
+ return Queue.from_wire(await self._req("POST", f"/v1/queues/{name}:resume"))
337
+
338
+ async def purge_queue(self, name: str) -> Queue:
339
+ return Queue.from_wire(await self._req("POST", f"/v1/queues/{name}:purge"))
340
+
341
+ async def delete_queue(self, name: str) -> None:
342
+ await self._req("DELETE", f"/v1/queues/{name}")
343
+
344
+ async def queue_stats(self, name: str, *, id_prefix: Optional[str] = None) -> QueueStats:
345
+ w = await self._req("GET", f"/v1/queues/{name}/stats", params=_prune(id_prefix=id_prefix))
346
+ return QueueStats.from_wire(w)
347
+
348
+ async def create_task(self, queue: str, **kwargs: Any) -> Task:
349
+ wire = _task_create_wire(
350
+ task_id=kwargs.get("task_id"), url=kwargs.get("url"), path=kwargs.get("path"),
351
+ method=kwargs.get("method"), headers=kwargs.get("headers"), body=kwargs.get("body"),
352
+ json_body=kwargs.get("json_body"), schedule_time=kwargs.get("schedule_time"),
353
+ delay_seconds=kwargs.get("delay_seconds"),
354
+ dispatch_deadline_seconds=kwargs.get("dispatch_deadline_seconds"),
355
+ retry=kwargs.get("retry"),
356
+ )
357
+ return Task.from_wire(await self._req("POST", f"/v1/queues/{queue}/tasks", json=wire))
358
+
359
+ async def create_tasks(self, queue: str, tasks: Iterable[Dict[str, Any]]) -> List[BatchResult]:
360
+ wire = [_task_create_wire(
361
+ task_id=t.get("task_id"), url=t.get("url"), path=t.get("path"),
362
+ method=t.get("method"), headers=t.get("headers"), body=t.get("body"),
363
+ json_body=t.get("json_body"), schedule_time=t.get("schedule_time"),
364
+ delay_seconds=t.get("delay_seconds"),
365
+ dispatch_deadline_seconds=t.get("dispatch_deadline_seconds"),
366
+ retry=t.get("retry"),
367
+ ) for t in tasks]
368
+ w = await self._req("POST", f"/v1/queues/{queue}/tasks:batch", json={"tasks": wire})
369
+ return [BatchResult.from_wire(r) for r in w.get("results", [])]
370
+
371
+ async def get_task(self, queue: str, task_id: str, *, view: str = "basic") -> Task:
372
+ w = await self._req("GET", f"/v1/queues/{queue}/tasks/{task_id}", params={"view": view})
373
+ return Task.from_wire(w)
374
+
375
+ async def list_tasks(self, queue: str, **kwargs: Any) -> Page:
376
+ w = await self._req("GET", f"/v1/queues/{queue}/tasks", params=_prune(
377
+ state=kwargs.get("state"), id_prefix=kwargs.get("id_prefix"),
378
+ view=kwargs.get("view"), page_size=kwargs.get("page_size"),
379
+ page_token=kwargs.get("page_token")))
380
+ return Page(
381
+ items=[Task.from_wire(t) for t in w.get("tasks", [])],
382
+ next_page_token=w.get("next_page_token"),
383
+ )
384
+
385
+ async def delete_task(self, queue: str, task_id: str) -> None:
386
+ await self._req("DELETE", f"/v1/queues/{queue}/tasks/{task_id}")
387
+
388
+ async def run_task(self, queue: str, task_id: str) -> Task:
389
+ return Task.from_wire(await self._req("POST", f"/v1/queues/{queue}/tasks/{task_id}:run"))
390
+
391
+ async def list_attempts(self, queue: str, task_id: str) -> List[Attempt]:
392
+ w = await self._req("GET", f"/v1/queues/{queue}/tasks/{task_id}/attempts")
393
+ return [Attempt.from_wire(a) for a in w.get("attempts", [])]
394
+
395
+
396
+ __all__ = ["Pushq", "AsyncPushq", "PushqError"]
pushq/_models.py ADDED
@@ -0,0 +1,268 @@
1
+ """Dataclass models mirroring the pushq API (snake_case wire format)."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ from dataclasses import dataclass, field
6
+ from datetime import datetime
7
+ from typing import Any, Dict, List, Optional
8
+
9
+ _ISO_RE = re.compile(r"^(.*?)(?:\.(\d+))?([+-]\d{2}:\d{2})$")
10
+
11
+
12
+ def _dt(value: Optional[str]) -> Optional[datetime]:
13
+ if not value:
14
+ return None
15
+ v = value.replace("Z", "+00:00")
16
+ # Python < 3.11 only accepts 3- or 6-digit fractions; RFC 3339 allows any.
17
+ m = _ISO_RE.match(v)
18
+ if m:
19
+ frac = ((m.group(2) or "") + "000000")[:6]
20
+ v = f"{m.group(1)}.{frac}{m.group(3)}"
21
+ return datetime.fromisoformat(v)
22
+
23
+
24
+ @dataclass
25
+ class RateLimits:
26
+ max_dispatches_per_second: Optional[float] = None
27
+ max_burst_size: Optional[int] = None
28
+ max_concurrent_dispatches: Optional[int] = None
29
+
30
+ def to_wire(self) -> Dict[str, Any]:
31
+ return _prune(
32
+ max_dispatches_per_second=self.max_dispatches_per_second,
33
+ max_burst_size=self.max_burst_size,
34
+ max_concurrent_dispatches=self.max_concurrent_dispatches,
35
+ )
36
+
37
+
38
+ @dataclass
39
+ class Retry:
40
+ """GCP Cloud Tasks retry semantics. On a task, any subset overrides the queue config."""
41
+
42
+ max_attempts: Optional[int] = None
43
+ max_retry_duration_seconds: Optional[float] = None
44
+ min_backoff_seconds: Optional[float] = None
45
+ max_backoff_seconds: Optional[float] = None
46
+ max_doublings: Optional[int] = None
47
+
48
+ def to_wire(self) -> Dict[str, Any]:
49
+ return _prune(
50
+ max_attempts=self.max_attempts,
51
+ max_retry_duration_seconds=self.max_retry_duration_seconds,
52
+ min_backoff_seconds=self.min_backoff_seconds,
53
+ max_backoff_seconds=self.max_backoff_seconds,
54
+ max_doublings=self.max_doublings,
55
+ )
56
+
57
+ @classmethod
58
+ def from_wire(cls, w: Optional[Dict[str, Any]]) -> Optional["Retry"]:
59
+ if not w:
60
+ return None
61
+ return cls(
62
+ max_attempts=w.get("max_attempts"),
63
+ max_retry_duration_seconds=w.get("max_retry_duration_seconds"),
64
+ min_backoff_seconds=w.get("min_backoff_seconds"),
65
+ max_backoff_seconds=w.get("max_backoff_seconds"),
66
+ max_doublings=w.get("max_doublings"),
67
+ )
68
+
69
+
70
+ @dataclass
71
+ class Target:
72
+ base_url: Optional[str] = None
73
+ method: Optional[str] = None
74
+ headers: Optional[Dict[str, str]] = None
75
+ signing_secret: Optional[str] = None
76
+ """On upsert: None keeps the stored secret, "" clears it."""
77
+
78
+ def to_wire(self) -> Dict[str, Any]:
79
+ return _prune(
80
+ base_url=self.base_url,
81
+ method=self.method,
82
+ headers=self.headers,
83
+ signing_secret=self.signing_secret,
84
+ )
85
+
86
+
87
+ @dataclass
88
+ class Queue:
89
+ name: str
90
+ state: str
91
+ rate_limits: RateLimits
92
+ retry: Retry
93
+ target_base_url: Optional[str]
94
+ target_method: Optional[str]
95
+ target_headers: Optional[Dict[str, str]]
96
+ has_signing_secret: bool
97
+ dead_letter_queue: Optional[str]
98
+ purged_at: Optional[datetime]
99
+ created_at: Optional[datetime]
100
+ updated_at: Optional[datetime]
101
+
102
+ @classmethod
103
+ def from_wire(cls, w: Dict[str, Any]) -> "Queue":
104
+ rl = w.get("rate_limits") or {}
105
+ tg = w.get("target") or {}
106
+ return cls(
107
+ name=w["name"],
108
+ state=w["state"],
109
+ rate_limits=RateLimits(
110
+ max_dispatches_per_second=rl.get("max_dispatches_per_second"),
111
+ max_burst_size=rl.get("max_burst_size"),
112
+ max_concurrent_dispatches=rl.get("max_concurrent_dispatches"),
113
+ ),
114
+ retry=Retry.from_wire(w.get("retry")) or Retry(),
115
+ target_base_url=tg.get("base_url"),
116
+ target_method=tg.get("method"),
117
+ target_headers=tg.get("headers"),
118
+ has_signing_secret=bool(tg.get("has_signing_secret")),
119
+ dead_letter_queue=w.get("dead_letter_queue"),
120
+ purged_at=_dt(w.get("purged_at")),
121
+ created_at=_dt(w.get("created_at")),
122
+ updated_at=_dt(w.get("updated_at")),
123
+ )
124
+
125
+
126
+ @dataclass
127
+ class QueueStats:
128
+ state: str
129
+ pending: int
130
+ running: int
131
+ succeeded: int
132
+ failed: int
133
+ scheduled_future: int
134
+ oldest_due_at: Optional[datetime]
135
+ oldest_due_age_seconds: Optional[float]
136
+ dispatched_last_1m: int
137
+ errors_last_1m: int
138
+ dispatched_last_1h: int
139
+ errors_last_1h: int
140
+ last_purge: Optional[datetime]
141
+
142
+ @classmethod
143
+ def from_wire(cls, w: Dict[str, Any]) -> "QueueStats":
144
+ return cls(
145
+ state=w.get("state", ""),
146
+ pending=w.get("pending", 0),
147
+ running=w.get("running", 0),
148
+ succeeded=w.get("succeeded", 0),
149
+ failed=w.get("failed", 0),
150
+ scheduled_future=w.get("scheduled_future", 0),
151
+ oldest_due_at=_dt(w.get("oldest_due_at")),
152
+ oldest_due_age_seconds=w.get("oldest_due_age_seconds"),
153
+ dispatched_last_1m=w.get("dispatched_last_1m", 0),
154
+ errors_last_1m=w.get("errors_last_1m", 0),
155
+ dispatched_last_1h=w.get("dispatched_last_1h", 0),
156
+ errors_last_1h=w.get("errors_last_1h", 0),
157
+ last_purge=_dt(w.get("last_purge")),
158
+ )
159
+
160
+
161
+ @dataclass
162
+ class LastAttempt:
163
+ at: Optional[datetime]
164
+ status: Optional[int]
165
+ error: Optional[str]
166
+
167
+
168
+ @dataclass
169
+ class Task:
170
+ id: str
171
+ queue: str
172
+ state: str
173
+ url: str
174
+ method: str
175
+ headers: Optional[Dict[str, str]]
176
+ body: Optional[bytes]
177
+ schedule_time: Optional[datetime]
178
+ created_at: Optional[datetime]
179
+ dispatch_deadline_seconds: float
180
+ retry: Optional[Retry]
181
+ dispatch_count: int
182
+ response_count: int
183
+ first_attempt_at: Optional[datetime]
184
+ finished_at: Optional[datetime]
185
+ last_attempt: Optional[LastAttempt]
186
+
187
+ @classmethod
188
+ def from_wire(cls, w: Dict[str, Any]) -> "Task":
189
+ import base64
190
+
191
+ la = w.get("last_attempt")
192
+ return cls(
193
+ id=w["id"],
194
+ queue=w["queue"],
195
+ state=w["state"],
196
+ url=w.get("url", ""),
197
+ method=w.get("method", ""),
198
+ headers=w.get("headers"),
199
+ body=base64.b64decode(w["body_base64"]) if w.get("body_base64") else None,
200
+ schedule_time=_dt(w.get("schedule_time")),
201
+ created_at=_dt(w.get("created_at")),
202
+ dispatch_deadline_seconds=w.get("dispatch_deadline_seconds", 0),
203
+ retry=Retry.from_wire(w.get("retry")),
204
+ dispatch_count=w.get("dispatch_count", 0),
205
+ response_count=w.get("response_count", 0),
206
+ first_attempt_at=_dt(w.get("first_attempt_at")),
207
+ finished_at=_dt(w.get("finished_at")),
208
+ last_attempt=LastAttempt(
209
+ at=_dt(la.get("at")), status=la.get("status"), error=la.get("error")
210
+ )
211
+ if la
212
+ else None,
213
+ )
214
+
215
+
216
+ @dataclass
217
+ class Attempt:
218
+ number: int
219
+ dispatch_time: Optional[datetime]
220
+ response_time: Optional[datetime]
221
+ response_status: Optional[int]
222
+ error_kind: Optional[str]
223
+ error_snippet: Optional[str]
224
+ duration_ms: int
225
+
226
+ @classmethod
227
+ def from_wire(cls, w: Dict[str, Any]) -> "Attempt":
228
+ return cls(
229
+ number=w.get("number", 0),
230
+ dispatch_time=_dt(w.get("dispatch_time")),
231
+ response_time=_dt(w.get("response_time")),
232
+ response_status=w.get("response_status"),
233
+ error_kind=w.get("error_kind"),
234
+ error_snippet=w.get("error_snippet"),
235
+ duration_ms=w.get("duration_ms", 0),
236
+ )
237
+
238
+
239
+ @dataclass
240
+ class BatchError:
241
+ code: str
242
+ detail: str
243
+
244
+
245
+ @dataclass
246
+ class BatchResult:
247
+ index: int
248
+ task: Optional[Task]
249
+ error: Optional[BatchError]
250
+
251
+ @classmethod
252
+ def from_wire(cls, w: Dict[str, Any]) -> "BatchResult":
253
+ err = w.get("error")
254
+ return cls(
255
+ index=w.get("index", 0),
256
+ task=Task.from_wire(w["task"]) if w.get("task") else None,
257
+ error=BatchError(code=err["code"], detail=err.get("detail", "")) if err else None,
258
+ )
259
+
260
+
261
+ @dataclass
262
+ class Page:
263
+ items: List[Any] = field(default_factory=list)
264
+ next_page_token: Optional[str] = None
265
+
266
+
267
+ def _prune(**kwargs: Any) -> Dict[str, Any]:
268
+ return {k: v for k, v in kwargs.items() if v is not None}
pushq/py.typed ADDED
File without changes
pushq/webhooks.py ADDED
@@ -0,0 +1,84 @@
1
+ """Receiver-side verification of pushq deliveries (Standard Webhooks scheme).
2
+
3
+ pushq signs deliveries with HMAC-SHA256 over ``"{id}.{timestamp}.{payload}"``
4
+ and sends ``webhook-id``, ``webhook-timestamp``, and ``webhook-signature``
5
+ headers, compatible with https://www.standardwebhooks.com.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import base64
10
+ import hashlib
11
+ import hmac
12
+ import time
13
+ from typing import Mapping, Optional, Union
14
+
15
+
16
+ class WebhookVerificationError(Exception):
17
+ pass
18
+
19
+
20
+ def _signing_key(secret: str) -> bytes:
21
+ if secret.startswith("whsec_"):
22
+ return base64.b64decode(secret[len("whsec_"):])
23
+ return secret.encode()
24
+
25
+
26
+ def sign(secret: str, msg_id: str, timestamp: int, payload: Union[bytes, str]) -> str:
27
+ """Compute a ``v1,<base64>`` signature (tooling/tests)."""
28
+ body = payload.encode() if isinstance(payload, str) else payload
29
+ message = f"{msg_id}.{timestamp}.".encode() + body
30
+ mac = hmac.new(_signing_key(secret), message, hashlib.sha256).digest()
31
+ return "v1," + base64.b64encode(mac).decode()
32
+
33
+
34
+ def verify_signature(
35
+ secret: str,
36
+ headers: Mapping[str, str],
37
+ payload: Union[bytes, str],
38
+ *,
39
+ tolerance_seconds: float = 300,
40
+ now: Optional[float] = None,
41
+ ) -> str:
42
+ """Verify a pushq delivery.
43
+
44
+ ``headers`` is any case-insensitive-ish mapping of the incoming request
45
+ headers (FastAPI/Starlette ``request.headers`` works directly); ``payload``
46
+ is the raw request body exactly as received.
47
+
48
+ Returns the webhook id ("queue/task_id" — stable across retries, usable as
49
+ an idempotency key) or raises :class:`WebhookVerificationError`.
50
+
51
+ FastAPI example::
52
+
53
+ @app.post("/hooks/task")
54
+ async def handle(request: Request):
55
+ body = await request.body()
56
+ verify_signature(SECRET, request.headers, body)
57
+ ...
58
+ """
59
+ lower = {k.lower(): v for k, v in headers.items()}
60
+ msg_id = lower.get("webhook-id")
61
+ ts_raw = lower.get("webhook-timestamp")
62
+ sig_header = lower.get("webhook-signature")
63
+ if not msg_id or not ts_raw or not sig_header:
64
+ raise WebhookVerificationError("missing webhook-id/-timestamp/-signature headers")
65
+
66
+ try:
67
+ ts = int(ts_raw)
68
+ except ValueError as exc:
69
+ raise WebhookVerificationError("invalid timestamp") from exc
70
+
71
+ if tolerance_seconds > 0:
72
+ current = time.time() if now is None else now
73
+ if abs(current - ts) > tolerance_seconds:
74
+ raise WebhookVerificationError("timestamp outside tolerance")
75
+
76
+ expected = sign(secret, msg_id, ts, payload)
77
+ _, _, expected_sig = expected.partition(",")
78
+ for part in sig_header.split():
79
+ version, _, sig = part.partition(",")
80
+ if version != "v1" or not sig:
81
+ continue
82
+ if hmac.compare_digest(sig, expected_sig):
83
+ return msg_id
84
+ raise WebhookVerificationError("no matching signature")
@@ -0,0 +1,99 @@
1
+ Metadata-Version: 2.4
2
+ Name: pushq
3
+ Version: 0.1.0b3
4
+ Summary: Client for pushq — self-hosted HTTP push task queue (open-source Cloud Tasks alternative)
5
+ Project-URL: Homepage, https://github.com/blissfulrays/pushq
6
+ Project-URL: Documentation, https://github.com/blissfulrays/pushq/tree/main/sdks/python#readme
7
+ Project-URL: Repository, https://github.com/blissfulrays/pushq
8
+ Project-URL: Issues, https://github.com/blissfulrays/pushq/issues
9
+ Project-URL: Changelog, https://github.com/blissfulrays/pushq/releases
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: background-jobs,cloud-tasks,queue,task-queue,webhooks
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: System :: Distributed Computing
23
+ Classifier: Typing :: Typed
24
+ Requires-Python: >=3.9
25
+ Requires-Dist: httpx>=0.25
26
+ Provides-Extra: dev
27
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
28
+ Requires-Dist: pytest>=7; extra == 'dev'
29
+ Description-Content-Type: text/markdown
30
+
31
+ # pushq (Python)
32
+
33
+ Client for [pushq](https://github.com/blissfulrays/pushq) — a self-hosted HTTP push
34
+ task queue (open-source alternative to GCP Cloud Tasks). Tasks are delivered
35
+ as HTTP requests to your endpoints with per-queue rate limits, concurrency
36
+ caps, and Cloud Tasks-compatible retry semantics.
37
+
38
+ ```bash
39
+ pip install pushq
40
+ ```
41
+
42
+ ## Enqueue
43
+
44
+ ```python
45
+ from pushq import Pushq, RateLimits, Retry, Target
46
+
47
+ pq = Pushq("http://localhost:8080", api_key="pq_...")
48
+
49
+ # Queues are created/updated at runtime — idempotent, safe to call on every enqueue.
50
+ pq.upsert_queue(
51
+ "account-42",
52
+ rate_limits=RateLimits(max_dispatches_per_second=10, max_concurrent_dispatches=5),
53
+ target=Target(base_url="https://api.example.com",
54
+ signing_secret="whsec_..."), # omit to keep the stored secret
55
+ )
56
+
57
+ pq.create_task(
58
+ "account-42",
59
+ path="/hooks/send-message", # resolved against the queue's base_url
60
+ json_body={"user_id": 1},
61
+ delay_seconds=3600, # or schedule_time=datetime(...)
62
+ task_id="follow_up_abc", # optional: dedup (409 on collision)
63
+ retry=Retry(max_attempts=3), # per-task override of the queue config
64
+ )
65
+
66
+ # Operate queues at runtime
67
+ pq.pause_queue("account-42")
68
+ pq.resume_queue("account-42")
69
+ pq.purge_queue("account-42")
70
+ stats = pq.queue_stats("account-42", id_prefix="follow_up_")
71
+ print(stats.pending, stats.errors_last_1h)
72
+ ```
73
+
74
+ `AsyncPushq` mirrors the same surface with `async`/`await`.
75
+
76
+ ## Verify deliveries (FastAPI)
77
+
78
+ pushq signs deliveries using the [Standard Webhooks](https://www.standardwebhooks.com)
79
+ scheme (`webhook-id`, `webhook-timestamp`, `webhook-signature` headers).
80
+
81
+ ```python
82
+ from fastapi import FastAPI, HTTPException, Request
83
+ from pushq import verify_signature, WebhookVerificationError
84
+
85
+ app = FastAPI()
86
+
87
+ @app.post("/hooks/send-message")
88
+ async def send_message(request: Request):
89
+ body = await request.body()
90
+ try:
91
+ # Returns "queue/task_id" — stable across retries, use it as an idempotency key.
92
+ msg_id = verify_signature("whsec_...", request.headers, body)
93
+ except WebhookVerificationError:
94
+ raise HTTPException(status_code=401)
95
+ ...
96
+ ```
97
+
98
+ Errors raise `PushqError` with `.status`, `.code`
99
+ (`already_exists`, `not_found`, `failed_precondition`, …), and `.detail`.
@@ -0,0 +1,9 @@
1
+ pushq/__init__.py,sha256=RJYhHRD7eODkUZzTBcKk3rV3dKEkd9ELDyWlyjKiUck,1252
2
+ pushq/_client.py,sha256=9UatGLEIYxymC_hzgfXuCXs4FV7zjqlY7MW1HozQ1GM,14999
3
+ pushq/_models.py,sha256=EIAJFCv4EHb6-N_K7SUirIOVKr-4EeiULfFNfkNxXug,8315
4
+ pushq/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ pushq/webhooks.py,sha256=4p90zUb00bpS_fSP6WTQF9XKcPSzRiidieGR4GvA31o,2896
6
+ pushq-0.1.0b3.dist-info/METADATA,sha256=1HcLELORekAVTUZOKPrY17RPYXfFOwBYfcMSF9JKlGo,3657
7
+ pushq-0.1.0b3.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
8
+ pushq-0.1.0b3.dist-info/licenses/LICENSE,sha256=iCPuRIIUFaKlOXVjswCMXEvy8r8YJVQJKz3xMJgX8w0,1075
9
+ pushq-0.1.0b3.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 pushq contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.