Skip to content

Commit af2d5bf

Browse files
authored
Support worker dependencies in Worker.run and the CLI (#551)
## Motivation Worker-level dependencies already work through the Worker constructor, but standalone services cannot configure them through Worker.run(). This is useful for per-task logging context, tracing, and other cross-cutting dependencies while retaining task registration, healthcheck/metrics servers, signal handling, and graceful shutdown. ## Changes - Add an optional dependencies argument to Worker.run(), accepting the same mappings or sequences of configured dependency instances as the constructor. - Also accept a module:member path to a dependency collection, following the existing task-collection loading convention. - Expose that path through --dependencies and DOCKET_WORKER_DEPENDENCIES in the worker CLI. - Append the new argument to preserve existing positional calls and reuse constructor validation. - Document standalone usage and link it from production configuration guidance. - Update the CLI file-size baseline by the 13 lines added for the option and forwarding. ## Tests - Cover mappings, lists, and tuples, supplied directly or by import path. - Verify CurrentExecution access, per-task context isolation, cleanup on success and failure, and final execution states. - Cover import errors and rejection of bare dependency functions. - Exercise fresh CLI subprocesses with both the flag and environment variable, including flag precedence. ## Validation - REDIS_VERSION=8.10 uv run pytest (from python/): **1,201 passed, 7 skipped; 100% line and branch coverage**. - uv run zensical build: passed with no issues. - Python type checks and workspace lint, formatting, spelling, and file-size checks: passed. - git diff --check: passed. - The full prek run is blocked only on Rust clippy: the local rustc is 1.90.0, while the Rust workspace requires 1.99. No Rust code is changed.
1 parent 5d2ccd6 commit af2d5bf

8 files changed

Lines changed: 274 additions & 5 deletions

File tree

‎docs/dependency-injection.md‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -597,6 +597,52 @@ async with Worker(
597597
...
598598
```
599599

600+
### Standalone workers
601+
602+
[`Worker.run()`](api-reference.md#docket.Worker.run) accepts the same
603+
`dependencies` argument, while providing task registration, optional healthcheck
604+
and metrics servers, signal handling, and graceful shutdown for standalone workers:
605+
606+
```python
607+
import asyncio
608+
from docket import Depends, Worker
609+
610+
asyncio.run(
611+
Worker.run(
612+
docket_name="orders",
613+
tasks=["myapp.tasks:tasks"],
614+
dependencies=[Depends(trace_task)],
615+
healthcheck_port=8080,
616+
)
617+
)
618+
```
619+
620+
For the CLI, export a mapping or sequence of configured dependency instances
621+
from an importable module, such as `myapp.dependencies`:
622+
623+
```python
624+
# myapp/dependencies.py, alongside the trace_task function above
625+
worker_dependencies = [Depends(trace_task)]
626+
```
627+
628+
Load that collection with `--dependencies`:
629+
630+
```bash
631+
docket worker --tasks myapp.tasks:tasks \
632+
--dependencies myapp.dependencies:worker_dependencies
633+
```
634+
635+
For the CLI, you can also set `DOCKET_WORKER_DEPENDENCIES` to the `module:member`
636+
path. An explicit `--dependencies` option takes precedence. Direct calls to
637+
`Worker.run()` accept that path as the `dependencies` argument too, but do not
638+
read the CLI environment variables. Collections must contain dependency
639+
instances; wrap dependency functions with `Depends(...)`.
640+
641+
As with the constructor, `Depends(...)` resolves per task execution: context
642+
managers are entered for each execution and cleaned up afterward, including when
643+
a task fails. See [Docket in Production](production.md#worker-configuration) for
644+
the other worker settings.
645+
600646
### `single=True` dependencies
601647

602648
`Timeout`, `Retry`, `Perpetual`, `ConcurrencyLimit`, and `Debounce` are

‎docs/production.md‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ async with Worker(
2929

3030
### Environment Variable Configuration
3131

32-
All settings can be configured via environment variables:
32+
The worker CLI supports environment variables for its configuration:
3333

3434
```bash
3535
# Core docket settings
@@ -57,6 +57,11 @@ export DOCKET_LOGGING_FORMAT=json
5757
export DOCKET_TASKS=myapp.tasks:production_tasks
5858
```
5959

60+
To install [worker-level dependencies](dependency-injection.md#standalone-workers),
61+
set `DOCKET_WORKER_DEPENDENCIES=myapp.dependencies:worker_dependencies`, pointing
62+
to an exported mapping or sequence of dependency instances. These environment
63+
variables configure the CLI; direct `Worker.run()` calls take explicit arguments.
64+
6065
### CLI Usage
6166

6267
Run workers in production using the CLI:
@@ -78,9 +83,18 @@ docket worker \
7883
--tasks myapp.tasks:production_tasks
7984
```
8085

86+
Use `--dependencies myapp.dependencies:worker_dependencies` to load a dependency
87+
collection, overriding `DOCKET_WORKER_DEPENDENCIES` if set. See
88+
[Standalone workers](dependency-injection.md#standalone-workers) for the collection
89+
definition and the equivalent Python entry point using `Worker.run()`.
90+
8191
### Signal Handling
8292

83-
Workers catch `SIGTERM` and `SIGINT` and shut down gracefully — they stop accepting new tasks and wait for in-flight tasks to finish before exiting. On container orchestrators like Kubernetes, set `terminationGracePeriodSeconds` to be longer than your slowest expected task so the worker has time to drain. Tasks that don't finish before the grace period expires will be redelivered to other workers based on `redelivery_timeout`.
93+
Workers started through the CLI or `Worker.run()` catch `SIGTERM` and `SIGINT` and shut down gracefully — they stop accepting new tasks and wait for in-flight tasks to finish before exiting. On container orchestrators like Kubernetes, set `terminationGracePeriodSeconds` to be longer than your slowest expected task so the worker has time to drain. Tasks that don't finish before the grace period expires will be redelivered to other workers based on `redelivery_timeout`.
94+
95+
When embedding a worker in another framework, use `worker.run_forever()` or
96+
`worker.run_until_finished()` within the worker's async context manager. These
97+
methods leave signal handling to the host framework.
8498

8599
## Connection Management
86100

‎loq.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ max_lines = 1471
1616

1717
[[rules]]
1818
path = "python/src/docket/cli/__init__.py"
19-
max_lines = 969
19+
max_lines = 982
2020

2121
[[rules]]
2222
path = "python/src/docket/execution.py"

‎python/src/docket/cli/__init__.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,18 @@ def worker(
225225
envvar="DOCKET_FALLBACK_TASK",
226226
),
227227
] = None,
228+
dependencies: Annotated[
229+
str | None,
230+
typer.Option(
231+
"--dependencies",
232+
help=(
233+
"Path to a worker dependency collection (module:member). "
234+
"The collection is a mapping or sequence of Dependency instances "
235+
"(e.g., Depends(fn)) that run around every task."
236+
),
237+
envvar="DOCKET_WORKER_DEPENDENCIES",
238+
),
239+
] = None,
228240
) -> None:
229241
asyncio.run(
230242
Worker.run(
@@ -244,6 +256,7 @@ def worker(
244256
metrics_port=metrics_port,
245257
tasks=tasks,
246258
fallback_task=fallback_task,
259+
dependencies=dependencies,
247260
)
248261
)
249262

‎python/src/docket/worker.py‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -359,12 +359,16 @@ async def run(
359359
metrics_port: int | None = None,
360360
tasks: list[str] = ["docket.tasks:standard_tasks"],
361361
fallback_task: str | None = None,
362-
# Last in the list so that every positional call written against an
363-
# earlier version keeps its meaning.
362+
# Append new options so that existing positional calls keep their meaning.
364363
message_batch: int = MESSAGE_BATCH,
364+
dependencies: (Mapping[str, Any] | Sequence[Any] | str | None) = None,
365365
) -> None:
366366
"""Run a worker as the main entry point (CLI).
367367
368+
``dependencies`` accepts the same mapping or sequence of dependency
369+
instances as the constructor, or a ``module:member`` path to such a
370+
collection. These dependencies run around every task the worker executes.
371+
368372
This method installs signal handlers for graceful shutdown since it
369373
assumes ownership of the event loop. When embedding Docket in another
370374
framework (e.g., FastAPI with uvicorn), use Worker.run_forever() or
@@ -378,6 +382,11 @@ async def run(
378382
module = importlib.import_module(module_name)
379383
resolved_fallback_task = getattr(module, member_name)
380384

385+
if isinstance(dependencies, str):
386+
module_name, _, member_name = dependencies.rpartition(":")
387+
module = importlib.import_module(module_name)
388+
dependencies = getattr(module, member_name)
389+
381390
with (
382391
healthcheck_server(port=healthcheck_port),
383392
metrics_server(port=metrics_port),
@@ -403,6 +412,7 @@ async def run(
403412
schedule_automatic_tasks=schedule_automatic_tasks,
404413
enable_internal_instrumentation=enable_internal_instrumentation,
405414
fallback_task=resolved_fallback_task,
415+
dependencies=dependencies,
406416
) as worker
407417
):
408418
# Install signal handlers for graceful shutdown.

‎python/tests/cli/test_worker.py‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,48 @@ async def run(**kwargs: object) -> None:
7575
assert passed["message_batch"] == 17
7676

7777

78+
@pytest.mark.skipif(
79+
os.environ.get("REDIS_VERSION") == "memory",
80+
reason="Memory backend doesn't share state across processes",
81+
)
82+
@pytest.mark.parametrize("from_env", [False, True])
83+
async def test_worker_loads_dependencies(docket: Docket, from_env: bool) -> None:
84+
"""A fresh CLI process loads dependencies and applies them to queued tasks."""
85+
from tests.cli.worker_dependencies import task_with_context
86+
87+
await docket.add(task_with_context, key="cli-dependency")()
88+
89+
path = "tests.cli.worker_dependencies:dependencies"
90+
args = [
91+
"worker",
92+
"--url",
93+
docket.url,
94+
"--docket",
95+
docket.name,
96+
"--tasks",
97+
"tests.cli.worker_dependencies:tasks",
98+
"--logging-level",
99+
"WARNING",
100+
"--until-finished",
101+
"--no-schedule-automatic-tasks",
102+
]
103+
env = {"DOCKET_WORKER_DEPENDENCIES": path}
104+
if from_env:
105+
result = await run_cli(*args, env=env)
106+
else:
107+
# An explicit flag takes precedence over an environment default.
108+
env["DOCKET_WORKER_DEPENDENCIES"] = "missing_module:dependencies"
109+
result = await run_cli(*args, "--dependencies", path, env=env)
110+
111+
assert result.exit_code == 0, result.output
112+
assert "ERROR" not in result.output
113+
assert result.stdout.splitlines() == [
114+
"enter cli-dependency",
115+
"task cli-dependency",
116+
"exit cli-dependency",
117+
]
118+
119+
78120
def test_no_schedule_automatic_tasks_flag_reaches_the_worker(
79121
monkeypatch: pytest.MonkeyPatch,
80122
):
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
"""Importable collections for the worker CLI dependency integration tests."""
2+
3+
from contextlib import asynccontextmanager
4+
from contextvars import ContextVar
5+
from typing import AsyncGenerator
6+
7+
from docket import CurrentExecution, Depends, Execution
8+
9+
10+
task_context: ContextVar[str] = ContextVar("task_context")
11+
12+
13+
@asynccontextmanager
14+
async def task_logging_context(
15+
execution: Execution = CurrentExecution(),
16+
) -> AsyncGenerator[None, None]:
17+
token = task_context.set(execution.key)
18+
print(f"enter {execution.key}")
19+
try:
20+
yield
21+
finally:
22+
print(f"exit {execution.key}")
23+
task_context.reset(token)
24+
25+
26+
async def task_with_context() -> None:
27+
print(f"task {task_context.get()}")
28+
29+
30+
dependencies = [Depends(task_logging_context)]
31+
tasks = [task_with_context]
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
"""Worker.run installs worker dependencies while loading task collections."""
2+
3+
import sys
4+
from contextlib import asynccontextmanager
5+
from contextvars import ContextVar
6+
from types import ModuleType
7+
from typing import AsyncGenerator
8+
from uuid import uuid4
9+
10+
import pytest
11+
12+
from docket import CurrentExecution, Depends, Docket, Execution, Worker
13+
from docket.execution import ExecutionState
14+
15+
16+
@pytest.mark.parametrize("collection_kind", ["mapping", "list", "tuple"])
17+
@pytest.mark.parametrize("by_path", [False, True])
18+
async def test_run_dependencies_bracket_tasks(
19+
monkeypatch: pytest.MonkeyPatch, collection_kind: str, by_path: bool
20+
) -> None:
21+
events: list[tuple[str, str]] = []
22+
task_context: ContextVar[str] = ContextVar("task_context")
23+
24+
@asynccontextmanager
25+
async def logging_context(
26+
execution: Execution = CurrentExecution(),
27+
) -> AsyncGenerator[None, None]:
28+
assert task_context.get(None) is None
29+
events.append(("enter", execution.key))
30+
token = task_context.set(execution.key)
31+
try:
32+
yield
33+
finally:
34+
events.append(("exit", execution.key))
35+
task_context.reset(token)
36+
37+
async def task(fail: bool) -> None:
38+
events.append(("task", task_context.get()))
39+
if fail:
40+
raise ValueError("task failed")
41+
42+
dependency = Depends(logging_context)
43+
if collection_kind == "mapping":
44+
dependencies = {"logging": dependency}
45+
elif collection_kind == "tuple":
46+
dependencies = (dependency,)
47+
else:
48+
dependencies = [dependency]
49+
50+
module = ModuleType("run_dependencies_fixture")
51+
setattr(module, "tasks", [task])
52+
setattr(module, "dependencies", dependencies)
53+
monkeypatch.setitem(sys.modules, module.__name__, module)
54+
55+
url = f"memory://{uuid4()}"
56+
async with Docket(name="run-dependencies", url=url) as docket:
57+
successful = await docket.add(task, key="successful")(False)
58+
failed = await docket.add(task, key="failed")(True)
59+
60+
await Worker.run(
61+
docket_name=docket.name,
62+
url=url,
63+
tasks=[f"{module.__name__}:tasks"],
64+
dependencies=f"{module.__name__}:dependencies" if by_path else dependencies,
65+
concurrency=1,
66+
schedule_automatic_tasks=False,
67+
until_finished=True,
68+
)
69+
70+
await successful.sync()
71+
await failed.sync()
72+
73+
for key in ("successful", "failed"):
74+
assert [event for event in events if event[1] == key] == [
75+
("enter", key),
76+
("task", key),
77+
("exit", key),
78+
]
79+
assert task_context.get(None) is None
80+
assert successful.state == ExecutionState.COMPLETED
81+
assert failed.state == ExecutionState.FAILED
82+
83+
84+
@pytest.mark.parametrize(
85+
("path", "error"),
86+
[
87+
("missing_worker_dependencies:dependencies", ModuleNotFoundError),
88+
("docket.tasks:missing_dependencies", AttributeError),
89+
],
90+
)
91+
async def test_run_dependency_import_errors(path: str, error: type[Exception]) -> None:
92+
with pytest.raises(error):
93+
await Worker.run(url="memory://", dependencies=path)
94+
95+
96+
@pytest.mark.parametrize("by_path", [False, True])
97+
async def test_run_rejects_bare_dependency_functions(
98+
monkeypatch: pytest.MonkeyPatch, by_path: bool
99+
) -> None:
100+
def dependency() -> None: ...
101+
102+
module = ModuleType("invalid_dependencies_fixture")
103+
setattr(module, "dependencies", [dependency])
104+
monkeypatch.setitem(sys.modules, module.__name__, module)
105+
106+
with pytest.raises(TypeError, match="must be a Dependency instance"):
107+
await Worker.run(
108+
url=f"memory://{uuid4()}",
109+
tasks=[],
110+
dependencies=f"{module.__name__}:dependencies" if by_path else [dependency],
111+
schedule_automatic_tasks=False,
112+
until_finished=True,
113+
)

0 commit comments

Comments
 (0)