Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions docs/dependency-injection.md
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +438,25 @@ async def task_b(pool: AsyncConnectionPool = Shared(create_db_pool)) -> None:
...
```

### Declaring dependencies with `Annotated`

`Depends`, `Shared`, `CallArgument`, `TaskArgument`, and the contextual dependencies also work as `Annotated` metadata, so you can name a dependency once and reuse it across tasks:

```python
from typing import Annotated
from docket import CurrentDocket, Depends, Docket

DB = Annotated[Connection, Depends(get_db_connection)]

async def update_user(user_id: int, db: DB) -> None:
await db.execute("UPDATE users SET ...", user_id)

async def notify(user_id: int, docket: Annotated[Docket, CurrentDocket()]) -> None:
...
```

This resolves exactly like `db: Connection = Depends(get_db_connection)`. The difference is that `db` stays a required parameter, so a type checker flags a direct call to `update_user(1)` that the default form would let through. Declare a parameter's value one way only: a parameter with both a dependency in its metadata and a dependency default raises `TypeError`.

### Error Handling

When dependencies fail, the entire task fails with detailed error information:
Expand Down Expand Up @@ -515,6 +534,19 @@ async def fetch_pages(
...
```

A dependency in metadata wraps the call unless it subclasses `Provider`, in which case it supplies the parameter's value instead, as `Depends` does. Subclass `Provider` rather than `Dependency` for a custom dependency that should work both ways:
Comment thread
chrisguidry marked this conversation as resolved.
Resolved

```python
from docket.dependencies import Provider

class CurrentTenant(Provider[str]):
async def __aenter__(self) -> str:
return current_tenant.get()

async def bill(invoice_id: int, tenant: Annotated[str, CurrentTenant()]) -> None:
...
```

For parameterless subclasses the bare class is shorthand: `Annotated[list[str], Traced]` and `Annotated[list[str], Traced()]` are equivalent.

Inside `__aenter__`, you can access the current execution context through the
Expand Down
2 changes: 1 addition & 1 deletion python/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ dependencies = [
"typer>=0.15.1",
"typing_extensions>=4.12.0",
"tzdata>=2025.2; sys_platform == 'win32'",
"uncalled-for>=0.4.0",
"uncalled-for>=0.6.0",
]

