labtasker-server 2.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. labtasker_server-2.0.0/.gitignore +14 -0
  2. labtasker_server-2.0.0/LICENSE +201 -0
  3. labtasker_server-2.0.0/PKG-INFO +16 -0
  4. labtasker_server-2.0.0/pyproject.toml +30 -0
  5. labtasker_server-2.0.0/src/labtasker_server/__init__.py +3 -0
  6. labtasker_server-2.0.0/src/labtasker_server/__main__.py +3 -0
  7. labtasker_server-2.0.0/src/labtasker_server/app.py +416 -0
  8. labtasker_server-2.0.0/src/labtasker_server/cli.py +371 -0
  9. labtasker_server-2.0.0/src/labtasker_server/config.py +42 -0
  10. labtasker_server-2.0.0/src/labtasker_server/database.py +176 -0
  11. labtasker_server-2.0.0/src/labtasker_server/errors.py +27 -0
  12. labtasker_server-2.0.0/src/labtasker_server/filtering.py +528 -0
  13. labtasker_server-2.0.0/src/labtasker_server/local.py +453 -0
  14. labtasker_server-2.0.0/src/labtasker_server/logging.py +47 -0
  15. labtasker_server-2.0.0/src/labtasker_server/middleware.py +73 -0
  16. labtasker_server-2.0.0/src/labtasker_server/migrations/__init__.py +1 -0
  17. labtasker_server-2.0.0/src/labtasker_server/migrations/env.py +20 -0
  18. labtasker_server-2.0.0/src/labtasker_server/migrations/versions/0001_initial.py +135 -0
  19. labtasker_server-2.0.0/src/labtasker_server/migrations/versions/__init__.py +1 -0
  20. labtasker_server-2.0.0/src/labtasker_server/models.py +139 -0
  21. labtasker_server-2.0.0/src/labtasker_server/pagination.py +126 -0
  22. labtasker_server-2.0.0/src/labtasker_server/py.typed +1 -0
  23. labtasker_server-2.0.0/src/labtasker_server/schemas.py +265 -0
  24. labtasker_server-2.0.0/src/labtasker_server/services/__init__.py +1 -0
  25. labtasker_server-2.0.0/src/labtasker_server/services/queues.py +66 -0
  26. labtasker_server-2.0.0/src/labtasker_server/services/tasks.py +859 -0
  27. labtasker_server-2.0.0/src/labtasker_server/validation.py +150 -0
