workly 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.
workly-0.1.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
workly-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,216 @@
1
+ Metadata-Version: 2.4
2
+ Name: workly
3
+ Version: 0.1.0
4
+ Summary: Python SDK for Workly, the open-source HTTP task queue
5
+ Keywords: task queue,background jobs,webhooks,http
6
+ License-Expression: Apache-2.0
7
+ License-File: LICENSE
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Framework :: AsyncIO
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Typing :: Typed
13
+ Requires-Dist: httpx>=0.27,<1
14
+ Requires-Dist: workly-cli ; extra == 'cli'
15
+ Requires-Python: >=3.11
16
+ Project-URL: Homepage, https://workly.run
17
+ Project-URL: Repository, https://github.com/worklydev/workly
18
+ Provides-Extra: cli
19
+ Description-Content-Type: text/markdown
20
+
21
+ # Workly for Python
22
+
23
+ The Python SDK for [Workly](https://github.com/worklydev/workly), the open-source HTTP task queue. Enqueue a task, and Workly delivers it to your endpoint over HTTP, retrying with backoff until it succeeds.
24
+
25
+ ```sh
26
+ pip install workly # the SDK
27
+ pip install "workly[cli]" # the SDK plus the workly binary, for `workly dev`
28
+ ```
29
+
30
+ Requires Python 3.11+. The only dependency is [httpx](https://www.python-httpx.org). The `cli` extra adds [`workly-cli`](https://pypi.org/project/workly-cli/), the server binary (about 7 MB), which you usually want on dev machines and not in production images.
31
+
32
+ ## Quickstart
33
+
34
+ Start a local server with `workly dev` (SQLite, no auth, on :7337), then:
35
+
36
+ ```python
37
+ from workly import Workly
38
+
39
+ client = Workly() # WORKLY_URL, else http://localhost:7337; WORKLY_API_KEY
40
+ task = client.tasks.enqueue(
41
+ "emails",
42
+ url="https://api.example.com/send-email",
43
+ payload={"user_id": 123},
44
+ )
45
+ print(task.id, task.state)
46
+ ```
47
+
48
+ Your endpoint receives a `POST` with the JSON payload. Any 2xx marks the task succeeded. A 5xx, 408, 429, timeout or connection error is retried with backoff. Delivery is at-least-once, so make handlers safe to run twice. `Workly-Task-Id` is stable across attempts and works as a deduplication key.
49
+
50
+ ## Verifying deliveries
51
+
52
+ Every delivery is signed: with the server's `WORKLY_SIGNING_SECRET` when you run Workly yourself, or with your workspace's secret on [workly.run](#hosted-workly). Check the signature against the **raw** body:
53
+
54
+ ```python
55
+ from workly import SignatureVerificationError, verify_signature
56
+
57
+
58
+ # Flask
59
+ @app.post("/send-email")
60
+ def send_email():
61
+ try:
62
+ verify_signature(request.get_data(), request.headers) # secret from WORKLY_SIGNING_SECRET
63
+ except SignatureVerificationError:
64
+ abort(401)
65
+ ...
66
+
67
+
68
+ # FastAPI / Starlette
69
+ @app.post("/send-email")
70
+ async def send_email(request: Request):
71
+ verify_signature(await request.body(), request.headers, secret)
72
+ ...
73
+ ```
74
+
75
+ By default, signatures older than 5 minutes are rejected (`tolerance=`). `workly dev` signs with `workly-dev-secret`. To test your handler without a server, use `workly.sign(body, secret)`, which returns the headers Workly would send.
76
+
77
+ ## Hosted Workly
78
+
79
+ On [workly.run](https://workly.run), point the client at the hosted API and use the keys from the [console](https://console.workly.run):
80
+
81
+ ```sh
82
+ export WORKLY_URL=https://api.workly.run
83
+ export WORKLY_API_KEY=... # API keys page
84
+ export WORKLY_SIGNING_SECRET=whsec_... # same page; each workspace has its own
85
+ ```
86
+
87
+ Nothing else changes. Hosted workspaces have a request rate limit and a monthly task quota: requests over the rate limit are retried for you, and an enqueue over the quota raises `PermissionDeniedError` with the code `quota_exceeded`.
88
+
89
+ ## Tasks
90
+
91
+ ```python
92
+ from datetime import datetime, timedelta, timezone
93
+
94
+ client.tasks.enqueue(
95
+ "emails",
96
+ url="https://api.example.com/send-email",
97
+ payload={"user_id": 123}, # JSON; or body="raw text", content_type="text/csv"
98
+ method="POST", # default
99
+ headers={"X-Tenant": "acme"}, # sent with every delivery
100
+ delay_seconds=60, # or run_at=datetime(..., tzinfo=timezone.utc)
101
+ idempotency_key="welcome-123", # an existing task with this key is returned instead
102
+ max_attempts=5, # overrides the queue's setting
103
+ timeout_seconds=10, # likewise
104
+ )
105
+
106
+ # Up to 100 at once, all or nothing.
107
+ client.tasks.enqueue_many(
108
+ "emails",
109
+ [{"url": "https://api.example.com/send-email", "payload": {"user_id": i}} for i in range(100)],
110
+ )
111
+
112
+ task = client.tasks.get("task_01J9...")
113
+ for attempt in client.tasks.attempts(task.id):
114
+ print(attempt.number, attempt.outcome, attempt.status_code, attempt.duration_ms)
115
+
116
+ client.tasks.retry(task.id) # run now; replays a finished task
117
+ delivery = client.tasks.delivery(task.id) # the signed request, to replay by hand
118
+ client.tasks.cancel(task.id)
119
+
120
+ # Newest first, across pages. All filters are optional.
121
+ for task in client.tasks.list(
122
+ queue="emails", state="failed", created_after=datetime.now(timezone.utc) - timedelta(days=1)
123
+ ):
124
+ ...
125
+ ```
126
+
127
+ ## Queues
128
+
129
+ Queues are created automatically on first enqueue. `put` sets a queue's configuration declaratively, which makes it easy to keep in code: settings you leave out are reset to their defaults.
130
+
131
+ ```python
132
+ client.queues.put(
133
+ "emails",
134
+ max_attempts=10,
135
+ min_backoff_seconds=1,
136
+ max_backoff_seconds=3600,
137
+ backoff_multiplier=2,
138
+ timeout_seconds=30,
139
+ rate_per_second=50,
140
+ max_concurrency=20,
141
+ )
142
+
143
+ queue = client.queues.get("emails")
144
+ print(queue.stats.due, queue.stats.oldest_due_at)
145
+
146
+ client.queues.pause("emails") # stop delivering; enqueueing still works
147
+ client.queues.resume("emails")
148
+ client.queues.cancel_pending("emails") # cancel pending tasks
149
+ client.queues.retry_failed("emails") # replay failed tasks, e.g. after an outage
150
+ for group in client.queues.failures("emails"): # failed tasks grouped by error
151
+ print(group.count, group.error)
152
+ client.queues.retry_failed("emails", last_error="HTTP 503 Service Unavailable") # replay one group
153
+ client.queues.activity("emails") # succeeded/failed/cancelled in the last 7 days
154
+ client.queues.delete("emails") # delete the queue and all its tasks
155
+ ```
156
+
157
+ ## Schedules
158
+
159
+ A schedule calls a URL on a cron timetable; each call is a run, retried and recorded like a task. Schedules are separate from queues. `put` is declarative, like `queues.put`. See [Schedules](https://docs.workly.run/schedules/).
160
+
161
+ ```python
162
+ schedule = client.schedules.put(
163
+ "nightly-report",
164
+ cron="0 3 * * *",
165
+ timezone="Europe/Stockholm",
166
+ url="https://api.example.com/reports/nightly",
167
+ payload={"kind": "daily"},
168
+ max_attempts=3,
169
+ overlap="skip", # skip a slot while the previous run is still going
170
+ )
171
+ print(schedule.next_runs) # the next five times
172
+
173
+ run = client.schedules.trigger("nightly-report") # run it now
174
+ for run in client.schedules.runs("nightly-report", state="failed"):
175
+ print(run.id, run.scheduled_for, run.last_error)
176
+ client.runs.attempts(run.id)
177
+ client.runs.retry(run.id) # deliver it again, e.g. a failed or skipped run
178
+ client.schedules.pause("nightly-report")
179
+ client.schedules.resume("nightly-report") # from the next scheduled time
180
+ client.schedules.delete("nightly-report") # with all its runs
181
+ ```
182
+
183
+ Runs are delivered with `Workly-Run-Id`, `Workly-Schedule` and `Workly-Scheduled-For` headers and the same signature, so `verify_signature` works unchanged.
184
+
185
+ ## Async
186
+
187
+ `AsyncWorkly` has the same methods, as coroutines:
188
+
189
+ ```python
190
+ from workly import AsyncWorkly
191
+
192
+ async with AsyncWorkly() as client:
193
+ task = await client.tasks.enqueue("emails", url="...", payload={"user_id": 123})
194
+ async for task in client.tasks.list(queue="emails"):
195
+ ...
196
+ ```
197
+
198
+ ## Errors
199
+
200
+ | Exception | When |
201
+ |---|---|
202
+ | `BadRequestError` | 400, invalid request |
203
+ | `AuthenticationError` | 401, missing or wrong API key |
204
+ | `PermissionDeniedError` | 403, not allowed, or a hosted limit was reached (e.g. `quota_exceeded`) |
205
+ | `NotFoundError` | 404, no such queue or task |
206
+ | `ConflictError` | 409, e.g. retrying a running task |
207
+ | `PayloadTooLargeError` | 413 |
208
+ | `RateLimitError` | 429, still rate limited after the retries |
209
+ | `APIError` | base class of the above; has `.status`, `.code` (stable) and `.message` |
210
+ | `APIConnectionError` | the server couldn't be reached |
211
+
212
+ Requests are retried up to `max_retries` times (2 by default), honouring `Retry-After`. A 429 is always retried, since the server refused the request without doing anything. Connection errors and 502–504 are retried for requests that are safe to repeat: an enqueue only when it has an `idempotency_key`, or when the connection failed before the request was sent.
213
+
214
+ ## License
215
+
216
+ [Apache-2.0](https://github.com/worklydev/workly/blob/main/LICENSE)
workly-0.1.0/README.md ADDED
@@ -0,0 +1,196 @@
1
+ # Workly for Python
2
+
3
+ The Python SDK for [Workly](https://github.com/worklydev/workly), the open-source HTTP task queue. Enqueue a task, and Workly delivers it to your endpoint over HTTP, retrying with backoff until it succeeds.
4
+
5
+ ```sh
6
+ pip install workly # the SDK
7
+ pip install "workly[cli]" # the SDK plus the workly binary, for `workly dev`
8
+ ```
9
+
10
+ Requires Python 3.11+. The only dependency is [httpx](https://www.python-httpx.org). The `cli` extra adds [`workly-cli`](https://pypi.org/project/workly-cli/), the server binary (about 7 MB), which you usually want on dev machines and not in production images.
11
+
12
+ ## Quickstart
13
+
14
+ Start a local server with `workly dev` (SQLite, no auth, on :7337), then:
15
+
16
+ ```python
17
+ from workly import Workly
18
+
19
+ client = Workly() # WORKLY_URL, else http://localhost:7337; WORKLY_API_KEY
20
+ task = client.tasks.enqueue(
21
+ "emails",
22
+ url="https://api.example.com/send-email",
23
+ payload={"user_id": 123},
24
+ )
25
+ print(task.id, task.state)
26
+ ```
27
+
28
+ Your endpoint receives a `POST` with the JSON payload. Any 2xx marks the task succeeded. A 5xx, 408, 429, timeout or connection error is retried with backoff. Delivery is at-least-once, so make handlers safe to run twice. `Workly-Task-Id` is stable across attempts and works as a deduplication key.
29
+
30
+ ## Verifying deliveries
31
+
32
+ Every delivery is signed: with the server's `WORKLY_SIGNING_SECRET` when you run Workly yourself, or with your workspace's secret on [workly.run](#hosted-workly). Check the signature against the **raw** body:
33
+
34
+ ```python
35
+ from workly import SignatureVerificationError, verify_signature
36
+
37
+
38
+ # Flask
39
+ @app.post("/send-email")
40
+ def send_email():
41
+ try:
42
+ verify_signature(request.get_data(), request.headers) # secret from WORKLY_SIGNING_SECRET
43
+ except SignatureVerificationError:
44
+ abort(401)
45
+ ...
46
+
47
+
48
+ # FastAPI / Starlette
49
+ @app.post("/send-email")
50
+ async def send_email(request: Request):
51
+ verify_signature(await request.body(), request.headers, secret)
52
+ ...
53
+ ```
54
+
55
+ By default, signatures older than 5 minutes are rejected (`tolerance=`). `workly dev` signs with `workly-dev-secret`. To test your handler without a server, use `workly.sign(body, secret)`, which returns the headers Workly would send.
56
+
57
+ ## Hosted Workly
58
+
59
+ On [workly.run](https://workly.run), point the client at the hosted API and use the keys from the [console](https://console.workly.run):
60
+
61
+ ```sh
62
+ export WORKLY_URL=https://api.workly.run
63
+ export WORKLY_API_KEY=... # API keys page
64
+ export WORKLY_SIGNING_SECRET=whsec_... # same page; each workspace has its own
65
+ ```
66
+
67
+ Nothing else changes. Hosted workspaces have a request rate limit and a monthly task quota: requests over the rate limit are retried for you, and an enqueue over the quota raises `PermissionDeniedError` with the code `quota_exceeded`.
68
+
69
+ ## Tasks
70
+
71
+ ```python
72
+ from datetime import datetime, timedelta, timezone
73
+
74
+ client.tasks.enqueue(
75
+ "emails",
76
+ url="https://api.example.com/send-email",
77
+ payload={"user_id": 123}, # JSON; or body="raw text", content_type="text/csv"
78
+ method="POST", # default
79
+ headers={"X-Tenant": "acme"}, # sent with every delivery
80
+ delay_seconds=60, # or run_at=datetime(..., tzinfo=timezone.utc)
81
+ idempotency_key="welcome-123", # an existing task with this key is returned instead
82
+ max_attempts=5, # overrides the queue's setting
83
+ timeout_seconds=10, # likewise
84
+ )
85
+
86
+ # Up to 100 at once, all or nothing.
87
+ client.tasks.enqueue_many(
88
+ "emails",
89
+ [{"url": "https://api.example.com/send-email", "payload": {"user_id": i}} for i in range(100)],
90
+ )
91
+
92
+ task = client.tasks.get("task_01J9...")
93
+ for attempt in client.tasks.attempts(task.id):
94
+ print(attempt.number, attempt.outcome, attempt.status_code, attempt.duration_ms)
95
+
96
+ client.tasks.retry(task.id) # run now; replays a finished task
97
+ delivery = client.tasks.delivery(task.id) # the signed request, to replay by hand
98
+ client.tasks.cancel(task.id)
99
+
100
+ # Newest first, across pages. All filters are optional.
101
+ for task in client.tasks.list(
102
+ queue="emails", state="failed", created_after=datetime.now(timezone.utc) - timedelta(days=1)
103
+ ):
104
+ ...
105
+ ```
106
+
107
+ ## Queues
108
+
109
+ Queues are created automatically on first enqueue. `put` sets a queue's configuration declaratively, which makes it easy to keep in code: settings you leave out are reset to their defaults.
110
+
111
+ ```python
112
+ client.queues.put(
113
+ "emails",
114
+ max_attempts=10,
115
+ min_backoff_seconds=1,
116
+ max_backoff_seconds=3600,
117
+ backoff_multiplier=2,
118
+ timeout_seconds=30,
119
+ rate_per_second=50,
120
+ max_concurrency=20,
121
+ )
122
+
123
+ queue = client.queues.get("emails")
124
+ print(queue.stats.due, queue.stats.oldest_due_at)
125
+
126
+ client.queues.pause("emails") # stop delivering; enqueueing still works
127
+ client.queues.resume("emails")
128
+ client.queues.cancel_pending("emails") # cancel pending tasks
129
+ client.queues.retry_failed("emails") # replay failed tasks, e.g. after an outage
130
+ for group in client.queues.failures("emails"): # failed tasks grouped by error
131
+ print(group.count, group.error)
132
+ client.queues.retry_failed("emails", last_error="HTTP 503 Service Unavailable") # replay one group
133
+ client.queues.activity("emails") # succeeded/failed/cancelled in the last 7 days
134
+ client.queues.delete("emails") # delete the queue and all its tasks
135
+ ```
136
+
137
+ ## Schedules
138
+
139
+ A schedule calls a URL on a cron timetable; each call is a run, retried and recorded like a task. Schedules are separate from queues. `put` is declarative, like `queues.put`. See [Schedules](https://docs.workly.run/schedules/).
140
+
141
+ ```python
142
+ schedule = client.schedules.put(
143
+ "nightly-report",
144
+ cron="0 3 * * *",
145
+ timezone="Europe/Stockholm",
146
+ url="https://api.example.com/reports/nightly",
147
+ payload={"kind": "daily"},
148
+ max_attempts=3,
149
+ overlap="skip", # skip a slot while the previous run is still going
150
+ )
151
+ print(schedule.next_runs) # the next five times
152
+
153
+ run = client.schedules.trigger("nightly-report") # run it now
154
+ for run in client.schedules.runs("nightly-report", state="failed"):
155
+ print(run.id, run.scheduled_for, run.last_error)
156
+ client.runs.attempts(run.id)
157
+ client.runs.retry(run.id) # deliver it again, e.g. a failed or skipped run
158
+ client.schedules.pause("nightly-report")
159
+ client.schedules.resume("nightly-report") # from the next scheduled time
160
+ client.schedules.delete("nightly-report") # with all its runs
161
+ ```
162
+
163
+ Runs are delivered with `Workly-Run-Id`, `Workly-Schedule` and `Workly-Scheduled-For` headers and the same signature, so `verify_signature` works unchanged.
164
+
165
+ ## Async
166
+
167
+ `AsyncWorkly` has the same methods, as coroutines:
168
+
169
+ ```python
170
+ from workly import AsyncWorkly
171
+
172
+ async with AsyncWorkly() as client:
173
+ task = await client.tasks.enqueue("emails", url="...", payload={"user_id": 123})
174
+ async for task in client.tasks.list(queue="emails"):
175
+ ...
176
+ ```
177
+
178
+ ## Errors
179
+
180
+ | Exception | When |
181
+ |---|---|
182
+ | `BadRequestError` | 400, invalid request |
183
+ | `AuthenticationError` | 401, missing or wrong API key |
184
+ | `PermissionDeniedError` | 403, not allowed, or a hosted limit was reached (e.g. `quota_exceeded`) |
185
+ | `NotFoundError` | 404, no such queue or task |
186
+ | `ConflictError` | 409, e.g. retrying a running task |
187
+ | `PayloadTooLargeError` | 413 |
188
+ | `RateLimitError` | 429, still rate limited after the retries |
189
+ | `APIError` | base class of the above; has `.status`, `.code` (stable) and `.message` |
190
+ | `APIConnectionError` | the server couldn't be reached |
191
+
192
+ Requests are retried up to `max_retries` times (2 by default), honouring `Retry-After`. A 429 is always retried, since the server refused the request without doing anything. Connection errors and 502–504 are retried for requests that are safe to repeat: an enqueue only when it has an `idempotency_key`, or when the connection failed before the request was sent.
193
+
194
+ ## License
195
+
196
+ [Apache-2.0](https://github.com/worklydev/workly/blob/main/LICENSE)
@@ -0,0 +1,70 @@
1
+ [project]
2
+ name = "workly"
3
+ version = "0.1.0"
4
+ description = "Python SDK for Workly, the open-source HTTP task queue"
5
+ readme = "README.md"
6
+ license = "Apache-2.0"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.11"
9
+ dependencies = ["httpx>=0.27,<1"]
10
+ keywords = [
11
+ "task queue",
12
+ "background jobs",
13
+ "webhooks",
14
+ "http",
15
+ ]
16
+ classifiers = [
17
+ "Development Status :: 3 - Alpha",
18
+ "Framework :: AsyncIO",
19
+ "Intended Audience :: Developers",
20
+ "Programming Language :: Python :: 3",
21
+ "Typing :: Typed",
22
+ ]
23
+
24
+ [project.urls]
25
+ Homepage = "https://workly.run"
26
+ Repository = "https://github.com/worklydev/workly"
27
+
28
+ [project.optional-dependencies]
29
+ cli = ["workly-cli"]
30
+
31
+ [dependency-groups]
32
+ dev = [
33
+ "pytest>=8",
34
+ "ruff>=0.6",
35
+ "pyright>=1.1.380",
36
+ ]
37
+
38
+ [build-system]
39
+ requires = ["uv_build>=0.8,<0.13"]
40
+ build-backend = "uv_build"
41
+
42
+ [tool.ruff]
43
+ line-length = 100
44
+ target-version = "py311"
45
+
46
+ [tool.ruff.lint]
47
+ select = [
48
+ "E",
49
+ "F",
50
+ "W",
51
+ "I",
52
+ "B",
53
+ "UP",
54
+ "SIM",
55
+ "RUF",
56
+ ]
57
+
58
+ [tool.pyright]
59
+ include = [
60
+ "src",
61
+ "tests",
62
+ ]
63
+ typeCheckingMode = "strict"
64
+ reportPrivateUsage = false
65
+
66
+ [tool.pytest.ini_options]
67
+ testpaths = ["tests"]
68
+
69
+ [tool.uv]
70
+ exclude-dependencies = ["workly-cli"]