[project.optional-dependencies]
Expand Down
2 changes: 2 additions & 0 deletions python/src/docket/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
ExponentialRetry,
Perpetual,
Progress,
Provided,
Retry,
Shared,
TaskArgument,
Expand Down Expand Up @@ -67,6 +68,7 @@
"Logged",
"Perpetual",
"Progress",
"Provided",
"Retry",
"Shared",
"StrikeList",
Expand Down
4 changes: 4 additions & 0 deletions python/src/docket/dependencies/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
CompletionHandler,
Dependency,
FailureHandler,
Provided,
Provider,
Runtime,
TaskOutcome,
current_docket,
Expand Down Expand Up @@ -61,6 +63,8 @@
__all__ = [
# Base
"Dependency",
"Provided",
"Provider",
"Runtime",
"FailureHandler",
"CompletionHandler",
Expand Down
6 changes: 5 additions & 1 deletion python/src/docket/dependencies/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@
from datetime import timedelta
from typing import TYPE_CHECKING, Any, Awaitable, Callable, TypeVar

from uncalled_for import Dependency as Dependency
from uncalled_for import (
Dependency as Dependency,
Provided as Provided,
Provider as Provider,
)

if TYPE_CHECKING: # pragma: no cover
from ..docket import Docket
Expand Down
8 changes: 6 additions & 2 deletions python/src/docket/dependencies/_concurrency.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

from opentelemetry import propagate

from uncalled_for import current_frame

from .._cancellation import CANCEL_MSG_CLEANUP, cancel_task
from .._lua import Arg, Args, Key, redis_script
from .._redis import RedisClient
Expand Down Expand Up @@ -228,9 +230,11 @@ async def __aenter__(self) -> ConcurrencyLimit:
# any independent prefix in cluster mode.
scope = f"{docket.prefix}:{self.scope}" if self.scope else docket.prefix
if self.argument_name is not None:
# The frame returns the value the task receives: the caller's
# argument, the value a dependency supplies, or the default.
try:
argument_value = execution.get_argument(self.argument_name)
except KeyError as e:
argument_value = await current_frame().resolve(self.argument_name)
except LookupError as e:
raise ValueError(
f"ConcurrencyLimit argument '{self.argument_name}' not found in "
f"task arguments. Available: {list(execution.kwargs.keys())}"
Expand Down
14 changes: 7 additions & 7 deletions python/src/docket/dependencies/_contextual.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,18 @@
import logging
from typing import TYPE_CHECKING, Any, cast

from uncalled_for import current_frame
from uncalled_for import Provider, current_frame
from uncalled_for.frames import _CallArgument # pyright: ignore[reportPrivateUsage]

from ._base import Dependency, current_docket, current_execution, current_worker
from ._base import current_docket, current_execution, current_worker

if TYPE_CHECKING: # pragma: no cover
from ..docket import Docket
from ..execution import Execution
from ..worker import Worker


class _CurrentWorker(Dependency["Worker"]):
class _CurrentWorker(Provider["Worker"]):
async def __aenter__(self) -> Worker:
return current_worker.get()

Expand All @@ -34,7 +34,7 @@ async def my_task(worker: Worker = CurrentWorker()) -> None:
return cast("Worker", _CurrentWorker())


class _CurrentDocket(Dependency["Docket"]):
class _CurrentDocket(Provider["Docket"]):
async def __aenter__(self) -> Docket:
return current_docket.get()

Expand All @@ -52,7 +52,7 @@ async def my_task(docket: Docket = CurrentDocket()) -> None:
return cast("Docket", _CurrentDocket())


class _CurrentExecution(Dependency["Execution"]):
class _CurrentExecution(Provider["Execution"]):
async def __aenter__(self) -> Execution:
return current_execution.get()

Expand All @@ -70,7 +70,7 @@ async def my_task(execution: Execution = CurrentExecution()) -> None:
return cast("Execution", _CurrentExecution())


class _TaskKey(Dependency[str]):
class _TaskKey(Provider[str]):
async def __aenter__(self) -> str:
return current_execution.get().key

Expand Down Expand Up @@ -129,7 +129,7 @@ async def greet_customer(customer_id: int, name: str = Depends(customer_name)) -
return cast(Any, _TaskArgument(parameter, optional))


class _TaskLogger(Dependency["logging.LoggerAdapter[logging.Logger]"]):
class _TaskLogger(Provider["logging.LoggerAdapter[logging.Logger]"]):
async def __aenter__(self) -> logging.LoggerAdapter[logging.Logger]:
execution = current_execution.get()
logger = logging.getLogger(f"docket.task.{execution.function_name}")
Expand Down
3 changes: 1 addition & 2 deletions python/src/docket/dependencies/_resolution.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,9 +168,8 @@ def _provided_arguments(execution: Execution) -> dict[str, Any]:
When the arguments do not bind to the signature, fall back to the keyword
arguments alone; calling the task will fail later with the same TypeError.
"""
signature = get_signature(execution.function)
try:
bound = signature.bind(*execution.args, **execution.kwargs)
bound = execution.bind_arguments()
except TypeError:
return dict(execution.kwargs)
return dict(bound.arguments)
Expand Down
32 changes: 25 additions & 7 deletions python/src/docket/execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -427,11 +427,27 @@ def specific_labels(self) -> Mapping[str, str | int]:
"docket.attempt": self.attempt,
}

def get_argument(self, parameter: str) -> Any:
def bind_arguments(self) -> inspect.BoundArguments:
"""Bind the caller's arguments to the task's parameters.

The caller may leave out a parameter whose value a dependency supplies,
including an ``Annotated`` one with no default, because the worker
resolves it. Any other missing parameter raises ``TypeError``, as
calling the task would.
"""
signature = get_signature(self.function)
bound_args = signature.bind(*self.args, **self.kwargs)
bound_args.apply_defaults()
return bound_args.arguments[parameter]
bound = signature.bind_partial(*self.args, **self.kwargs)
supplied = uncalled_for.get_dependency_parameters(self.function)
for name, parameter in signature.parameters.items():
if (
name not in bound.arguments
and name not in supplied
Comment thread
chrisguidry marked this conversation as resolved.
Resolved
and parameter.default is parameter.empty
and parameter.kind
not in (parameter.VAR_POSITIONAL, parameter.VAR_KEYWORD)
):
raise TypeError(f"missing a required argument: {name!r}")
return bound

def call_repr(self) -> str:
arguments: list[str] = []
Expand Down Expand Up @@ -1067,12 +1083,14 @@ async def subscribe(
yield message_data


def compact_signature(signature: inspect.Signature) -> str:
def compact_signature(function: Callable[..., Any]) -> str:
"""Describe a task's caller-supplied parameters, collapsing the rest to ``...``."""
parameters: list[str] = []
dependencies: int = 0
supplied = uncalled_for.get_dependency_parameters(function)

for parameter in signature.parameters.values():
if isinstance(parameter.default, uncalled_for.Dependency):
for parameter in get_signature(function).parameters.values():
if parameter.name in supplied:
dependencies += 1
continue

Expand Down
6 changes: 1 addition & 5 deletions python/src/docket/strikelist.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,19 +383,15 @@ def _is_dict_stricken(self, params: Mapping[str, Any]) -> bool:
return False

def _matches_task_or_parameter_strike(self, execution: "Execution") -> bool:
from .execution import get_signature

function_name = execution.function_name

# Check if the entire task is stricken (without parameter conditions)
task_strikes = self.task_strikes.get(function_name, {})
if function_name in self.task_strikes and not task_strikes:
return True

signature = get_signature(execution.function)

try:
bound_args = signature.bind(*execution.args, **execution.kwargs)
bound_args = execution.bind_arguments()
bound_args.apply_defaults()
except TypeError:
# If we can't make sense of the arguments, just assume the task is fine
Expand Down
15 changes: 7 additions & 8 deletions python/src/docket/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
current_worker,
format_duration,
get_annotation_dependencies,
get_dependency_parameters,
get_single_dependency_of_type,
get_single_dependency_parameter_of_type,
resolved_dependencies,
Expand All @@ -68,7 +69,7 @@
RedisMessageID,
RedisReadGroupResponse,
)
from .execution import TaskFunction, compact_signature, get_signature
from .execution import TaskFunction, compact_signature
from .instrumentation import (
QUEUE_DEPTH,
REDIS_DISRUPTIONS,
Expand Down Expand Up @@ -561,9 +562,7 @@ def _dependency_lifecycle_classes(self) -> list[type[Dependency[Any]]]:
seen: set[type[Dependency[Any]]] = set()
ordered: list[type[Dependency[Any]]] = []

def consider(dep: Any) -> None:
if not isinstance(dep, Dependency):
return
def consider(dep: Dependency[Any]) -> None:
cls = type(dep)
if cls in seen or not hasattr(cls, "worker_lifecycle"):
return
Expand All @@ -572,11 +571,11 @@ def consider(dep: Any) -> None:

for task_func in self.docket.tasks.values():
try:
sig = get_signature(task_func)
supplied = get_dependency_parameters(task_func)
except (ValueError, TypeError): # pragma: no cover
continue
for param in sig.parameters.values():
consider(param.default)
for dep in supplied.values():
consider(dep)
for deps in get_annotation_dependencies(task_func).values():
for dep in deps:
consider(dep)
Expand Down Expand Up @@ -1269,7 +1268,7 @@ async def _execute(self, execution: Execution, session: _ProcessingSession) -> N
def _startup_log(self) -> None:
logger.info("Starting worker %r with the following tasks:", self.name)
for task_name, task in self.docket.tasks.items():
logger.info("* %s(%s)", task_name, compact_signature(get_signature(task)))
logger.info("* %s(%s)", task_name, compact_signature(task))

@property
def workers_set(self) -> str:
Expand Down
31 changes: 30 additions & 1 deletion python/tests/concurrency_limits/test_annotated.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

import pytest

from docket import ConcurrencyLimit, Docket, Worker
from docket import ConcurrencyLimit, Depends, Docket, Provided, TaskArgument, Worker

from tests.concurrency_limits.overlap import assert_some_overlap

Expand Down Expand Up @@ -152,3 +152,32 @@ async def task(customer_id: Annotated[int, ConcurrencyLimit(1)]):
async with docket.redis() as redis:
key = f"{docket.prefix}:concurrency:customer_id:42"
assert await redis.exists(key) == 0


def tenant_of(customer_id: Annotated[int, TaskArgument()]) -> str:
return f"tenant-{customer_id}"


Tenant = Annotated[str, Depends(tenant_of), ConcurrencyLimit(1)]


async def test_annotated_concurrency_limit_keys_on_a_provided_value(
docket: Docket, worker: Worker
):
"""A limit on a dependency-supplied parameter keys on the resolved value."""
execution_intervals: dict[str, tuple[float, float]] = {}

async def task(customer_id: int, tenant: Tenant = Provided):
start = time.monotonic()
await asyncio.sleep(0.1)
execution_intervals[tenant] = (start, time.monotonic())

await docket.add(task)(customer_id=1)
await docket.add(task)(customer_id=2)

worker.concurrency = 10
await worker.run_until_finished()

assert set(execution_intervals) == {"tenant-1", "tenant-2"}
intervals = list(execution_intervals.values())
assert_some_overlap(intervals, "Different tenants should run concurrently")
13 changes: 7 additions & 6 deletions python/tests/test_annotated_dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
async def process(customer_id: Annotated[int, ConcurrencyLimit(1)]): ...

The parameter keeps its real value (the int); the dependency runs as a
side-effect (acquiring the concurrency slot).
side-effect (acquiring the concurrency slot). Dependencies that supply a
value, such as ``Depends``, are tested in test_annotated_providers.py.
"""

from __future__ import annotations
Expand All @@ -21,24 +22,24 @@ async def process(customer_id: Annotated[int, ConcurrencyLimit(1)]): ...

async def my_side_effect() -> str:
_side_effects.append("side_effect_ran")
return "unused"
return "configured"


async def test_annotated_depends_side_effect(docket: Docket, worker: Worker):
"""Annotated Depends runs as a side-effect (doesn't produce the param value)."""
async def test_annotated_depends_supplies_value(docket: Docket, worker: Worker):
"""Annotated Depends supplies the parameter's value, like a Depends default."""
_side_effects.clear()

async def task(
customer_id: int,
_setup: Annotated[str, Depends(my_side_effect)] = "",
):
_side_effects.append(f"task_{customer_id}")
_side_effects.append(f"task_{customer_id}_{_setup}")

await docket.add(task)(customer_id=1)
await worker.run_until_finished()

assert "side_effect_ran" in _side_effects
assert "task_1" in _side_effects
assert "task_1_configured" in _side_effects


async def test_mixed_default_and_annotation_deps(docket: Docket, worker: Worker):
Expand Down
Loading
Loading