@@ -0,0 +1,14 @@
1
+ .venv/
2
+ .pytest_cache/
3
+ .coverage
4
+ coverage.xml
5
+ htmlcov/
6
+ .mypy_cache/
7
+ .ruff_cache/
8
+ __pycache__/
9
+ *.py[cod]
10
+ *.egg-info/
11
+ build/
12
+ dist/
13
+ site/
14
+ .labtasker/
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,16 @@
1
+ Metadata-Version: 2.5
2
+ Name: labtasker-server
3
+ Version: 2.0.0
4
+ Summary: SQLite/FastAPI server for parallel model inference and evaluation
5
+ Project-URL: Homepage, https://github.com/luocfprime/labtasker
6
+ Project-URL: Repository, https://github.com/luocfprime/labtasker.git
7
+ Author-email: lcf <luocfprime@gmail.com>
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Requires-Python: >=3.11
11
+ Requires-Dist: alembic<2,>=1.14
12
+ Requires-Dist: fastapi<1,>=0.115
13
+ Requires-Dist: pydantic<3,>=2.10
14
+ Requires-Dist: sqlalchemy<3,>=2.0
15
+ Requires-Dist: typer<1,>=0.16
16
+ Requires-Dist: uvicorn<1,>=0.34
@@ -0,0 +1,30 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "labtasker-server"
7
+ version = "2.0.0"
8
+ description = "SQLite/FastAPI server for parallel model inference and evaluation"
9
+ requires-python = ">=3.11"
10
+ license = "Apache-2.0"
11
+ license-files = ["LICENSE"]
12
+ authors = [{ name = "lcf", email = "luocfprime@gmail.com" }]
13
+ dependencies = [
14
+ "alembic>=1.14,<2",
15
+ "fastapi>=0.115,<1",
16
+ "pydantic>=2.10,<3",
17
+ "sqlalchemy>=2.0,<3",
18
+ "typer>=0.16,<1",
19
+ "uvicorn>=0.34,<1",
20
+ ]
21
+
22
+ [project.urls]
23
+ Homepage = "https://github.com/luocfprime/labtasker"
24
+ Repository = "https://github.com/luocfprime/labtasker.git"
25
+
26
+ [project.scripts]
27
+ labtasker-server = "labtasker_server.cli:app"
28
+
29
+ [tool.hatch.build.targets.wheel]
30
+ packages = ["src/labtasker_server"]
@@ -0,0 +1,3 @@
1
+ """Labtasker v2 HTTP server package."""
2
+
3
+ __version__ = "2.0.0"
@@ -0,0 +1,3 @@
1
+ from labtasker_server.cli import app
2
+
3
+ app()
@@ -0,0 +1,416 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import hmac
5
+ import logging
6
+ from collections.abc import AsyncIterator, Callable
7
+ from contextlib import asynccontextmanager, suppress
8
+ from typing import Annotated, Any
9
+
10
+ from fastapi import Depends, FastAPI, Query, Request, Response
11
+ from fastapi.exceptions import RequestValidationError
12
+ from fastapi.responses import JSONResponse
13
+ from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
14
+ from sqlalchemy import text
15
+
16
+ from labtasker_server.config import ServerSettings
17
+ from labtasker_server.database import Database
18
+ from labtasker_server.errors import DomainError
19
+ from labtasker_server.middleware import RequestBodyLimitMiddleware
20
+ from labtasker_server.schemas import (
21
+ BulkUpdateRequest,
22
+ BulkUpdateResult,
23
+ ClaimRequest,
24
+ ClaimResponse,
25
+ CompleteRequest,
26
+ CountResponse,
27
+ ErrorEnvelope,
28
+ FailRequest,
29
+ HealthyResponse,
30
+ HeartbeatResponse,
31
+ Queue,
32
+ RunRequest,
33
+ Task,
34
+ TaskCreate,
35
+ TaskOrderField,
36
+ TaskPage,
37
+ TaskStatus,
38
+ TaskUpdate,
39
+ UnhealthyResponse,
40
+ )
41
+ from labtasker_server.services.queues import QueueService
42
+ from labtasker_server.services.tasks import TaskService, system_now_us
43
+ from labtasker_server.validation import MAX_TASK_DATA_BYTES
44
+
45
+ EXPIRY_SCAN_INTERVAL_SECONDS = 60
46
+ logger = logging.getLogger(__name__)
47
+ BEARER = HTTPBearer(auto_error=False)
48
+ API_ERROR_RESPONSES: dict[int | str, dict[str, Any]] = {
49
+ status: {"model": ErrorEnvelope} for status in (401, 404, 409, 413, 422, 503)
50
+ }
51
+
52
+
53
+ def create_app(
54
+ settings: ServerSettings,
55
+ *,
56
+ now_us: Callable[[], int] = system_now_us,
57
+ ) -> FastAPI:
58
+ database = Database(settings.database, ownership_fd=settings.database_fd)
59
+ try:
60
+ database.initialize()
61
+ except BaseException:
62
+ database.dispose()
63
+ raise
64
+ queue_service = QueueService(database)
65
+ task_service = TaskService(database, now_us=now_us)
66
+ task_service.expire_leases()
67
+
68
+ @asynccontextmanager
69
+ async def lifespan(_: FastAPI) -> AsyncIterator[None]:
70
+ scanner = asyncio.create_task(_expiry_scanner(task_service))
71
+ try:
72
+ yield
73
+ finally:
74
+ scanner.cancel()
75
+ with suppress(asyncio.CancelledError):
76
+ await scanner
77
+ database.dispose()
78
+
79
+ app = FastAPI(docs_url=None, redoc_url=None, lifespan=lifespan)
80
+ app.add_middleware(RequestBodyLimitMiddleware, max_bytes=MAX_TASK_DATA_BYTES)
81
+ app.state.database = database
82
+ app.state.settings = settings
83
+ app.state.task_service = task_service
84
+
85
+ @app.exception_handler(DomainError)
86
+ async def handle_domain_error(_: Request, exc: DomainError) -> JSONResponse:
87
+ headers = {"WWW-Authenticate": "Bearer"} if exc.status_code == 401 else None
88
+ return JSONResponse(
89
+ status_code=exc.status_code,
90
+ content={"error": {"code": exc.code, "message": exc.message, "details": exc.details}},
91
+ headers=headers,
92
+ )
93
+
94
+ @app.exception_handler(RequestValidationError)
95
+ async def handle_request_validation(
96
+ request: Request,
97
+ exc: RequestValidationError,
98
+ ) -> JSONResponse:
99
+ code, details = _validation_error(request, exc)
100
+ if details is not None:
101
+ return JSONResponse(
102
+ status_code=422,
103
+ content={
104
+ "error": {
105
+ "code": code,
106
+ "message": (
107
+ "Request validation failed."
108
+ if code == "invalid_request"
109
+ else _specific_validation_message(code)
110
+ ),
111
+ "details": details,
112
+ }
113
+ },
114
+ )
115
+ errors = []
116
+ for error in exc.errors():
117
+ location = list(error.get("loc", ()))
118
+ if not location:
119
+ location = ["body"]
120
+ errors.append(
121
+ {
122
+ "location": location,
123
+ "message": str(error.get("msg", "Invalid value.")),
124
+ }
125
+ )
126
+ return JSONResponse(
127
+ status_code=422,
128
+ content={
129
+ "error": {
130
+ "code": code,
131
+ "message": "Request validation failed.",
132
+ "details": {"errors": errors},
133
+ }
134
+ },
135
+ )
136
+
137
+ def require_auth(
138
+ credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(BEARER)],
139
+ ) -> None:
140
+ token = settings.token
141
+ if token is None:
142
+ return
143
+ if credentials is None or credentials.scheme.lower() != "bearer":
144
+ raise _unauthorized()
145
+ if not hmac.compare_digest(credentials.credentials, token):
146
+ raise _unauthorized()
147
+
148
+ authenticated = [Depends(require_auth)]
149
+
150
+ @app.get(
151
+ "/health",
152
+ response_model=HealthyResponse,
153
+ responses={503: {"model": UnhealthyResponse}},
154
+ )
155
+ def health() -> JSONResponse:
156
+ try:
157
+ with database.read_session() as session:
158
+ session.execute(text("SELECT 1"))
159
+ except Exception:
160
+ return JSONResponse(
161
+ status_code=503,
162
+ content={"status": "error", "api_version": "2", "database": "error"},
163
+ )
164
+ return JSONResponse(
165
+ status_code=200,
166
+ content={"status": "ok", "api_version": "2", "database": "ok"},
167
+ )
168
+
169
+ @app.put(
170
+ "/api/v2/queues/{queue}",
171
+ response_model=Queue,
172
+ dependencies=authenticated,
173
+ responses={**API_ERROR_RESPONSES, 201: {"model": Queue}},
174
+ )
175
+ def create_queue(queue: str, response: Response) -> Queue:
176
+ result, created = queue_service.create(queue)
177
+ response.status_code = 201 if created else 200
178
+ return result
179
+
180
+ @app.get(
181
+ "/api/v2/queues",
182
+ response_model=list[Queue],
183
+ dependencies=authenticated,
184
+ responses=API_ERROR_RESPONSES,
185
+ )
186
+ def list_queues() -> list[Queue]:
187
+ return queue_service.list()
188
+
189
+ @app.delete(
190
+ "/api/v2/queues/{queue}",
191
+ status_code=204,
192
+ dependencies=authenticated,
193
+ responses=API_ERROR_RESPONSES,
194
+ )
195
+ def delete_queue(queue: str, cascade: bool = False) -> Response:
196
+ queue_service.delete(queue, cascade=cascade)
197
+ return Response(status_code=204)
198
+
199
+ @app.put(
200
+ "/api/v2/queues/{queue}/tasks/{task_id}",
201
+ response_model=Task,
202
+ dependencies=authenticated,
203
+ responses={**API_ERROR_RESPONSES, 201: {"model": Task}},
204
+ )
205
+ def create_task(queue: str, task_id: str, request: TaskCreate, response: Response) -> Task:
206
+ result, created = task_service.create(queue, task_id, request)
207
+ response.status_code = 201 if created else 200
208
+ return result
209
+
210
+ @app.get(
211
+ "/api/v2/queues/{queue}/tasks",
212
+ response_model=TaskPage,
213
+ dependencies=authenticated,
214
+ responses=API_ERROR_RESPONSES,
215
+ )
216
+ def list_tasks(
217
+ queue: str,
218
+ status: TaskStatus | None = None,
219
+ name: str | None = None,
220
+ filter_expression: Annotated[str | None, Query(alias="filter")] = None,
221
+ order_by: TaskOrderField = "created_at",
222
+ descending: bool = True,
223
+ limit: Annotated[int, Query(ge=1, le=1000)] = 100,
224
+ cursor: str | None = None,
225
+ ) -> TaskPage:
226
+ return task_service.list_tasks(
227
+ queue,
228
+ status=status,
229
+ name=name,
230
+ filter_expression=filter_expression,
231
+ order_by=order_by,
232
+ descending=descending,
233
+ limit=limit,
234
+ cursor=cursor,
235
+ )
236
+
237
+ @app.get(
238
+ "/api/v2/queues/{queue}/tasks/count",
239
+ response_model=CountResponse,
240
+ dependencies=authenticated,
241
+ responses=API_ERROR_RESPONSES,
242
+ )
243
+ def count_tasks(
244
+ queue: str,
245
+ status: TaskStatus | None = None,
246
+ name: str | None = None,
247
+ filter_expression: Annotated[str | None, Query(alias="filter")] = None,
248
+ ) -> CountResponse:
249
+ return CountResponse(
250
+ count=task_service.count_tasks(
251
+ queue,
252
+ status=status,
253
+ name=name,
254
+ filter_expression=filter_expression,
255
+ )
256
+ )
257
+
258
+ @app.get(
259
+ "/api/v2/queues/{queue}/tasks/{task_id}",
260
+ response_model=Task,
261
+ dependencies=authenticated,
262
+ responses=API_ERROR_RESPONSES,
263
+ )
264
+ def get_task(queue: str, task_id: str) -> Task:
265
+ return task_service.get(queue, task_id)
266
+
267
+ @app.patch(
268
+ "/api/v2/queues/{queue}/tasks/{task_id}",
269
+ response_model=Task,
270
+ dependencies=authenticated,
271
+ responses=API_ERROR_RESPONSES,
272
+ )
273
+ def update_task(queue: str, task_id: str, changes: TaskUpdate) -> Task:
274
+ return task_service.update_task(queue, task_id, changes)
275
+
276
+ @app.patch(
277
+ "/api/v2/queues/{queue}/tasks",
278
+ response_model=BulkUpdateResult,
279
+ dependencies=authenticated,
280
+ responses=API_ERROR_RESPONSES,
281
+ )
282
+ def update_tasks(queue: str, request: BulkUpdateRequest) -> BulkUpdateResult:
283
+ return task_service.update_tasks(
284
+ queue,
285
+ filter_expression=request.filter,
286
+ changes=request.changes,
287
+ )
288
+
289
+ @app.post(
290
+ "/api/v2/queues/{queue}/tasks/claim",
291
+ response_model=ClaimResponse,
292
+ dependencies=authenticated,
293
+ responses={**API_ERROR_RESPONSES, 204: {"description": "No eligible Task."}},
294
+ )
295
+ def claim_task(queue: str, request: ClaimRequest) -> ClaimResponse | Response:
296
+ claim = task_service.claim(queue, request.route, request.run_id)
297
+ return Response(status_code=204) if claim is None else claim
298
+
299
+ @app.post(
300
+ "/api/v2/queues/{queue}/tasks/{task_id}/heartbeat",
301
+ response_model=HeartbeatResponse,
302
+ dependencies=authenticated,
303
+ responses=API_ERROR_RESPONSES,
304
+ )
305
+ def heartbeat(queue: str, task_id: str, request: RunRequest) -> HeartbeatResponse:
306
+ return task_service.heartbeat(queue, task_id, request.run_id)
307
+
308
+ @app.post(
309
+ "/api/v2/queues/{queue}/tasks/{task_id}/complete",
310
+ status_code=204,
311
+ dependencies=authenticated,
312
+ responses=API_ERROR_RESPONSES,
313
+ )
314
+ def complete(queue: str, task_id: str, request: CompleteRequest) -> Response:
315
+ task_service.complete(queue, task_id, request.run_id, request.result)
316
+ return Response(status_code=204)
317
+
318
+ @app.post(
319
+ "/api/v2/queues/{queue}/tasks/{task_id}/fail",
320
+ status_code=204,
321
+ dependencies=authenticated,
322
+ responses=API_ERROR_RESPONSES,
323
+ )
324
+ def fail(queue: str, task_id: str, request: FailRequest) -> Response:
325
+ task_service.fail(queue, task_id, request.run_id, request.error)
326
+ return Response(status_code=204)
327
+
328
+ @app.post(
329
+ "/api/v2/queues/{queue}/tasks/{task_id}/unclaim",
330
+ status_code=204,
331
+ dependencies=authenticated,
332
+ responses=API_ERROR_RESPONSES,
333
+ )
334
+ def unclaim(queue: str, task_id: str, request: RunRequest) -> Response:
335
+ task_service.unclaim(queue, task_id, request.run_id)
336
+ return Response(status_code=204)
337
+
338
+ @app.post(
339
+ "/api/v2/queues/{queue}/tasks/{task_id}/cancel",
340
+ response_model=Task,
341
+ dependencies=authenticated,
342
+ responses=API_ERROR_RESPONSES,
343
+ )
344
+ def cancel_task(queue: str, task_id: str) -> Task:
345
+ return task_service.cancel(queue, task_id)
346
+
347
+ @app.post(
348
+ "/api/v2/queues/{queue}/tasks/{task_id}/requeue",
349
+ response_model=Task,
350
+ dependencies=authenticated,
351
+ responses=API_ERROR_RESPONSES,
352
+ )
353
+ def requeue_task(queue: str, task_id: str) -> Task:
354
+ return task_service.requeue(queue, task_id)
355
+
356
+ @app.delete(
357
+ "/api/v2/queues/{queue}/tasks/{task_id}",
358
+ status_code=204,
359
+ dependencies=authenticated,
360
+ responses=API_ERROR_RESPONSES,
361
+ )
362
+ def delete_task(queue: str, task_id: str) -> Response:
363
+ task_service.delete(queue, task_id)
364
+ return Response(status_code=204)
365
+
366
+ return app
367
+
368
+
369
+ async def _expiry_scanner(task_service: TaskService) -> None:
370
+ while True:
371
+ await asyncio.sleep(EXPIRY_SCAN_INTERVAL_SECONDS)
372
+ try:
373
+ await asyncio.to_thread(task_service.expire_leases)
374
+ except Exception:
375
+ logger.exception("Heartbeat expiry scan failed; it will retry in 60 seconds.")
376
+
377
+
378
+ def _unauthorized() -> DomainError:
379
+ return DomainError(401, "unauthorized", "Authentication is required.", {})
380
+
381
+
382
+ def _validation_code(request: Request) -> str:
383
+ if request.method == "PUT" and "/tasks/" in request.url.path:
384
+ return "invalid_task"
385
+ if request.method == "PATCH" and "/tasks" in request.url.path:
386
+ return "invalid_update"
387
+ return "invalid_request"
388
+
389
+
390
+ def _validation_error(
391
+ request: Request,
392
+ exc: RequestValidationError,
393
+ ) -> tuple[str, dict[str, object] | None]:
394
+ for error in exc.errors():
395
+ error_type = str(error.get("type", ""))
396
+ if error_type == "json_invalid":
397
+ return "invalid_request", {
398
+ "errors": [{"location": ["body"], "message": "Malformed JSON body."}]
399
+ }
400
+ if error_type in {"invalid_task_name", "json_too_deep"}:
401
+ context = error.get("ctx")
402
+ return error_type, dict(context) if isinstance(context, dict) else {}
403
+ if request.method == "PATCH" and request.url.path.endswith("/tasks"):
404
+ for error in exc.errors():
405
+ location = tuple(error.get("loc", ()))
406
+ if location[:2] == ("body", "filter"):
407
+ return "invalid_filter", None
408
+ return _validation_code(request), None
409
+
410
+
411
+ def _specific_validation_message(code: str) -> str:
412
+ if code == "json_too_deep":
413
+ return "JSON value is too deeply nested."
414
+ if code == "invalid_task_name":
415
+ return "Task name is invalid."
416
+ raise AssertionError(f"Unknown specific validation code: {code}")