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
6 changes: 6 additions & 0 deletions docs/dependency-injection.md
Original file line number Diff line number Diff line change
Expand Up @@ -581,6 +581,12 @@ async def audited_task(
```


### Subclassing the built-in behaviors

You can also subclass a built-in behavior to change one part of it: override `handle_failure` on `Retry`, `on_complete` on `Perpetual` or `Cron`, or `run` on `Timeout`. The task receives an instance of your subclass, and the worker calls your overrides. See [Custom Retry Policies](task-behaviors.md#custom-retry-policies) for an example.

Each execution works with a shallow copy of the instance you declared, so your subclass's constructor may take any arguments, and attributes it sets are available on the copy. `ConcurrencyLimit`, `Cooldown`, `RateLimit`, and `Debounce` are copied the same way when they are bound to a parameter through `Annotated`.

## Worker-level dependencies

Sometimes you want a dependency to run around **every** task a worker
Expand Down
55 changes: 55 additions & 0 deletions docs/task-behaviors.md
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,61 @@ async def call_flaky_api(

You can also pass `attempts=None` directly, which is equivalent.

### Retries with Perpetual and Cron

A task can declare a retry alongside `Perpetual` or `Cron`. The retry applies within one run: a run that fails is retried until it succeeds or its attempts are used up, and only then is the next run scheduled. Each run starts again at attempt 1, so a task that always fails makes `attempts` attempts in every run.

```python
async def hourly_sync(
perpetual: Perpetual = Perpetual(every=timedelta(hours=1)),
retry: Retry = Retry(attempts=3, delay=timedelta(seconds=30)),
) -> None:
# Up to 3 attempts per run, 30 seconds apart; the next run is scheduled
# an hour after the last attempt started
await sync_external_data()
```

Exhausted retries never stop the cycle. A task that should stop rescheduling itself once its retries run out calls `perpetual.cancel()` on its last attempt:

```python
async def sync_until_it_fails(
perpetual: Perpetual = Perpetual(every=timedelta(hours=1)),
retry: Retry = Retry(attempts=3, delay=timedelta(seconds=30)),
) -> None:
try:
await sync_external_data()
except Exception:
if retry.attempt == retry.attempts:
perpetual.cancel()
raise
```

Each attempt receives its own `Perpetual`, so `cancel()`, `perpetuate()`, `after()`, and `at()` take effect only on the attempt that ends the run; a call on an attempt that is retried is discarded. For an automatic task `cancel()` only pauses it until a worker next adds it, so use `docket.strike()` to stop one durably.

### Custom Retry Policies

To decide for yourself which failures are retried, subclass `Retry` or `ExponentialRetry` and override `handle_failure`. Return `False` to let the task fail, or call the base method to retry as usual:

```python
from docket import Retry
from docket.dependencies import TaskOutcome
from docket.execution import Execution

class RetryUnlessInvalid(Retry):
async def handle_failure(self, execution: Execution, outcome: TaskOutcome) -> bool:
if isinstance(outcome.exception, ValueError):
return False
return await super().handle_failure(execution, outcome)

async def import_record(
record_id: str,
retry: Retry = RetryUnlessInvalid(attempts=5),
) -> None:
await import_from_source(record_id)
```

Each attempt receives a shallow copy of the retry the task declared, with `attempt` set, so attributes a subclass sets in its constructor are available in the task and in `handle_failure`. An attribute that an attempt assigns on its copy is not carried to the next attempt, which may run on another worker; keep a count that must outlast one attempt in Redis or another store. A mutable attribute such as a list is the same object in every copy, so do not use one for per-attempt state.

## Task Timeouts

Prevent tasks from running too long with the `Timeout` dependency:
Expand Down
26 changes: 13 additions & 13 deletions python/src/docket/dependencies/_concurrency.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@
from __future__ import annotations

import asyncio
import copy
import json
import logging
from contextlib import asynccontextmanager
from datetime import datetime, timedelta, timezone
from typing import TYPE_CHECKING, Any, AsyncIterator, overload
from typing import TYPE_CHECKING, Any, AsyncIterator, Self, overload

from opentelemetry import propagate

Expand Down Expand Up @@ -199,16 +200,14 @@ def __init__(
self._renewal_task: asyncio.Task[None] | None = None
self._redelivery_timeout: timedelta | None = None

def bind_to_parameter(self, name: str, value: Any) -> ConcurrencyLimit:
def bind_to_parameter(self, name: str, value: Any) -> Self:
"""Bind to an ``Annotated`` parameter, inferring argument_name if not set."""
argument_name = self.argument_name if self.argument_name is not None else name
return ConcurrencyLimit(
argument_name,
max_concurrent=self.max_concurrent,
scope=self.scope,
)
bound = copy.copy(self)
if bound.argument_name is None:
bound.argument_name = name
return bound

async def __aenter__(self) -> ConcurrencyLimit:
async def __aenter__(self) -> Self:
from ._functional import _Depends

execution = current_execution.get()
Expand Down Expand Up @@ -245,10 +244,11 @@ async def __aenter__(self) -> ConcurrencyLimit:
else:
concurrency_key = f"{scope}:concurrency:{execution.function_name}"

# Create a NEW instance for this specific task execution. The
# original (the default parameter value) is shared across all calls,
# so its attributes must not be mutated.
limit = ConcurrencyLimit(self.argument_name, self.max_concurrent, self.scope)
# Copy the instance for this specific task execution. The original
# (the default parameter value) is shared across all calls, so its
# attributes must not be mutated. Copying keeps a subclass and its
# state without calling its constructor.
limit = copy.copy(self)
limit._concurrency_key = concurrency_key
limit._initialized = True
limit._task_key = execution.key
Expand Down
7 changes: 4 additions & 3 deletions python/src/docket/dependencies/_cooldown.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@

from __future__ import annotations

import copy
from datetime import timedelta
from types import TracebackType
from typing import Any
from typing import Any, Self

from ._base import AdmissionBlocked, Dependency, current_docket, current_execution

Expand Down Expand Up @@ -38,8 +39,8 @@ def __init__(self, window: timedelta, *, scope: str | None = None) -> None:
self._argument_name: str | None = None
self._argument_value: Any = None

def bind_to_parameter(self, name: str, value: Any) -> Cooldown:
bound = Cooldown(self.window, scope=self.scope)
def bind_to_parameter(self, name: str, value: Any) -> Self:
bound = copy.copy(self)
bound._argument_name = name
bound._argument_value = value
return bound
Expand Down
14 changes: 7 additions & 7 deletions python/src/docket/dependencies/_cron.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,10 @@
from __future__ import annotations

from datetime import datetime, timezone, tzinfo
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Self

from cronsim import CronSim

from ._base import current_execution
from ._perpetual import Perpetual

if TYPE_CHECKING: # pragma: no cover
Expand Down Expand Up @@ -88,11 +87,12 @@ def __init__(
self.tz = tz
self._iterator = CronSim(self.expression, datetime.now(self.tz))

async def __aenter__(self) -> Cron:
execution = current_execution.get()
cron = Cron(expression=self.expression, automatic=self.automatic, tz=self.tz)
cron.args = execution.args
cron.kwargs = execution.kwargs
async def __aenter__(self) -> Self:
cron = await super().__aenter__()
# The copy shares the declared instance's iterator, which counts from
# when the task was declared and advances on every read. Each run
# needs the next match after its own start.
cron._iterator = CronSim(self.expression, datetime.now(self.tz))
return cron

def next_time(self) -> datetime:
Expand Down
7 changes: 4 additions & 3 deletions python/src/docket/dependencies/_debounce.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@

from __future__ import annotations

import copy
import time
from datetime import timedelta
from types import TracebackType
from typing import Any
from typing import Any, Self

from .._lua import Arg, Key, redis_script
from .._redis import RedisClient
Expand Down Expand Up @@ -62,8 +63,8 @@ def __init__(self, settle: timedelta, *, scope: str | None = None) -> None:
self._argument_name: str | None = None
self._argument_value: Any = None

def bind_to_parameter(self, name: str, value: Any) -> Debounce:
bound = Debounce(self.settle, scope=self.scope)
def bind_to_parameter(self, name: str, value: Any) -> Self:
bound = copy.copy(self)
bound._argument_name = name
bound._argument_value = value
return bound
Expand Down
11 changes: 8 additions & 3 deletions python/src/docket/dependencies/_perpetual.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@

from __future__ import annotations

import copy
import logging
from datetime import datetime, timedelta, timezone
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING, Any, Self

from ._base import (
CompletionHandler,
Expand Down Expand Up @@ -85,9 +86,13 @@ def __init__(
self.cancelled = False
self._next_when = None

async def __aenter__(self) -> Perpetual:
async def __aenter__(self) -> Self:
# Each attempt gets a copy of the declared instance, so what the task
# asks of it (cancel, perpetuate, after, at) applies to that attempt
# alone. Copying keeps a subclass and its state without calling its
# constructor, whose arguments may differ from this class's.
execution = current_execution.get()
perpetual = Perpetual(every=self.every, automatic=self.automatic)
perpetual = copy.copy(self)
perpetual.args = execution.args
perpetual.kwargs = execution.kwargs
return perpetual
Expand Down
7 changes: 4 additions & 3 deletions python/src/docket/dependencies/_ratelimit.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@

from __future__ import annotations

import copy
import time
from datetime import timedelta
from types import TracebackType
from typing import Any
from typing import Any, Self

from .._lua import Arg, Key, redis_script
from .._redis import RedisClient
Expand Down Expand Up @@ -74,8 +75,8 @@ def __init__(
self._ratelimit_key: str | None = None
self._member: str | None = None

def bind_to_parameter(self, name: str, value: Any) -> RateLimit:
bound = RateLimit(self.limit, per=self.per, drop=self.drop, scope=self.scope)
def bind_to_parameter(self, name: str, value: Any) -> Self:
bound = copy.copy(self)
bound._argument_name = name
bound._argument_value = value
return bound
Expand Down
35 changes: 23 additions & 12 deletions python/src/docket/dependencies/_retry.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@

from __future__ import annotations

import copy
import logging
from datetime import datetime, timedelta, timezone
from typing import TYPE_CHECKING, NoReturn
from typing import TYPE_CHECKING, NoReturn, Self

from ._base import (
FailureHandler,
Expand All @@ -31,6 +32,14 @@ class Retry(FailureHandler["Retry"]):
"""Configures linear retries for a task. You can specify the total number of
attempts (or `None` to retry indefinitely), and the delay between attempts.

With `Perpetual` or `Cron`, the attempts apply within one run, and each run
starts again at attempt 1.

Subclasses can override `handle_failure` to decide which failures are
retried. Each attempt receives a shallow copy of the declared instance, so
state a subclass sets in its constructor is kept, and an attribute an
attempt assigns on its copy is not carried to the next attempt.

Examples:

```python
Expand Down Expand Up @@ -60,7 +69,7 @@ def __init__(
self.attempt = 1

@classmethod
def forever(cls, delay: timedelta = timedelta(0)) -> Retry:
def forever(cls, delay: timedelta = timedelta(0)) -> Self:
"""Create a retry that retries indefinitely until the task succeeds.

Example:
Expand All @@ -72,9 +81,13 @@ async def my_task(retry: Retry = Retry.forever(delay=timedelta(minutes=5))) -> N
"""
return cls(attempts=None, delay=delay)

async def __aenter__(self) -> Retry:
async def __aenter__(self) -> Self:
# Each attempt gets a copy of the retry the task declared, so a delay
# the task sets with after() or at() applies to that attempt alone.
# Copying keeps the subclass and its state without calling its
# constructor, whose arguments may differ from this class's.
execution = current_execution.get()
retry = Retry(attempts=self.attempts, delay=self.delay)
retry = copy.copy(self)
retry.attempt = execution.attempt
return retry

Expand Down Expand Up @@ -165,6 +178,9 @@ class ExponentialRetry(Retry):
of attempts (or `None` to retry indefinitely), and the minimum and maximum delays
between attempts.

With `Perpetual` or `Cron`, the attempts apply within one run, and each run
starts again at attempt 1.

Examples:

```python
Expand Down Expand Up @@ -199,7 +215,7 @@ def forever(
cls,
delay: timedelta = timedelta(seconds=1),
maximum_delay: timedelta = timedelta(seconds=64),
) -> ExponentialRetry:
) -> Self:
"""Create an exponential retry that retries indefinitely.

Args:
Expand All @@ -220,15 +236,10 @@ async def my_task(
"""
return cls(attempts=None, minimum_delay=delay, maximum_delay=maximum_delay)

async def __aenter__(self) -> ExponentialRetry:
async def __aenter__(self) -> Self:
execution = current_execution.get()

retry = ExponentialRetry(
attempts=self.attempts,
minimum_delay=self.delay,
maximum_delay=self.maximum_delay,
)
retry.attempt = execution.attempt
retry = await super().__aenter__()

if execution.attempt > 1:
exponent = execution.attempt - 1
Expand Down
10 changes: 7 additions & 3 deletions python/src/docket/dependencies/_timeout.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
from __future__ import annotations

import asyncio
import copy
import time
from datetime import timedelta
from typing import TYPE_CHECKING, Any, Awaitable, Callable
from typing import TYPE_CHECKING, Any, Awaitable, Callable, Self

if TYPE_CHECKING: # pragma: no cover
from ..execution import Execution
Expand Down Expand Up @@ -37,8 +38,11 @@ def __init__(self, base: timedelta) -> None:
"""
self.base = base

async def __aenter__(self) -> Timeout:
return Timeout(base=self.base)
async def __aenter__(self) -> Self:
# Each execution gets a copy of the declared instance, with its own
# deadline. Copying keeps a subclass and its state without calling
# its constructor, whose arguments may differ from this class's.
return copy.copy(self)

def start(self) -> None:
self._deadline = time.monotonic() + self.base.total_seconds()
Expand Down
Loading