tempest_fastapi_sdk.tasks¶
Tarefas em background sobre o TaskIQ: fila, agendador com lock e jobs persistidos.
tasks
¶
TaskIQ-backed background task primitives.
Imports the optional taskiq package lazily so the rest of the SDK
remains importable when the [tasks] extra is not installed.
TaskQueue is the recommended typed facade (tasks + scheduler folded
into one object); AsyncTaskBrokerManager / AsyncTaskScheduler are
the older lifecycle-only wrappers, kept for backward compatibility. The
cron helpers (CronEnum / CronOffsetEnum / WeekdayEnum + builder
functions) have no third-party dependency and import without the extra.
DEFAULT_POLL_SECONDS
module-attribute
¶
How often :func:run_cancellable re-reads the cancellation predicate.
Short enough that a cancel feels immediate to whoever clicked (a screen polling for status is usually on the same order), long enough that the cost is noise next to work measured in tens of seconds.
DEFAULT_HEARTBEAT_EVERY
module-attribute
¶
Default period between two heartbeats.
HEARTBEAT_FILE_MODE
module-attribute
¶
Permission bits of a written heartbeat file.
:func:tempfile.mkstemp creates 0600; a checker running as another
user on a shared volume could then not read the file and would report a
healthy process as unhealthy.
HEARTBEAT_FUTURE_TOLERANCE_SECONDS
module-attribute
¶
How far in the future a heartbeat may be and still read as fresh.
A little skew is normal when the writer and the checker read different clocks (two containers sharing a volume). Beyond this, a timestamp from the future is evidence of a broken clock or a forged file, and a file that "will be fresh" for hours would hide a dead process the whole time.
HEARTBEAT_SCHEDULE_ID
module-attribute
¶
Fixed schedule_id of the scheduler heartbeat schedule.
Fixed rather than random so the scheduler source recognises its own
schedule in pre_send and every scheduler start reuses the same id.
HEARTBEAT_TASK_NAME
module-attribute
¶
Task name carried by the scheduler heartbeat schedule.
The schedule is cancelled in pre_send every time it fires, so no
message with this name ever reaches the broker and no task by this name
is registered.
CANCELLABLE_JOB_STATUSES
module-attribute
¶
CANCELLABLE_JOB_STATUSES: frozenset[str] = frozenset(
{JobStatusEnum.QUEUED.value, JobStatusEnum.RUNNING.value}
)
Statuses with work left to stop — what :meth:JobStore.cancel accepts.
STALE_JOB_ERROR
module-attribute
¶
STALE_JOB_ERROR: str = "The worker stopped responding while this job was running, and the claim budget is spent."
error written by :meth:JobStore.reclaim_stale when it gives up.
A constant rather than a per-row message because the sweep is a single
UPDATE and interpolating each row's attempt count into it would mean
reading the rows first — the read-then-write shape this module avoids.
STORE_OWNED_JOB_COLUMNS
module-attribute
¶
STORE_OWNED_JOB_COLUMNS: frozenset[str] = frozenset(
{
"id",
"is_active",
"created_at",
"updated_at",
"kind",
"status",
"stage",
"progress",
"params",
"payload",
"result_id",
"error",
"attempts",
"max_attempts",
"started_at",
"finished_at",
}
)
Columns of :class:BaseJobModel that :meth:JobStore.succeed refuses in values.
Every column the abstract model declares — its own and the four it
inherits from :class:~tempest_fastapi_sdk.db.model.BaseModel. Each one
either is a transition the store owns (status, finished_at,
progress, payload, attempts), has a parameter of its own
(result_id), or is identity (id, kind, created_at).
values exists for the columns a project adds on its subclass, so
letting it reach these would make succeed able to write a DONE row
that says RUNNING. A test pins this set against a concrete model, so a
column added to :class:BaseJobModel fails there instead of becoming
writable by accident.
TERMINAL_JOB_STATUSES
module-attribute
¶
TERMINAL_JOB_STATUSES: frozenset[str] = frozenset(
{
JobStatusEnum.DONE.value,
JobStatusEnum.FAILED.value,
JobStatusEnum.CANCELLED.value,
}
)
Statuses a job never leaves: the poll stops, the payload is gone.
DEFAULT_LOCK_NAME
module-attribute
¶
Redis key the lease lives under, when the caller names none.
DEFAULT_LOCK_TTL_SECONDS
module-attribute
¶
How long a lease survives without renewal.
Long enough that a garbage-collection pause or a slow tick does not hand the lease to another replica, short enough that a replica killed mid-tick does not stall the schedule for minutes. The renew loop runs at a third of this, so two consecutive missed renewals still hold.
DEFAULT_RESULT_PREFIX
module-attribute
¶
Key prefix for stored task results.
RedisAsyncResultBackend._task_name writes the bare task id when no
prefix is given, which made results the only keys this SDK writes without
a namespace — tasks/lock.py, sessions/store.py, queue/dedup.py
and the response cache all carry one. Without a prefix a shared Redis
cannot even be swept for these keys, so the manual cleanup is unavailable
too.
Pass "" to restore the bare task id.
DEFAULT_RESULT_SERIALIZER
module-attribute
¶
DEFAULT_RESULT_SERIALIZER: Final[ResultSerializer] = 'json'
The result encoding used unless result_serializer= says otherwise.
DEFAULT_RESULT_TTL_SECONDS
module-attribute
¶
How long a stored task result lives, in seconds.
Ported from Celery's result_expires, whose default is
timedelta(days=1) — read from celery.app.defaults.NAMESPACES
on celery 5.6.3, not from memory.
taskiq_redis itself defaults to no expiry
(result_ex_time=None, result_px_time=None, keep_results=True),
so every execution used to leave a permanent key. Measured against Redis
8.2.9: a result for a task returning None occupies 144 bytes with
TTL -1, and a once-a-minute cron writes 1440 of them a day. On a
shared Redis running allkeys-lru that growth evicts the keys of
whoever is using Redis to work — a rate limit, an idempotency marker, the
scheduler lease — while the service paying for it may never read a result
at all.
Pass 0 to restore the unbounded behaviour deliberately.
Hook
module-attribute
¶
A lifecycle callback taking no arguments. Sync or async.
LifecycleScope
module-attribute
¶
Which process a lifecycle hook runs in.
"worker" is the taskiq worker process, "client" is whoever
calls :meth:TaskQueue.connect (typically the web application's
lifespan), "both" is either. TaskQueue.memory() runs both sides
in one process, so a worker-scoped hook fires there as well.
ResultSerializer
module-attribute
¶
How stored task results are encoded in Redis.
"json" (the default) stores data only. "pickle" is what
taskiq_redis uses on its own, and reading a pickled value runs whatever
code the stored bytes name: anyone able to write the result keys (a
co-tenant on a shared Redis, a leaked credential) gets code execution in the
process that reads the result. It stays available as an explicit opt-in for
a Redis nobody else can write.
RUNNING_STAGE_STATUSES
module-attribute
¶
RUNNING_STAGE_STATUSES: frozenset[StageStatusEnum] = frozenset(
{StageStatusEnum.PENDING, StageStatusEnum.RUNNING}
)
Statuses with work left to stop — what :meth:StageMap.cancel accepts.
PENDING counts: the message is on the queue and the worker will pick it
up, so there is something to stop even though nothing is running yet.
TERMINAL_STAGE_STATUSES
module-attribute
¶
TERMINAL_STAGE_STATUSES: frozenset[StageStatusEnum] = frozenset(
{StageStatusEnum.DONE, StageStatusEnum.FAILED, StageStatusEnum.CANCELLED}
)
Statuses a stage does not leave on its own; only an explicit restart.
StageInterruptedError
¶
Bases: Exception
The work was cancelled, or taken over, before it finished.
Nothing went wrong. Raised by :func:run_cancellable when the predicate
says to stop, after the wrapped coroutine has already been cancelled.
The handler's job is to return quietly: do not mark anything FAILED,
and do not write a partial result.
The Error suffix follows the convention rather than the meaning —
the same trade asyncio.CancelledError makes, which is also control
flow rather than a fault.
CronEnum
¶
Bases: BaseStrEnum
Ready-made cron expressions for the most common schedules.
Pass a member straight to @tq.cron(...) - it is a cron string,
so no conversion is needed. For anything parameterized (a specific
hour, weekday, day of month) use the builder functions instead.
CronOffsetEnum
¶
Bases: BaseStrEnum
Timezone offsets for cron_offset, by place instead of digits.
A cron expression is anchored to UTC unless you pass an offset. Pick
the member for your region instead of hand-writing "-03:00":
UTC-+00:00.BRASILIA--03:00(BRT; most of Brazil, incl. SP/RJ/DF).FERNANDO_DE_NORONHA--02:00.MANAUS--04:00(Amazonas / Mato Grosso).ACRE--05:00(Acre / western Amazonas).
WeekdayEnum
¶
Bases: BaseStrEnum
Day-of-week tokens for the cron day-of-week field.
Members carry the three-letter cron token ("MON" … "SUN") so
they read clearly in a schedule and drop straight into the builder
functions.
BaseDeadLetterModel
¶
Bases: BaseModel
A terminally-failed task call, persisted for inspection + requeue.
Abstract — subclass it (setting __tablename__) in the project, or build
a concrete class with :func:make_dead_letter_model. Inherits the SDK base
columns (id / is_active / created_at / updated_at);
created_at is when the failure was recorded.
from_dead_letter
classmethod
¶
from_dead_letter(dead_letter: DeadLetter) -> BaseDeadLetterModel
Build a row from a :class:DeadLetter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dead_letter
|
DeadLetter
|
The terminal failure to persist. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
BaseDeadLetterModel |
BaseDeadLetterModel
|
An unsaved row instance. |
DbDeadLetterSink
¶
DbDeadLetterSink(db: AsyncDatabaseManager, model: type[BaseDeadLetterModel])
A :class:DeadLetterSink that persists dead letters to the database.
Example:
>>> model = make_dead_letter_model()
>>> tq.dead_letter(DbDeadLetterSink(db, model))
Runs inside TaskIQ's on_error middleware, which swallows and logs any
sink exception — so a DB hiccup never crashes the worker.
Configure the sink.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db
|
AsyncDatabaseManager
|
The database manager (opens its own short transaction per dead letter). |
required |
model
|
type[BaseDeadLetterModel]
|
The concrete dead-letter table. |
required |
TaskInfo
dataclass
¶
TaskInfo(
name: str,
schedule: list[dict[str, Any]],
retry_on_error: bool,
max_retries: int | None,
)
One registered task's declared shape (for the inventory view).
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The registered task name. |
schedule |
list[dict[str, Any]]
|
The cron/interval schedule labels, or an empty list for an on-demand task. |
retry_on_error |
bool
|
Whether the task opts into retries. |
max_retries |
int | None
|
The attempt cap, when the task set one. |
HeartbeatLoop
¶
HeartbeatLoop(writer: HeartbeatWriter, every: float)
Rewrite a heartbeat file every period from inside one process.
The worker heartbeat: started on the worker's startup event and cancelled on its shutdown, so each worker process (and each replica) writes its own file, independent of what the broker delivers to it. What a fresh file proves is that the process is alive and its event loop is not blocked — a task that blocks the loop with synchronous work stops the beat. A task that awaits forever without blocking the loop does not; that is a task-timeout problem.
Attributes:
| Name | Type | Description |
|---|---|---|
writer |
HeartbeatWriter
|
Writes the file. |
every |
float
|
Seconds between two beats. |
Initialize the loop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
writer
|
HeartbeatWriter
|
Writes the file. |
required |
every
|
float
|
Seconds between two beats. |
required |
HeartbeatWriter
¶
Write a heartbeat file without ever failing the caller.
The writer runs inside the worker's heartbeat loop or the scheduler loop, where an exception would end the loop or surface in the scheduler's logs every period. A failed write is logged as a warning once, then silenced until a write succeeds again: the healthcheck reports the stale file, which is the signal an operator acts on.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
Path
|
The heartbeat file. |
Initialize the writer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
The heartbeat file. Its directory must exist when the first beat is written. |
required |
write
¶
Write the current time to :attr:path.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
write failed (already logged). |
BaseJobModel
¶
Bases: BaseModel
Abstract job table — one row per unit of long-running work.
The consuming project subclasses this and picks a __tablename__,
mirroring :class:~tempest_fastapi_sdk.db.outbox.BaseOutboxModel.
Inherits the canonical four columns from
:class:~tempest_fastapi_sdk.db.model.BaseModel (id,
is_active, created_at, updated_at), so created_at is
when the work was requested.
Attributes:
| Name | Type | Description |
|---|---|---|
kind |
str
|
Which work this is — the discriminator a worker branches on and a filter the interface offers. Indexed. |
status |
str
|
One of :class: |
params |
dict[str, Any]
|
Small input, as JSON. What fits in a message. |
payload |
bytes | None
|
Large input — the uploaded document a broker has no business carrying. Dropped when the job reaches a terminal state. |
result_id |
UUID | None
|
The row the work produced, so the interface can navigate to it without a second lookup table. |
error |
str | None
|
Why it stopped, written for the user rather than as a traceback. |
attempts |
int
|
How many times the job was claimed. Incremented
by :meth: |
max_attempts |
int
|
Claim budget. :meth: |
started_at |
datetime | None
|
When the current attempt was
claimed; |
finished_at |
datetime | None
|
When it reached |
stage |
str
|
Which part of the work is running, as the work names it. Free text, because only the work knows its own parts. |
progress |
float
|
How much of the work is done, |
is_terminal
property
¶
Whether the job will never change status again.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
new_job
classmethod
¶
new_job(
kind: str,
*,
params: dict[str, Any] | None = None,
payload: bytes | None = None,
max_attempts: int = 3,
) -> Self
Build a fresh queued job row.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kind
|
str
|
Which work this is. |
required |
params
|
dict[str, Any] | None
|
Small JSON input. |
None
|
payload
|
bytes | None
|
Large binary input. |
None
|
max_attempts
|
int
|
Claim budget. Defaults to |
3
|
Returns:
| Name | Type | Description |
|---|---|---|
Self |
Self
|
A new |
JobAlreadyFinishedError
¶
Bases: RuntimeError
Raised when finishing a job that already reached a terminal state.
Surfaced rather than swallowed: a second succeed or fail on
the same row means two workers believe they own the job, or one
worker ran the same job twice. Silently overwriting the first
outcome would erase the evidence.
JobCancelledError
¶
Bases: JobAlreadyFinishedError
Raised when finishing a job the user cancelled meanwhile.
A subclass so existing except JobAlreadyFinishedError keeps
working, and a separate type because the two mean opposite things: a
plain JobAlreadyFinishedError says something is wrong with your
concurrency, while this one says the system did exactly what it was
told. A worker that races past its last cancellation checkpoint and
calls succeed should log this and move on, not alert.
The write is refused either way — a cancelled job never gets a result written over it.
JobNotFoundError
¶
Bases: LookupError
Raised when a job id matches no row.
A LookupError rather than an
:class:~tempest_fastapi_sdk.exceptions.AppException because the
store runs in the worker as often as in a request, and a worker has
no HTTP status to answer with. Map it at the boundary — a route that
exposes job status can raise its own 404 from
:func:~tempest_fastapi_sdk.not_found_exception.
JobStatusEnum
¶
Bases: StrEnum
Lifecycle of a unit of long-running work.
QUEUED— the row exists, nobody has picked it up.RUNNING— a worker claimed it (see :meth:JobStore.claim).DONE— finished;result_idpoints at what it produced.FAILED— stopped;errorsays why, in the user's language.CANCELLED— the user asked it to stop (see :meth:JobStore.cancel). Terminal like the two above, but not a failure: nothing went wrong, so an interface that highlightsFAILEDshould leave this one alone, and an alert that pages on failures should not fire.
JobStore
¶
JobStore(
db: AsyncDatabaseManager,
*,
model: type[JobT],
stale_after: float | timedelta | None = None,
)
Bases: Generic[JobT]
Enqueue, claim and close jobs — one short transaction per call.
The store takes the :class:~tempest_fastapi_sdk.db.AsyncDatabaseManager
rather than a session on purpose. Its callers are a request handler
that enqueues, a worker that claims and closes, and a UI poll that
asks every couple of seconds; none of them should hold a session
across the long work in between — on SQLite that is exactly the
read-then-write transaction no busy timeout can rescue.
Example
store = JobStore(db, model=JobModel, stale_after=300.0) job = await store.enqueue("extract", payload=pdf_bytes) await extract_task.enqueue(str(job.id))
in the worker¶
claimed = await store.claim(job_id) if claimed is not None: ... await store.succeed(job_id, result_id=draft.id)
Attributes:
| Name | Type | Description |
|---|---|---|
stale_after |
timedelta | None
|
How long a job may stay
|
Initialize the store.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db
|
AsyncDatabaseManager
|
The database manager; the store opens its own session per call. |
required |
model
|
type[JobT]
|
The concrete job model. |
required |
stale_after
|
float | timedelta | None
|
Seconds (or a
|
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
enqueue
async
¶
enqueue(
kind: str,
*,
params: dict[str, Any] | None = None,
payload: bytes | None = None,
max_attempts: int = 3,
) -> JobT
Record a unit of work as QUEUED.
Enqueueing the row and enqueueing the task are two steps on purpose: the row is what the interface reads, and it must exist before the worker can claim it. Write the row first, then send the task its id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kind
|
str
|
Which work this is. |
required |
params
|
dict[str, Any] | None
|
Small JSON input. |
None
|
payload
|
bytes | None
|
Large binary input — the file a broker should not be carrying. |
None
|
max_attempts
|
int
|
Claim budget. Defaults to |
3
|
Returns:
| Name | Type | Description |
|---|---|---|
JobT |
JobT
|
The persisted, queued job. |
get
async
¶
Return one job.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_id
|
UUID
|
The job to read. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
JobT |
JobT
|
The job row, payload included. |
Raises:
| Type | Description |
|---|---|
JobNotFoundError
|
When no row has that id. |
claim
async
¶
Move a queued job to RUNNING and return it.
The transition is a single conditional UPDATE, so two
workers racing for the same id cannot both win: exactly one sees
a row change, the other gets None.
None means "not yours to run" and covers both a job someone
else already claimed and an id that does not exist — which is
what a competing worker should do either way. Call :meth:get
when the difference matters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_id
|
UUID
|
The job to claim. |
required |
Returns:
| Type | Description |
|---|---|
JobT | None
|
JobT | None: The claimed job, payload included, or |
JobT | None
|
when it was not claimable. |
report_progress
async
¶
Move a running job's progress bar forward.
One conditional UPDATE, no read first — the same shape as
:meth:claim, and for the same reason: a tick that reads the row
and writes it back is a lock promotion, which on SQLite fails
outright against the interface writing at the same moment.
The bar cannot go backwards. The progress < clause is in
the statement rather than in the caller, because the caller is
exactly who cannot enforce it: two ticks can be in flight at once,
and the one that arrives second is not the one that measured
second. A refused write is not an error — it is the row already
being further along than this tick believed.
A job that is not RUNNING is not written either. Progress on a
cancelled job would repaint a bar the user already stopped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_id
|
UUID
|
The job to advance. |
required |
progress
|
float
|
Completed fraction, clamped to |
required |
stage
|
str | None
|
Which part of the work is running.
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
Whether the row moved — |
bool
|
longer running, or was already further along. |
succeed
async
¶
succeed(
job_id: UUID,
*,
result_id: UUID | None = None,
values: Mapping[str, Any] | None = None,
) -> JobT
Close a job as DONE.
The payload is dropped here: a table of finished jobs that still carries every uploaded document is a table that outgrows the data it was serving.
values writes the columns a project added to its job model —
the object_key of the file the work generated, say — in the
same conditional UPDATE that sets DONE. Writing them
from a session of your own before calling succeed is two
transactions, and between them the row is RUNNING with the
key already set: a cancel landing there makes succeed raise
:class:JobCancelledError and leaves a cancelled row pointing at
a file the worker is about to delete. Here a cancelled job gets
nothing, because the statement that would write the values is the
one the cancellation refuses.
Example
await store.succeed(job_id, values={"object_key": key})
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_id
|
UUID
|
The job to close. |
required |
result_id
|
UUID | None
|
The row the work produced, so the interface can link straight to it. |
None
|
values
|
Mapping[str, Any] | None
|
Project columns to write with the transition, keyed by attribute name. Validated before any SQL runs. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
JobT |
JobT
|
The finished job. |
Raises:
| Type | Description |
|---|---|
JobNotFoundError
|
When no row has that id. |
JobAlreadyFinishedError
|
When the job is already terminal. |
JobCancelledError
|
When the job was cancelled; |
ValueError
|
When |
fail
async
¶
Close a job as FAILED.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_id
|
UUID
|
The job to close. |
required |
reason
|
str
|
Why it stopped, written for the person who will read it on a screen — not a traceback. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
JobT |
JobT
|
The failed job. |
Raises:
| Type | Description |
|---|---|
JobNotFoundError
|
When no row has that id. |
JobAlreadyFinishedError
|
When the job is already terminal. |
cancel
async
¶
Ask a queued or running job to stop.
This writes CANCELLED and returns; it does not reach into
the worker. There is no portable way to kill a coroutine running in
another process, so cancellation is cooperative: the worker reads
this status at checkpoints and gives up
(:func:~tempest_fastapi_sdk.tasks.run_cancellable). The screen can
therefore reflect the cancellation immediately, while the work
behind it takes a few seconds more to actually stop.
Idempotent. Cancelling something that is not running answers
None rather than raising — a user double-clicking, or clicking
just as the job finished on its own, is not an error. That makes
None mean "there was nothing to stop", covering an unknown id,
a job already done, already failed, or already cancelled.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_id
|
UUID
|
The job to cancel. |
required |
reason
|
str | None
|
Stored in |
None
|
Returns:
| Type | Description |
|---|---|
JobT | None
|
JobT | None: The cancelled job, or |
JobT | None
|
cancellable. |
is_cancelled
async
¶
Has this job been cancelled?
Reads in a fresh session on purpose. The worker's own session is inside a transaction that started before the cancel was committed, so asking it would serve the pre-cancel snapshot — the exact opposite of what a checkpoint needs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_id
|
UUID
|
The job to check. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
longer exists answers |
|
bool
|
produce a result for, so stopping is the right move. |
cancellation_watch
¶
Build the predicate :func:run_cancellable polls.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_id
|
UUID
|
The job to watch. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Callable[[], Awaitable[bool]]
|
Callable[[], Awaitable[bool]]: A no-argument coroutine |
|
answering |
Callable[[], Awaitable[bool]]
|
meth: |
Example:
>>> await run_cancellable(
... transcribe(audio),
... interrupted=store.cancellation_watch(job.id),
... )
list_recent
async
¶
list_recent(
*,
kind: str | None = None,
status: JobStatusEnum | str | None = None,
statuses: Sequence[JobStatusEnum | str] | None = None,
limit: int = 20,
) -> list[JobT]
Return the most recently requested jobs, newest first.
Returns an empty list when nothing matches — "no jobs yet" is a successful answer, not a 404.
statuses is what a screen showing work in flight actually
needs: "queued or running" is one question, and asking it as two
queries makes the two halves disagree the moment a worker claims a
job between them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kind
|
str | None
|
Restrict to one kind of work. |
None
|
status
|
JobStatusEnum | str | None
|
Restrict to one status. |
None
|
statuses
|
Sequence[JobStatusEnum | str] | None
|
Restrict to any of several statuses. |
None
|
limit
|
int
|
Maximum rows. Defaults to |
20
|
Returns:
| Type | Description |
|---|---|
list[JobT]
|
list[JobT]: The matching jobs, newest first. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
reclaim_stale
async
¶
reclaim_stale() -> ReclaimedJobs
Readmit jobs whose worker died holding them.
A RUNNING row nobody will ever finish is the failure mode a
queue cannot see: the task is gone, the row is not. Rows whose
started_at is older than :attr:stale_after go back to
QUEUED — unless they already spent their max_attempts,
in which case they are closed as FAILED, because a job that
kills its worker would otherwise be readmitted forever.
Two conditional UPDATE ... RETURNING id statements over
disjoint conditions, deliberately with no SELECT first: a
sweep that reads the rows and then writes them is a lock
promotion, which on SQLite fails outright against a concurrent
writer — measured, and the reason busy_timeout cannot help
there (see :func:~tempest_fastapi_sdk.enable_sqlite_wal). The
cost is that the give-up message names the budget rather than the
row's own attempt count. RETURNING needs SQLite 3.35+ or
PostgreSQL.
A requeued row is not sent to a worker by this method: its message died with the worker. Dispatch the returned ids::
reclaimed = await store.reclaim_stale()
for job_id in reclaimed.requeued:
await extract_task.enqueue(str(job_id))
or let :meth:redispatch_queued find them on a later sweep.
Returns:
| Name | Type | Description |
|---|---|---|
ReclaimedJobs |
ReclaimedJobs
|
The ids requeued and the ids given up on. Its |
ReclaimedJobs
|
|
|
needs |
ReclaimedJobs
|
attr: |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When the store was built without
|
redispatch_queued
async
¶
redispatch_queued(
dispatch: Callable[[JobT], Awaitable[None]],
*,
older_than: float | timedelta,
limit: int = 100,
) -> list[UUID]
Send QUEUED rows nobody touched for a while back to a worker.
The documented flow writes the row and then sends its id to the
queue — two steps, and the second can be lost: the broker was
down, the process died between them, or :meth:reclaim_stale
requeued a row whose message died with its worker. Either way the
row is QUEUED and nothing will ever claim it. This sweep is
meant to run as a scheduled task::
async def _send(job: JobModel) -> None:
await extract_task.enqueue(str(job.id))
@tq.interval(timedelta(minutes=5))
async def redispatch() -> None:
await store.redispatch_queued(_send, older_than=600.0)
Sending twice is harmless. A row whose message is merely
waiting in a long backlog is sent again, and both messages reach
:meth:claim; its conditional UPDATE lets exactly one of them
run the job and answers None to the other. Pick older_than
above the backlog you expect so that stays rare, not to keep it
correct.
Age is updated_at, not created_at: every write to the row
refreshes it, and this method refreshes it after each dispatch, so
a row is resent at most once per older_than rather than on
every sweep. No session is held while dispatch runs — the
candidate read is its own short transaction, and the refresh is a
conditional UPDATE that skips a row a worker claimed in the
meantime.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dispatch
|
Callable[[JobT], Awaitable[None]]
|
Sends one job to a
worker — typically |
required |
older_than
|
float | timedelta
|
Seconds (or a |
required |
limit
|
int
|
Most rows resent per call, oldest first. Defaults
to |
100
|
Returns:
| Type | Description |
|---|---|
list[UUID]
|
list[UUID]: The ids handed to |
list[UUID]
|
Empty when nothing was waiting. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
Exception
|
Whatever |
watch
async
¶
watch(
job_id: UUID,
*,
interval: float = 2.0,
timeout: float | None = None,
emit_on: Sequence[str] = ("status",),
) -> AsyncIterator[JobT]
Yield the job whenever a watched field changes, until it is terminal.
This replaces the while True: sleep; get every application
writes by hand — including the part that is easy to get wrong:
no session is held between ticks. Each poll opens and closes
its own, so a worker writing to the same database is never
blocked by the screen watching it.
The current state is yielded immediately, so a caller that subscribes after the job already finished still gets exactly one value and the loop ends.
emit_on is what makes this usable for a progress bar. Watching
only the status yields three times for a whole reading — claimed,
finished, and nothing in between — so a screen driven by it shows a
bar that never moves. Add "progress" and every tick the worker
wrote comes through.
Example
async for job in store.watch( ... job_id, ... interval=2.0, ... emit_on=("status", "progress", "stage"), ... ): ... await session.render(job.status, job.progress)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_id
|
UUID
|
The job to follow. |
required |
interval
|
float
|
Seconds between polls. Defaults to |
2.0
|
timeout
|
float | None
|
Give up after this many seconds.
|
None
|
emit_on
|
Sequence[str]
|
Column names whose change triggers a
yield. Defaults to |
('status',)
|
Yields:
| Name | Type | Description |
|---|---|---|
JobT |
AsyncIterator[JobT]
|
The job, each time one of the watched fields differs |
AsyncIterator[JobT]
|
from the last value yielded. |
Raises:
| Type | Description |
|---|---|
JobNotFoundError
|
When no row has that id. |
TimeoutError
|
When |
ValueError
|
If |
ReclaimedJobs
dataclass
¶
What :meth:JobStore.reclaim_stale did, row by row.
The ids are what make the sweep useful. A requeued row is QUEUED
again, but its message is gone with the worker that died — nothing
sends it to a worker until somebody calls task.enqueue(str(id))
for it, and the old int return gave the caller nothing to call
it with.
len() and truthiness count both lists, so if await
store.reclaim_stale(): reads as it did when the method returned an
int. Comparing with a number (== 1) or adding to one does not:
use :attr:total.
Attributes:
| Name | Type | Description |
|---|---|---|
requeued |
list[UUID]
|
Rows moved back to |
failed |
list[UUID]
|
Rows closed as |
total
property
¶
Return how many rows left RUNNING.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
|
RedisLockClient
¶
Bases: Protocol
The one method :class:RedisSchedulerLock needs from a client.
redis.asyncio.Redis satisfies this, and so does fakeredis's
async client — which is what the suite runs against, since a lock is
only worth testing where two holders can actually contend.
lock
¶
lock(
name: str, /, *, timeout: float | None = ..., blocking: bool = ...
) -> RedisLockHandle
Build a lock object for one key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The Redis key the lock lives under. |
required |
timeout
|
float | None
|
Lease TTL in seconds. |
...
|
blocking
|
bool
|
Whether |
...
|
Returns:
| Name | Type | Description |
|---|---|---|
RedisLockHandle |
RedisLockHandle
|
The lock, not yet acquired. |
RedisLockHandle
¶
Bases: Protocol
The lock object redis-py returns from Redis.lock.
Written positional-only for the required argument on purpose: mypy accepts a parameter-name mismatch in protocol compatibility and basedpyright rejects it, and the implementer here is a library whose parameter names are not ours to keep in sync.
acquire
¶
Take the lock.
Returns:
| Type | Description |
|---|---|
Awaitable[bool]
|
Awaitable[bool]: Whether the lock was taken. |
extend
¶
Push the expiry out, verifying ownership first.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
additional_time
|
float
|
Seconds to add, or to set when
|
required |
replace_ttl
|
bool
|
Replace the remaining TTL rather than adding to it, so a long-lived leader's lease does not grow without bound. |
...
|
Returns:
| Type | Description |
|---|---|
Awaitable[bool]
|
Awaitable[bool]: Whether the extension applied. |
release
¶
Delete the key, verifying ownership first.
Returns:
| Type | Description |
|---|---|
Awaitable[None]
|
Awaitable[None]: Completes once the key is gone. |
RedisSchedulerLock
¶
RedisSchedulerLock(
client: RedisLockClient,
*,
name: str = DEFAULT_LOCK_NAME,
ttl_seconds: float = DEFAULT_LOCK_TTL_SECONDS,
)
A :class:SchedulerLock over the lock redis-py ships.
Example:
>>> import redis.asyncio as redis
>>> from tempest_fastapi_sdk.tasks import RedisSchedulerLock
>>>
>>> lock: RedisSchedulerLock = RedisSchedulerLock(
... redis.Redis.from_url("redis://localhost:6379/0"),
... )
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The Redis key the lease lives under. |
ttl_seconds |
float
|
How long the lease survives unrenewed. |
Wrap a Redis client as a scheduler lease.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
RedisLockClient
|
An async Redis client. Anything
with |
required |
name
|
str
|
The key to lock. Give two services sharing one Redis instance different names, or one of them will never schedule. |
DEFAULT_LOCK_NAME
|
ttl_seconds
|
float
|
Lease duration. See
:data: |
DEFAULT_LOCK_TTL_SECONDS
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
from_url
classmethod
¶
from_url(
url: str,
*,
name: str = DEFAULT_LOCK_NAME,
ttl_seconds: float = DEFAULT_LOCK_TTL_SECONDS,
) -> RedisSchedulerLock
Build the lease from a Redis URL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
A |
required |
name
|
str
|
The key to lock. |
DEFAULT_LOCK_NAME
|
ttl_seconds
|
float
|
Lease duration. |
DEFAULT_LOCK_TTL_SECONDS
|
Returns:
| Name | Type | Description |
|---|---|---|
RedisSchedulerLock |
RedisSchedulerLock
|
The lease, over a client of its own. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When |
acquire
async
¶
Try to take the lease without waiting.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
Whether this process now holds it. |
renew
async
¶
Extend the lease this process holds.
replace_ttl is set, so the lease is pushed to a fixed
ttl_seconds from now rather than accumulating: a leader up
for a week would otherwise hold a week-long lease, and its death
would stop the schedule until that ran out.
A renewal that fails because the transport failed is indistinguishable, from here, from one that fails because another replica took the lease. Standing down is the safe direction in both: a gap of at most one TTL costs a late tick, while guessing the other way runs two schedulers. The key is released on the way out, so a lease this process still owned goes back immediately instead of waiting out the TTL.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
Whether the lease is still held afterwards. |
bool
|
once it has been lost, and it stays |
release
async
¶
Give up the lease if it is still held.
A failure here is logged and swallowed: this runs on shutdown,
and raising would replace whatever actually stopped the process.
The lease expires on its own within ttl_seconds anyway.
SchedulerLock
¶
Bases: Protocol
The three calls leader election needs from a lease.
A service with its own coordination — etcd, ZooKeeper, a Postgres
advisory lock — implements this and passes it to
:meth:~tempest_fastapi_sdk.tasks.TaskQueue.lifespan; nothing here
knows about Redis.
Every method is a coroutine because acquiring a lease is I/O in every implementation worth having.
acquire
async
¶
Try to take the lease without waiting.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
when another one does. Must not block: a replica that |
|
bool
|
waited here would delay its own startup behind the leader's |
|
bool
|
entire lifetime. |
renew
async
¶
Extend a lease this process already holds.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
it was lost — expired, or taken over. |
|
bool
|
the scheduler loop: a lost lease means another replica is |
|
bool
|
already running it. |
release
async
¶
Give up the lease, if this process still holds it.
Releasing on shutdown is what lets another replica take over in seconds instead of after the TTL. Must tolerate being called when the lease was never acquired or was already lost.
AsyncTaskBrokerManager
¶
Manage the lifecycle of a TaskIQ broker.
Wraps any TaskIQ broker (AioPikaBroker for RabbitMQ, RedisBroker,
InMemoryBroker for tests, etc.) with a uniform startup / shutdown
surface that matches the SDK's other backends and exposes the
task decorator so application code never imports the broker
directly.
The broker is injected so consumers stay free to choose the transport without forcing TaskIQ to import every backend.
Typical usage::
from taskiq_aio_pika import AioPikaBroker
from tempest_fastapi_sdk import AsyncTaskBrokerManager
broker = AioPikaBroker("amqp://guest:guest@localhost:5672/")
tasks = AsyncTaskBrokerManager(broker)
@tasks.task
async def send_email(to: str) -> None:
...
# FastAPI lifespan
await tasks.connect()
...
await tasks.disconnect()
# enqueue from a request handler
await send_email.kiq("user@example.com")
Attributes:
| Name | Type | Description |
|---|---|---|
broker |
AsyncBroker
|
The wrapped broker instance. |
Initialize the manager.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
broker
|
AsyncBroker
|
A TaskIQ broker instance. |
required |
is_connected
property
¶
Return True once :meth:connect succeeded.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
connect
async
¶
Start the broker so tasks can be enqueued and processed.
Safe to call multiple times — subsequent calls are no-ops while the same broker is alive.
task
¶
task(
task_name: Callable[_P, _R] | str | None = None, **labels: Any
) -> (
AsyncTaskiqDecoratedTask[_P, _R]
| Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]
)
Forward to broker.task so callers don't import TaskIQ.
Can be used as either @manager.task or
@manager.task(task_name="..."). Both forms mirror the overloads
of AsyncBroker.task, so the decorated name keeps the
function's parameters and return type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_name
|
Callable[_P, _R] | str | None
|
The function itself
(bare |
None
|
**labels
|
Any
|
TaskIQ labels forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
AsyncTaskiqDecoratedTask[_P, _R] | Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]
|
AsyncTaskiqDecoratedTask[_P, _R] | Callable[[Callable[_P, _R]], |
AsyncTaskiqDecoratedTask[_P, _R] | Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]
|
AsyncTaskiqDecoratedTask[_P, _R]]: The decorated task (bare |
AsyncTaskiqDecoratedTask[_P, _R] | Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]
|
form), or the decorator that produces one. |
register_task
¶
register_task(
func: Callable[_P, _R], *, task_name: str | None = None, **kwargs: Any
) -> AsyncTaskiqDecoratedTask[_P, _R]
Register func as a task without using decorator syntax.
Useful when wiring third-party callables that you can't decorate at definition time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable[_P, _R]
|
The async callable to register. |
required |
task_name
|
str | None
|
Override the task name. Defaults to
TaskIQ's auto-generated |
None
|
**kwargs
|
Any
|
Extra keyword arguments forwarded to
|
{}
|
Returns:
| Type | Description |
|---|---|
AsyncTaskiqDecoratedTask[_P, _R]
|
AsyncTaskiqDecoratedTask[_P, _R]: The registered task, |
AsyncTaskiqDecoratedTask[_P, _R]
|
preserving |
lifespan
async
¶
Yield the broker inside an async with block.
Connects on entry, disconnects on exit.
Yields:
| Name | Type | Description |
|---|---|---|
AsyncBroker |
AsyncGenerator[AsyncBroker, None]
|
The connected broker. |
broker_dependency
async
¶
Async generator dependency suitable for FastAPI Depends.
Yields:
| Name | Type | Description |
|---|---|---|
AsyncBroker |
AsyncIterator[AsyncBroker]
|
The connected broker. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When :meth: |
health_check
async
¶
Return True when the broker is started.
TaskIQ brokers don't expose a generic ping, so we only report whether the startup handshake completed.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
DeadLetter
dataclass
¶
DeadLetter(
task_name: str,
task_id: str,
exception: BaseException,
retries: int,
args: list[Any] = list(),
kwargs: dict[str, Any] = dict(),
)
A task call that failed terminally, handed to a :class:DeadLetterSink.
Attributes:
| Name | Type | Description |
|---|---|---|
task_name |
str
|
The registered task name. |
task_id |
str
|
The failed invocation's id. |
args |
list[Any]
|
Positional arguments of the failed call. |
kwargs |
dict[str, Any]
|
Keyword arguments of the failed call. |
exception |
BaseException
|
The exception that ended the last attempt. |
retries |
int
|
Number of attempts made before giving up. |
DeadLetterSink
¶
Bases: Protocol
Where terminally-failed tasks go.
Implement this to route dead letters wherever you want — a
:class:~tempest_fastapi_sdk.queue.MessageBroker channel, a database
table, a log line, an alert. The sink is called at most once per task
invocation, only after retries (if any) are exhausted.
The parameter is positional-only, so a plain function works whatever
it names it — async def sink(letter: DeadLetter) -> None is a
DeadLetterSink. Both checkers compare parameter names when matching
a function against a callback protocol; with a named parameter mypy and
basedpyright rejected every sink not spelled dead_letter.
RetryPolicy
dataclass
¶
Typed retry configuration for a background task.
Attributes:
| Name | Type | Description |
|---|---|---|
max_retries |
int
|
Total attempts before the task is given up on
(matches TaskIQ's |
on_error |
bool
|
Whether the task is retried on failure at all. |
as_labels
¶
Render this policy as the TaskIQ labels the retry middleware reads.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: |
TaskMetrics
¶
Prometheus run count + duration histogram for background tasks.
Example:
>>> from tempest_fastapi_sdk.tasks import TaskMetrics, TaskQueue
>>> tq = TaskQueue.rabbitmq("amqp://guest:guest@localhost/")
>>> tq.enable_metrics(TaskMetrics())
Attributes:
| Name | Type | Description |
|---|---|---|
namespace |
str
|
Metric name prefix. |
Build the metric objects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace
|
str
|
Prefix for every metric name. |
'tasks'
|
registry
|
Any
|
A |
None
|
record
¶
Record one completed task execution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task
|
str
|
The task name label. |
required |
status
|
str
|
|
required |
duration_seconds
|
float
|
Wall-clock execution time. |
required |
middleware
¶
Build the TaskIQ middleware that records this bundle.
Returns:
| Name | Type | Description |
|---|---|---|
TaskiqMiddleware |
TaskiqMiddleware
|
The middleware instance (needs the |
TaskiqMiddleware
|
extra). |
TaskBinding
dataclass
¶
TaskBinding(
key: str,
func: Callable[..., Awaitable[Any]],
name: str | None,
options: dict[str, Any] = dict(),
retry: RetryPolicy | None = None,
)
One task registration produced by a :class:TaskDef.
Attributes:
| Name | Type | Description |
|---|---|---|
key |
str
|
A stable key (the method name, or |
func |
Callable[..., Awaitable[Any]]
|
The async callable to run. |
name |
str | None
|
Explicit task name override, or |
options |
dict[str, Any]
|
Extra TaskIQ labels / options. |
retry |
RetryPolicy | None
|
Retry configuration, kept apart from
:attr: |
TaskDef
¶
TaskDef(*, name: str | None = None, retry: RetryPolicy | None = None, **options: Any)
Bases: Generic[TaskReturnT]
Base class for class-based background tasks.
Subclass it in either style from the module docstring. Register an
instance with :meth:~tempest_fastapi_sdk.tasks.TaskQueue.register,
which returns a single Task (constructor form) or a
dict[str, Task] keyed by method name (grouped form).
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str | None
|
Task name for the constructor form; |
retry |
RetryPolicy | None
|
Retry configuration for every task
this definition declares. A :func: |
options |
dict[str, Any]
|
Extra TaskIQ labels for the constructor form. Never mutated, so the empty class-level default is safe to share. |
Configure the constructor form.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str | None
|
Override the task name. Omit in the grouped
( |
None
|
retry
|
RetryPolicy | None
|
Retry configuration, the same
keyword |
None
|
**options
|
Any
|
Extra TaskIQ labels / options for the
constructor form. The grouped form takes its own on each
:func: |
{}
|
is_grouped
property
¶
Return True when this uses the grouped @task_method form.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
run
async
¶
Run the task — override in the constructor form.
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
When neither |
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args
|
Any
|
Positional arguments forwarded to the task. |
()
|
**kwargs
|
Any
|
Keyword arguments forwarded to the task. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
TaskReturnT |
TaskReturnT
|
Whatever the wrapped task returns. |
task_bindings
¶
task_bindings() -> list[TaskBinding]
Return every task this definition declares.
Grouped @task_method methods take precedence; if none are
present, the constructor form (run + name) is used. A
binding with no retry of its own inherits :attr:retry.
Returns:
| Type | Description |
|---|---|
list[TaskBinding]
|
list[TaskBinding]: One entry per task. |
Phase
dataclass
¶
One measured step of a longer job.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
What the step is called, as the interface will show it and as the row will record it. |
weight |
float
|
How much of the whole job this step accounts for, relative to the other phases. Measured seconds are the natural value; they are normalised, so any scale works. |
seconds |
float
|
How long the step usually takes — the median of
real runs. |
seconds_per_kilochar |
float
|
How much each thousand characters
of input adds, when the caller passes |
PhasePlan
¶
PhasePlan(phases: Sequence[Phase], *, ceiling_margin: float = 0.95)
Measured phases, turned into the fraction to write on the row.
Attributes:
| Name | Type | Description |
|---|---|---|
ceiling_margin |
float
|
How far into a phase's span the interpolation is allowed to climb before the phase actually ends. |
Build a plan from measured phases.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
phases
|
Sequence[Phase]
|
The steps, in the order they run. |
required |
ceiling_margin
|
float
|
Fraction of a phase's span the
interpolation may reach. Defaults to |
0.95
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When there are no phases, a name repeats, a
weight is not positive, or |
names
property
¶
The phase names, in order.
Returns:
| Type | Description |
|---|---|
tuple[str, ...]
|
tuple[str, ...]: The names this plan knows. |
from_seconds
classmethod
¶
from_seconds(
medians: Mapping[str, float],
*,
per_kilochar: Mapping[str, float] | None = None,
ceiling_margin: float = 0.95,
) -> PhasePlan
Build a plan straight out of a measurement run.
The median duration is both the weight and the expected duration, which is what a measurement gives you without further arithmetic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
medians
|
Mapping[str, float]
|
Median seconds per phase, in the order the phases run. |
required |
per_kilochar
|
Mapping[str, float] | None
|
Fitted seconds per thousand characters, for the phases that have one. |
None
|
ceiling_margin
|
float
|
Passed through to the constructor. |
0.95
|
Returns:
| Name | Type | Description |
|---|---|---|
PhasePlan |
PhasePlan
|
The plan. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When a median is not positive — a phase that takes no time is not a phase to show. |
bounds
¶
Where a phase starts and ends on the bar.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
phase
|
str
|
The phase name. |
required |
Returns:
| Type | Description |
|---|---|
float
|
tuple[float, float]: Its floor and ceiling, both in |
float
|
|
Raises:
| Type | Description |
|---|---|
KeyError
|
When the plan has no such phase. |
expected
¶
How long this phase should take, given its input.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
phase
|
str
|
The phase name. |
required |
size
|
float | None
|
Input size in characters, when the phase was fitted against it. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
Expected seconds, |
float
|
measured. |
Raises:
| Type | Description |
|---|---|
KeyError
|
When the plan has no such phase. |
fraction
¶
fraction(
phase: str,
*,
elapsed: float = 0.0,
size: float | None = None,
done: float | None = None,
) -> float
The number to write on the row right now.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
phase
|
str
|
The phase that is running. |
required |
elapsed
|
float
|
Seconds since the phase started. |
0.0
|
size
|
float | None
|
Input size in characters, when known. |
None
|
done
|
float | None
|
A real fraction of this phase, from a counter the work actually has — pages read out of pages total. Given, it wins: a measured count beats an interpolation, and it is allowed to reach the phase ceiling because it is not a guess. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The completed fraction of the whole job, in |
float
|
|
Raises:
| Type | Description |
|---|---|
KeyError
|
When the plan has no such phase. |
ProgressSink
¶
Bases: Protocol
The two things a tracker needs from a job store.
Narrow on purpose: a tracker asks the row how far along it is allowed to say the work is, and whether the user stopped it. Anything that answers those two questions can be tracked, which is what keeps the tests here free of a database.
report_progress
async
¶
Move the recorded progress forward.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_id
|
UUID
|
The job to advance. |
required |
progress
|
float
|
Completed fraction. |
required |
stage
|
str | None
|
Which part of the work is running. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
Whether the row moved. |
is_cancelled
async
¶
Answer whether the user stopped this job.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_id
|
UUID
|
The job to check. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
ProgressTracker
¶
ProgressTracker(
sink: ProgressSink,
job_id: UUID,
*,
plan: PhasePlan,
interval: float = DEFAULT_POLL_SECONDS,
clock: Callable[[], float] = monotonic,
)
Runs a job's phases, writing where each one has got to.
Attributes:
| Name | Type | Description |
|---|---|---|
plan |
PhasePlan
|
The measured phases being followed. |
interval |
float
|
Seconds between ticks — each tick writes the interpolated progress and asks whether the job was cancelled. |
Bind a tracker to one job.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sink
|
ProgressSink
|
Where progress is written and
cancellation is read — normally a
:class: |
required |
job_id
|
UUID
|
The job being tracked. |
required |
plan
|
PhasePlan
|
The measured phases. |
required |
interval
|
float
|
Seconds between ticks. |
DEFAULT_POLL_SECONDS
|
clock
|
Callable[[], float]
|
Monotonic seconds source; injectable so a test does not have to wait. |
monotonic
|
enter
async
¶
Announce a phase without running anything in it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
phase
|
str
|
The phase starting now. |
required |
report
async
¶
Write a phase's own count of how far it has got.
For work that can actually count — pages extracted, rows written — this beats interpolation and is what the bar should show.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
phase
|
str
|
The phase that is running. |
required |
done
|
float
|
Its completed fraction, |
required |
run
async
¶
run(
phase: str,
work: Awaitable[ResultT],
*,
size: float | None = None,
stop_event: Event | None = None,
) -> ResultT
Run one phase, ticking the bar and honouring cancellation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
phase
|
str
|
The phase this work is. |
required |
work
|
Awaitable[ResultT]
|
The work itself. It must be
genuinely cancellable — async I/O, not a thread wrapper,
for the reason
:func: |
required |
size
|
float | None
|
Input size in characters, when the phase was fitted against it. With it, a call over 40.000 characters is not paced like one over 4.000. |
None
|
stop_event
|
Event | None
|
Forwarded to
:func: |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
ResultT |
ResultT
|
Whatever |
Raises:
| Type | Description |
|---|---|
StageInterruptedError
|
The job was cancelled while this phase
was running; |
KeyError
|
When the plan has no such phase. |
Exception
|
Anything |
LifecycleResource
¶
Bases: Protocol
Anything the queue can open on startup and close on shutdown.
:class:~tempest_fastapi_sdk.db.AsyncDatabaseManager,
:class:~tempest_fastapi_sdk.queue.MessageBroker and
:class:~tempest_fastapi_sdk.storage.AsyncMinIOClient all satisfy
it, which is what makes resources=[db, broker] work without the
SDK naming any of them.
Task
¶
Bases: Generic[P, R]
A background-runnable function — the result of :meth:TaskQueue.task.
Wraps a TaskIQ task so the two things you actually do read clearly and stay typed against the original signature:
await my_task.enqueue(...)— hand the call to a worker and return immediately (the worker runs it out-of-process).await my_task.run(...)— run the body right here, in-process, returning its real value. Handy in tests and for reuse from other tasks.
Attributes:
| Name | Type | Description |
|---|---|---|
taskiq_task |
Any
|
The underlying TaskIQ decorated task — the
escape hatch for |
Wrap a TaskIQ decorated task.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
taskiq_task
|
Any
|
The object returned by |
required |
func
|
Callable[P, Awaitable[R]]
|
The original async function,
kept for :meth: |
required |
task_name
property
¶
Return the registered task name.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
TaskIQ's |
enqueue
async
¶
Send this call to a worker and return without waiting for it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args
|
args
|
Positional arguments for the task. |
()
|
**kwargs
|
kwargs
|
Keyword arguments for the task. |
{}
|
Returns:
| Type | Description |
|---|---|
AsyncTaskiqTask[R]
|
AsyncTaskiqTask[R]: The TaskIQ task handle, typed by the wrapped |
AsyncTaskiqTask[R]
|
function's return value. |
AsyncTaskiqTask[R]
|
for a |
run
async
¶
Run the task body inline (no broker) and return its value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args
|
args
|
Positional arguments for the task. |
()
|
**kwargs
|
kwargs
|
Keyword arguments for the task. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
R |
R
|
Whatever the wrapped function returns. |
TaskIQSettingsLike
¶
Bases: Protocol
The two settings fields :meth:TaskQueue.from_settings reads.
Typed as a protocol rather than as
:class:~tempest_fastapi_sdk.settings.TaskIQSettings so a service
composing its own Settings from the mixins passes without an
import cycle, and so a test can hand over a plain object.
Every member is a read-only @property. A bare annotation in a
Protocol declares a settable attribute, and
:class:~tempest_fastapi_sdk.settings.BaseAppSettings is
frozen=True — so mypy rejected the very Settings the mixins
build (expected settable variable, got read-only attribute) and
the documented TaskQueue.from_settings(Settings()) needed a
type: ignore. A property accepts both the frozen settings and a
plain object with ordinary attributes.
Attributes:
| Name | Type | Description |
|---|---|---|
TASKIQ_BROKER_URL |
str
|
Broker URL. Empty selects the in-memory broker, which is the shape a test suite and a dev box without Redis actually run in. |
TASKIQ_RESULT_BACKEND_URL |
str | None
|
Where task results go.
|
TASKIQ_STORE_RESULTS |
bool
|
Whether results are stored at all.
|
TASKIQ_RESULT_TTL_SECONDS |
int
|
Seconds a stored result
survives; |
TaskQueue
¶
TaskQueue(
broker: AsyncBroker,
*,
resources: Sequence[LifecycleResource] = (),
lock_url: str | None = None,
)
Typed facade over a TaskIQ broker plus its periodic scheduler.
Declare tasks with :meth:task, enqueue them with
:meth:Task.enqueue, and schedule periodic ones with :meth:cron /
:meth:interval — all on one object::
from tempest_fastapi_sdk.tasks import TaskQueue
tq = TaskQueue.rabbitmq("amqp://guest:guest@localhost:5672/")
@tq.task
async def send_welcome(to: str, name: str) -> None:
await email.send(to, "Welcome", f"Hi {name}")
@tq.cron("0 9 * * MON-FRI", cron_offset="-03:00")
async def daily_digest() -> None:
...
# FastAPI lifespan
await tq.connect()
await tq.start_scheduler() # dev / single-process only
...
await tq.stop_scheduler()
await tq.disconnect()
# from a request handler
await send_welcome.enqueue(to=user.email, name=user.name)
In production run the worker (and one scheduler) as separate
processes. The TaskIQ CLI resolves module:attr with a plain
getattr, so bind :attr:broker / :attr:scheduler to names of
their own — myapp.tasks:tq.broker raises AttributeError:
module 'myapp.tasks' has no attribute 'tq.broker'::
# myapp/tasks.py
broker = tq.broker
scheduler = tq.scheduler
# shell
taskiq worker myapp.tasks:broker
taskiq scheduler myapp.tasks:scheduler
Attributes:
| Name | Type | Description |
|---|---|---|
broker |
AsyncBroker
|
The underlying TaskIQ broker (for the worker CLI and escape hatches). |
Wrap an already-constructed TaskIQ broker.
Prefer :meth:from_settings, or :meth:rabbitmq / :meth:redis
/ :meth:memory; use this to inject a custom or pre-configured
broker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
broker
|
AsyncBroker
|
A TaskIQ broker instance. |
required |
resources
|
Sequence[LifecycleResource]
|
Resources the
worker opens on startup and closes on shutdown, in
order — see :meth: |
()
|
lock_url
|
str | None
|
Redis URL the scheduler lease is
derived from when :meth: |
None
|
scheduler
property
¶
Return the underlying TaskIQ scheduler (for the CLI).
Lazily built on first access. Point the standalone scheduler
process at it. The CLI resolves module:attr with a plain
getattr, so bind it to a module-level name first —
scheduler = tq.scheduler, then taskiq scheduler
myapp.tasks:scheduler.
Returns:
| Name | Type | Description |
|---|---|---|
TaskiqScheduler |
TaskiqScheduler
|
The underlying TaskIQ scheduler, so |
TaskiqScheduler
|
|
is_connected
property
¶
Return True once :meth:connect has succeeded.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
rabbitmq
classmethod
¶
rabbitmq(
url: str, *, resources: Sequence[LifecycleResource] = (), **options: Any
) -> TaskQueue
Build a RabbitMQ-backed task queue ([tasks] extra).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
AMQP URL. |
required |
resources
|
Sequence[LifecycleResource]
|
Resources the
worker opens on startup and closes on shutdown — see
:meth: |
()
|
**options
|
Any
|
Extra keyword arguments forwarded to
|
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
TaskQueue |
TaskQueue
|
A facade around an |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
redis
classmethod
¶
redis(
url: str,
*,
results: bool | str = True,
result_ttl_seconds: int = DEFAULT_RESULT_TTL_SECONDS,
result_prefix: str = DEFAULT_RESULT_PREFIX,
result_serializer: ResultSerializer = DEFAULT_RESULT_SERIALIZER,
resources: Sequence[LifecycleResource] = (),
**options: Any,
) -> TaskQueue
Build a Redis-backed task queue ([tasks-redis] extra).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
Redis URL. |
required |
results
|
bool | str
|
Where task results are stored.
|
True
|
result_ttl_seconds
|
int
|
Seconds a stored result survives.
Defaults to :data: |
DEFAULT_RESULT_TTL_SECONDS
|
result_prefix
|
str
|
Namespace for the result keys. Defaults
to :data: |
DEFAULT_RESULT_PREFIX
|
result_serializer
|
ResultSerializer
|
How results are encoded.
|
DEFAULT_RESULT_SERIALIZER
|
resources
|
Sequence[LifecycleResource]
|
Resources the
worker opens on startup and closes on shutdown — see
:meth: |
()
|
**options
|
Any
|
Extra keyword arguments forwarded to
|
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
TaskQueue |
TaskQueue
|
A facade around a Redis stream broker, carrying |
TaskQueue
|
the URL its scheduler lease can be derived from — see |
|
TaskQueue
|
meth: |
Raises:
| Type | Description |
|---|---|
ImportError
|
When |
from_settings
classmethod
¶
from_settings(
settings: TaskIQSettingsLike,
*,
results: bool | str | None = None,
result_ttl_seconds: int | None = None,
result_prefix: str | None = None,
result_serializer: ResultSerializer = DEFAULT_RESULT_SERIALIZER,
resources: Sequence[LifecycleResource] = (),
**options: Any,
) -> TaskQueue
Build the queue the settings describe, transport included.
The branch this replaces was written once per service, and each
copy decided the same three things again: which transport the
URL means, whether results are stored, and what an empty URL
does. The last one is the load-bearing case — a test suite and a
dev box without Redis run with TASKIQ_BROKER_URL empty, and
the answer has to be a broker that still registers
@tq.task, not a parse error on an empty string.
Heartbeat files are read from the settings too:
TASKIQ_WORKER_HEARTBEAT_FILE / TASKIQ_SCHEDULER_HEARTBEAT_FILE
(empty, the default, leaves that heartbeat off) and
TASKIQ_HEARTBEAT_SECONDS. When either file is set,
:meth:enable_heartbeat is called. They are read with
getattr and a default, because :class:TaskIQSettingsLike
keeps its four members — adding three to the protocol would
reject the plain objects that satisfy it today.
Example:
>>> from tempest_fastapi_sdk.settings import TaskIQSettings
>>> from tempest_fastapi_sdk.tasks import TaskQueue
>>>
>>> class Settings(TaskIQSettings):
... '''Service settings.'''
>>>
>>> tq: TaskQueue = TaskQueue.from_settings(Settings())
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
settings
|
TaskIQSettingsLike
|
Anything carrying the four
fields of that protocol — the
:class: |
required |
results
|
bool | str | None
|
Overrides where results go.
|
None
|
result_ttl_seconds
|
int | None
|
Overrides the result TTL.
|
None
|
result_prefix
|
str | None
|
Overrides the result key
namespace. |
None
|
result_serializer
|
ResultSerializer
|
How results are encoded,
on both transports. |
DEFAULT_RESULT_SERIALIZER
|
resources
|
Sequence[LifecycleResource]
|
Resources the worker opens on startup and closes on shutdown. |
()
|
**options
|
Any
|
Extra keyword arguments forwarded to the selected broker. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
TaskQueue |
TaskQueue
|
A facade over the transport the URL scheme names — |
TaskQueue
|
|
|
TaskQueue
|
for RabbitMQ, and the in-memory broker for an empty URL. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the URL carries a scheme none of the transports handles. Falling back to memory here would turn a typo in a deployed environment variable into a queue that silently runs every task in the web process. |
ImportError
|
When the transport the URL selects needs an
extra that is not installed. The message names
|
memory
classmethod
¶
memory(*, resources: Sequence[LifecycleResource] = ()) -> TaskQueue
Build an in-memory task queue for tests.
enqueue runs the task synchronously in-process, so tests
need no worker and no broker connection. The in-memory broker
runs the client and worker lifecycle events on
:meth:connect, so worker-scoped hooks fire here too — which is
what makes them testable without a worker process.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
resources
|
Sequence[LifecycleResource]
|
Resources opened on
startup and closed on shutdown — see :meth: |
()
|
Returns:
| Name | Type | Description |
|---|---|---|
TaskQueue |
TaskQueue
|
A facade around |
task
¶
task(
func: Callable[P, Awaitable[R]],
*,
name: str | None = None,
retry: RetryPolicy | None = None,
schedule: list[dict[str, Any]] | None = None,
**options: Any,
) -> Task[P, R]
task(
func: None = None,
*,
name: str | None = None,
retry: RetryPolicy | None = None,
schedule: list[dict[str, Any]] | None = None,
**options: Any,
) -> Callable[[Callable[P, Awaitable[R]]], Task[P, R]]
task(
func: Callable[P, Awaitable[R]] | None = None,
*,
name: str | None = None,
retry: RetryPolicy | None = None,
schedule: list[dict[str, Any]] | None = None,
**options: Any,
) -> Task[P, R] | Callable[[Callable[P, Awaitable[R]]], Task[P, R]]
Register an async function as a background task.
Usable bare or with options::
@tq.task
async def a() -> None: ...
@tq.task(name="reports:nightly", retry=RetryPolicy(max_retries=5))
async def b() -> None: ...
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable[P, Awaitable[R]] | None
|
The function, when
used as a bare |
None
|
name
|
str | None
|
Override the auto-generated
|
None
|
retry
|
RetryPolicy | None
|
Per-task retry configuration; its
labels are merged into |
None
|
schedule
|
list[dict[str, Any]] | None
|
A raw TaskIQ schedule
spec, for the triggers :meth: |
None
|
**options
|
Any
|
Extra TaskIQ labels / options forwarded to
|
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Task[P, R] | Callable[[Callable[P, Awaitable[R]]], Task[P, R]]
|
Task[P, R] | Callable[[Callable[P, Awaitable[R]]], Task[P, R]]: |
|
A |
Task[P, R] | Callable[[Callable[P, Awaitable[R]]], Task[P, R]]
|
class: |
Task[P, R] | Callable[[Callable[P, Awaitable[R]]], Task[P, R]]
|
forms are overloaded so the decorated name keeps the wrapped |
|
Task[P, R] | Callable[[Callable[P, Awaitable[R]]], Task[P, R]]
|
function's parameters and return type — |
|
Task[P, R] | Callable[[Callable[P, Awaitable[R]]], Task[P, R]]
|
|
|
Task[P, R] | Callable[[Callable[P, Awaitable[R]]], Task[P, R]]
|
decorator ( |
Raises:
| Type | Description |
|---|---|
ValueError
|
When an entry's |
enqueue_by_name
async
¶
Send a call to the task registered under name, without importing it.
The API process enqueues work the worker owns: importing the task
module there would pull the task's whole dependency graph (and its
import-time side effects) into every request process, and couple
the two. Sending by name keeps the API to a string — a
*_TASK_NAME constant next to the task — and the worker
resolves it.
Every :class:TaskQueue installs, first in its broker, the
middleware from
:func:~tempest_fastapi_sdk.tasks.observability.make_registered_labels_middleware,
so the labels the task was registered with (retry policy,
timeout, ack_type) still apply to a call sent this way.
Nothing checks name on the sending side, because that process
does not know the tasks: over Redis or RabbitMQ an unknown name is
logged by the worker as task "..." is not found and dropped.
The in-memory broker is its own worker, so there it raises
taskiq.exceptions.SendTaskError right away.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The registered task name — the |
required |
*args
|
Any
|
Positional arguments for the task. |
()
|
**kwargs
|
Any
|
Keyword arguments for the task. |
{}
|
Returns:
| Type | Description |
|---|---|
AsyncTaskiqTask[Any]
|
AsyncTaskiqTask[Any]: The TaskIQ task handle; untyped, since the |
AsyncTaskiqTask[Any]
|
sender never sees the task's signature. |
Raises:
| Type | Description |
|---|---|
SendTaskError
|
When the broker refuses the message — with the in-memory broker, for a name no task is registered under. |
register
¶
Register a class-based :class:~tempest_fastapi_sdk.tasks.TaskDef.
Reads the definition's task bindings (constructor form or grouped
@task_method methods) and registers each with the broker.
A binding's retry is rendered into labels here, exactly as
:meth:task does — TaskIQ's middleware reads
retry_on_error / max_retries, so a RetryPolicy
forwarded as a label would be ignored and the task would never
retry, silently.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
definition
|
TaskDef[TaskReturnT]
|
The task-definition instance. |
required |
Returns:
| Type | Description |
|---|---|
Task[Any, TaskReturnT] | dict[str, Task[Any, Any]]
|
Task[Any, TaskReturnT] | dict[str, Task[Any, Any]]: A single |
Task[Any, TaskReturnT] | dict[str, Task[Any, Any]]
|
class: |
Task[Any, TaskReturnT] | dict[str, Task[Any, Any]]
|
method name for the grouped form. |
Notes
TaskIQ needs a plain function with a settable __name__,
and a bound method has neither, so the method is wrapped.
Deliberately without functools.wraps: that would make
inspect.signature follow __wrapped__ back to a
signature including self.
enable_retries
¶
Install TaskIQ's retry middleware so failing tasks are re-run.
A task opts in with a :class:~tempest_fastapi_sdk.tasks.RetryPolicy
(@tq.task(retry=RetryPolicy(...))); this installs the middleware
that honours it. Call it before :meth:connect.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
default_max_retries
|
int
|
Attempt cap for a retrying task that
sets no |
3
|
enable_metrics
¶
enable_metrics(metrics: TaskMetrics) -> None
Record Prometheus run count + duration for every task.
Call it before :meth:connect.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metrics
|
TaskMetrics
|
The metric bundle to record into. |
required |
dead_letter
¶
dead_letter(sink: DeadLetterSink, *, default_max_retries: int = 3) -> None
Route terminally-failed tasks to sink.
A task that fails with no retry configured, or after its retries are
exhausted, is handed to sink exactly once. Call it before
:meth:connect.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sink
|
DeadLetterSink
|
Where dead letters go (a channel publisher, a DB write, an alert — the target is yours). |
required |
default_max_retries
|
int
|
Must match the value passed to
:meth: |
3
|
enable_heartbeat
¶
enable_heartbeat(
*,
worker_file: str | Path | None = None,
scheduler_file: str | Path | None = None,
every: timedelta = DEFAULT_HEARTBEAT_EVERY,
) -> None
Make the worker and the scheduler prove they are alive.
worker_file— each worker process rewrites it with the current UTC time everyevery, from an asyncio task started on the worker's startup event and cancelled on its shutdown (:class:~tempest_fastapi_sdk.tasks.heartbeat.HeartbeatLoop). The beat is local: it goes through no broker and no scheduler, so every replica keeps its own file fresh however the broker spreads tasks between them. A fresh file proves the process is alive and its event loop is not blocked; a task that blocks the loop with synchronous work stops the beat.scheduler_file— the scheduler rewrites it once pereveryfrom inside TaskIQ's scheduler loop, through thepre_sendof a schedule source attached to :attr:scheduler(:class:~tempest_fastapi_sdk.tasks.heartbeat.source.HeartbeatScheduleSource). The send is then cancelled, so nothing is published. A fresh file proves the loop is ticking — not that the scheduler can still publish.
Both are written atomically (temporary file plus
:func:os.replace, mode 0644). A failed write — read-only
filesystem, missing directory — logs one warning and never stops
the worker or the scheduler; the stale file is the signal.
Call this in the module the worker and the scheduler import,
before binding scheduler = tq.scheduler; taskiq scheduler
myapp.tasks:scheduler then picks the source up with no extra
wiring. Each process only writes the file that belongs to it, so
configuring both paths in both containers is safe. With
:meth:memory the worker events fire on :meth:connect, so the
worker loop runs in that process too.
Check the file from the container with
python -m tempest_fastapi_sdk.tasks.heartbeat <file> --max-age
<seconds>, using a max_age of about three times every.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
worker_file
|
str | Path | None
|
Heartbeat file each worker
process writes; |
None
|
scheduler_file
|
str | Path | None
|
Heartbeat file the
scheduler writes; |
None
|
every
|
timedelta
|
Heartbeat period. Whole seconds, at least one — TaskIQ's interval schedules accept nothing else. |
DEFAULT_HEARTBEAT_EVERY
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When neither file is given, or |
RuntimeError
|
When the heartbeat was already enabled on this queue. |
cron
¶
cron(
expr: str,
*,
cron_offset: str | timedelta | None = None,
name: str | None = None,
**options: Any,
) -> Callable[[Callable[P, Awaitable[R]]], Task[P, R]]
Register a task to run on a cron schedule.
For readable schedules without hand-writing cron syntax, pass a
:class:tempest_fastapi_sdk.tasks.CronEnum member or a builder result
(:func:~tempest_fastapi_sdk.tasks.daily,
:func:~tempest_fastapi_sdk.tasks.weekdays, …) as expr, and a
:class:~tempest_fastapi_sdk.tasks.CronOffsetEnum member as
cron_offset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expr
|
str
|
A cron expression ( |
required |
cron_offset
|
str | timedelta | None
|
Timezone offset applied
to |
None
|
name
|
str | None
|
Override the task name. |
None
|
**options
|
Any
|
Extra TaskIQ labels forwarded to the task. |
{}
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable[P, Awaitable[R]]], Task[P, R]]
|
Callable[[Callable[P, Awaitable[R]]], Task[P, R]]: A decorator |
Callable[[Callable[P, Awaitable[R]]], Task[P, R]]
|
returning the wrapped :class: |
interval
¶
interval(
seconds: float | timedelta, *, name: str | None = None, **options: Any
) -> Callable[[Callable[P, Awaitable[R]]], Task[P, R]]
Register a task to run every seconds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seconds
|
float | timedelta
|
Interval between runs. A number is coerced to seconds. |
required |
name
|
str | None
|
Override the task name. |
None
|
**options
|
Any
|
Extra TaskIQ labels forwarded to the task. |
{}
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable[P, Awaitable[R]]], Task[P, R]]
|
Callable[[Callable[P, Awaitable[R]]], Task[P, R]]: A decorator |
Callable[[Callable[P, Awaitable[R]]], Task[P, R]]
|
returning the wrapped :class: |
on_startup
¶
on_startup(handler: HookT, *, scope: LifecycleScope = 'worker') -> HookT
on_startup(
handler: None = None, *, scope: LifecycleScope = "worker"
) -> Callable[[HookT], HookT]
on_startup(
handler: HookT | None = None, *, scope: LifecycleScope = "worker"
) -> HookT | Callable[[HookT], HookT]
Run a callback when the process this queue lives in starts.
The worker has no FastAPI lifespan, so without this there is
nowhere to open the database, the message broker or an HTTP
client — and nowhere to close them either. This is that place::
queue = TaskQueue.rabbitmq(settings.TASKIQ_BROKER_URL)
@queue.on_startup
async def _open() -> None:
await db.connect()
@queue.on_shutdown
async def _close() -> None:
await db.disconnect()
For the common case of resources that already speak
connect / disconnect, :meth:use does both in one line.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
handler
|
HookT | None
|
The callback, when used as a bare
|
None
|
scope
|
LifecycleScope
|
Which process runs it. The default
|
'worker'
|
Returns:
| Type | Description |
|---|---|
HookT | Callable[[HookT], HookT]
|
HookT | Callable[[HookT], HookT]: The handler, unchanged (bare |
HookT | Callable[[HookT], HookT]
|
form), or a decorator returning it. |
on_shutdown
¶
on_shutdown(handler: HookT, *, scope: LifecycleScope = 'worker') -> HookT
on_shutdown(
handler: None = None, *, scope: LifecycleScope = "worker"
) -> Callable[[HookT], HookT]
on_shutdown(
handler: HookT | None = None, *, scope: LifecycleScope = "worker"
) -> HookT | Callable[[HookT], HookT]
Run a callback when the process this queue lives in stops.
The mirror of :meth:on_startup; see it for the example.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
handler
|
HookT | None
|
The callback, when used as a bare
|
None
|
scope
|
LifecycleScope
|
Which process runs it. |
'worker'
|
Returns:
| Type | Description |
|---|---|
HookT | Callable[[HookT], HookT]
|
HookT | Callable[[HookT], HookT]: The handler, unchanged (bare |
HookT | Callable[[HookT], HookT]
|
form), or a decorator returning it. |
use
¶
use(*resources: LifecycleResource, scope: LifecycleScope = 'worker') -> None
Open resources when the process starts, close them when it stops.
The shortcut behind TaskQueue.rabbitmq(url, resources=[db,
broker]). Anything with connect / disconnect fits —
:class:~tempest_fastapi_sdk.db.AsyncDatabaseManager,
:class:~tempest_fastapi_sdk.queue.MessageBroker,
:class:~tempest_fastapi_sdk.storage.AsyncMinIOClient::
queue = TaskQueue.rabbitmq(url, resources=[db, broker])
They are opened left to right and closed right to left, so a
resource that depends on an earlier one still has it while
closing. connect / disconnect are looked up when the
hook fires, not when use runs, so patching them later — on
the class or on the instance, as a test does to keep the
in-memory queue off a real broker — takes effect.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*resources
|
LifecycleResource
|
The resources to manage. |
()
|
scope
|
LifecycleScope
|
Which process manages them; see
:meth: |
'worker'
|
connect
async
¶
Start the broker so tasks can be enqueued and processed.
Idempotent — extra calls are no-ops while the broker is alive.
start_scheduler
async
¶
Start the periodic scheduler loop in this process, unguarded.
This is the raw loop: it fires every schedule it owns, in every
process that calls it. With more than one replica that means
every schedule fires once per replica, and nothing says so —
prefer lifespan(scheduler=True), which holds a lease so
exactly one replica runs the loop.
Returns:
| Type | Description |
|---|---|
Task[None]
|
asyncio.Task[None]: The scheduler loop task (cancelled by |
Task[None]
|
meth: |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When :meth: |
stop_scheduler
async
¶
Stop the in-process scheduler started by :meth:start_scheduler.
lifespan
async
¶
lifespan(
*,
scheduler: bool | Literal["unlocked"] = False,
scheduler_lock: SchedulerLock | None = None,
lease_name: str | None = None,
lease_ttl_seconds: float = DEFAULT_LOCK_TTL_SECONDS,
) -> AsyncGenerator[TaskQueue, None]
Connect on entry, disconnect on exit — and optionally schedule.
Plugs straight into FastAPI, which is what removes the second process from a small deployment::
from contextlib import asynccontextmanager
from collections.abc import AsyncGenerator
from fastapi import FastAPI
tq = TaskQueue.from_settings(settings)
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
'''Open the queue and run periodic tasks in-process.'''
async with tq.lifespan(scheduler=True):
yield
app = FastAPI(lifespan=lifespan)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scheduler
|
bool | Literal['unlocked']
|
Whether to run the
periodic scheduler here. |
False
|
scheduler_lock
|
SchedulerLock | None
|
The lease to use.
|
None
|
lease_name
|
str | None
|
Redis key for the derived lease. Two services sharing one Redis instance need different names, or only one of them ever schedules. |
None
|
lease_ttl_seconds
|
float
|
How long the derived lease survives unrenewed. Renewals run at a third of it. |
DEFAULT_LOCK_TTL_SECONDS
|
Yields:
| Name | Type | Description |
|---|---|---|
TaskQueue |
AsyncGenerator[TaskQueue, None]
|
This connected facade. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
health_check
async
¶
Return True while the broker is started.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
AsyncTaskScheduler
¶
Manage the lifecycle of a TaskIQ periodic-task scheduler.
Wraps :class:taskiq.TaskiqScheduler together with
:class:taskiq.schedule_sources.LabelScheduleSource so periodic
tasks are declared with decorators alongside regular tasks and the
scheduler is started, stopped and (optionally) driven in-process
from the FastAPI lifespan.
The scheduler does not execute task bodies directly — it kicks
them into the same broker used by
:class:AsyncTaskBrokerManager, where the worker process consumes
and runs them. For production deployments, prefer running the
standalone taskiq scheduler <module>:<name> CLI process, where
<name> is a module-level binding of :attr:scheduler (the CLI
resolves the spec with a plain getattr, so a dotted attribute
path raises AttributeError); :meth:run_in_background is
convenient for development and single-process services.
Typical usage::
from taskiq_aio_pika import AioPikaBroker
from tempest_fastapi_sdk.tasks import (
AsyncTaskBrokerManager,
AsyncTaskScheduler,
)
broker = AioPikaBroker("amqp://guest:guest@localhost:5672/")
tasks = AsyncTaskBrokerManager(broker)
scheduler = AsyncTaskScheduler(broker)
@scheduler.cron("*/5 * * * *")
async def heartbeat() -> None:
...
@scheduler.interval(seconds=30)
async def poll_remote() -> None:
...
# FastAPI lifespan
await tasks.connect()
await scheduler.connect()
await scheduler.run_in_background() # dev / single-process only
...
await scheduler.disconnect()
await tasks.disconnect()
Attributes:
| Name | Type | Description |
|---|---|---|
broker |
AsyncBroker
|
The TaskIQ broker tasks are kicked into. |
sources |
list[ScheduleSource]
|
Active schedule sources. |
scheduler |
TaskiqScheduler
|
Underlying TaskIQ scheduler. |
Initialize the scheduler manager.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
broker
|
AsyncBroker
|
The TaskIQ broker periodic tasks will
be kicked into. Reuse the same broker instance that
:class: |
required |
sources
|
Sequence[ScheduleSource] | None
|
Schedule sources
to read scheduled tasks from. Defaults to a single
:class: |
None
|
is_connected
property
¶
Return True once :meth:connect succeeded.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
cron
¶
cron(
expr: str,
*,
cron_offset: str | timedelta | None = None,
task_name: str | None = None,
**labels: Any,
) -> Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]
Register a task to run on a cron schedule.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expr
|
str
|
A cron expression (e.g. |
required |
cron_offset
|
str | timedelta | None
|
Optional timezone
offset applied to |
None
|
task_name
|
str | None
|
Override the auto-generated
|
None
|
**labels
|
Any
|
Extra TaskIQ labels forwarded to
|
{}
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]
|
Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]: |
Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]
|
The decorator |
Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]
|
the function's parameters and return type. |
interval
¶
interval(
seconds: float | timedelta, *, task_name: str | None = None, **labels: Any
) -> Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]
Register a task to run every seconds interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seconds
|
float | timedelta
|
Interval between runs. A
:class: |
required |
task_name
|
str | None
|
Override the auto-generated task name. |
None
|
**labels
|
Any
|
Extra TaskIQ labels forwarded to
|
{}
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]
|
Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]: |
Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]
|
The decorator |
Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]
|
the function's parameters and return type. |
schedule
¶
schedule(
spec: list[dict[str, Any]], *, task_name: str | None = None, **labels: Any
) -> Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]
Register a task with a raw TaskIQ schedule spec.
Use this when you need time (one-shot at a specific
datetime), multiple triggers on the same task, or any
combination not covered by :meth:cron / :meth:interval.
Any cron_offset in spec goes through
:func:~tempest_fastapi_sdk.tasks.normalize_cron_offset, so a
numeric offset reaches the scheduler in the form it applies
rather than as an unresolvable time zone key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
list[dict[str, Any]]
|
The schedule list (each entry
must carry one of |
required |
task_name
|
str | None
|
Override the auto-generated task name. |
None
|
**labels
|
Any
|
Extra TaskIQ labels forwarded to
|
{}
|
Returns:
| Type | Description |
|---|---|
Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]
|
Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]: |
Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]
|
The decorator |
Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]
|
the function's parameters and return type. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When an entry's |
register
¶
register(
func: Callable[_P, _R],
*,
schedule: list[dict[str, Any]],
task_name: str | None = None,
**labels: Any,
) -> AsyncTaskiqDecoratedTask[_P, _R]
Register func as a scheduled task without decorator syntax.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable[_P, _R]
|
The async callable to register. |
required |
schedule
|
list[dict[str, Any]]
|
The schedule list (see
:meth: |
required |
task_name
|
str | None
|
Override the auto-generated task name. |
None
|
**labels
|
Any
|
Extra TaskIQ labels forwarded to
|
{}
|
Returns:
| Type | Description |
|---|---|
AsyncTaskiqDecoratedTask[_P, _R]
|
AsyncTaskiqDecoratedTask[_P, _R]: The registered task, |
AsyncTaskiqDecoratedTask[_P, _R]
|
preserving |
Raises:
| Type | Description |
|---|---|
ValueError
|
When an entry's |
connect
async
¶
Start the scheduler and every configured source.
:class:taskiq.TaskiqScheduler itself only starts the broker;
we additionally call startup() on each source so the default
:class:LabelScheduleSource discovers tasks declared via
:meth:cron / :meth:interval / :meth:schedule /
:meth:register. Safe to call multiple times — subsequent
calls are no-ops while the scheduler is alive.
disconnect
async
¶
Stop the background loop (if any) and shut the scheduler down.
run_in_background
async
¶
Run TaskIQ's scheduler loop as an in-process asyncio task.
Suitable for development and single-process services. For
production deployments with multiple workers, run the standalone
CLI instead so only one scheduler is active. Bind
:attr:scheduler to a module-level name — the CLI resolves
module:attr with a plain getattr, so a dotted path
raises AttributeError::
# myapp/tasks.py
taskiq_scheduler = scheduler.scheduler
# shell
taskiq scheduler myapp.tasks:taskiq_scheduler
Returns:
| Type | Description |
|---|---|
Task[None]
|
asyncio.Task[None]: The spawned task running |
Task[None]
|
class: |
Task[None]
|
meth: |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When :meth: |
lifespan
async
¶
Yield the scheduler inside an async with block.
Connects on entry, disconnects on exit. The in-process loop is
not started automatically — call :meth:run_in_background
explicitly when you need it.
Yields:
| Name | Type | Description |
|---|---|---|
TaskiqScheduler |
AsyncGenerator[TaskiqScheduler, None]
|
The connected scheduler. |
health_check
async
¶
Return True when the scheduler has been started.
Schedule sources don't expose a generic ping, so we only report
whether :meth:connect succeeded and (when applicable) the
background loop is still alive.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
in-process loop is still running. |
StageColumns
dataclass
¶
The resolved column names of one stage on one record.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The stage's name. |
status |
str
|
Attribute holding the :class: |
error |
str
|
Attribute holding the failure message. |
result |
str
|
Attribute holding what the stage produced. |
StageMap
¶
StageMap(
stages: Sequence[str],
*,
prefix: str = "",
status_template: str = "status_{stage}",
error_template: str = "error_{stage}",
result_template: str = "result_{stage}",
)
Declares a record's stages and performs their transitions.
Attributes:
| Name | Type | Description |
|---|---|---|
prefix |
str
|
Prepended to every resolved column name. |
Declare the stages and how their columns are named.
The templates exist because column naming is a house convention,
not something a library gets to impose — a codebase spelling them
summary_status should not have to rename its schema to use
this.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stages
|
Sequence[str]
|
Stage names, in the order the interface should show them. |
required |
prefix
|
str
|
Prepended to every column name, for schemas that
namespace a record's columns ( |
''
|
status_template
|
str
|
Column name for a stage's status, with
|
'status_{stage}'
|
error_template
|
str
|
Column name for a stage's error. |
'error_{stage}'
|
result_template
|
str
|
Column name for a stage's result. |
'result_{stage}'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
names
property
¶
The declared stage names, in declaration order.
Returns:
| Type | Description |
|---|---|
tuple[str, ...]
|
tuple[str, ...]: The names. |
columns
¶
columns(stage: str) -> StageColumns
Resolve one stage's column names.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stage
|
str
|
The stage name. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
StageColumns |
StageColumns
|
The resolved names. |
Raises:
| Type | Description |
|---|---|
KeyError
|
When the stage was not declared. |
status
¶
status(record: object, stage: str) -> StageStatusEnum | None
Read a stage's status off a record.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
record
|
object
|
The row. |
required |
stage
|
str
|
The stage name. |
required |
Returns:
| Type | Description |
|---|---|
StageStatusEnum | None
|
StageStatusEnum | None: The status, or |
StageStatusEnum | None
|
empty — which means the stage was never requested, a state |
StageStatusEnum | None
|
worth distinguishing from |
Raises:
| Type | Description |
|---|---|
KeyError
|
When the stage was not declared. |
is_running
¶
Does this stage still have work to stop?
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
record
|
object
|
The row. |
required |
stage
|
str
|
The stage name. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
Raises:
| Type | Description |
|---|---|
KeyError
|
When the stage was not declared. |
owns
¶
owns(record: object, stage: str, expected: StageStatusEnum) -> bool
Does the run that set expected still own this stage?
The check to make before writing a result, and it is about
ownership rather than cancellation on purpose: a status that is no
longer expected covers both the user cancelling and a newer run
having restarted the stage. Writing in either case is wrong — one
resurrects stopped work, the other clobbers a fresher result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
record
|
object
|
A freshly read row. Re-read it before calling
this; an object loaded before the long work started still
holds the old status and would answer |
required |
stage
|
str
|
The stage name. |
required |
expected
|
StageStatusEnum
|
What this run left the stage at. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
Raises:
| Type | Description |
|---|---|
KeyError
|
When the stage was not declared. |
mark
¶
mark(
record: object,
stage: str,
status: StageStatusEnum,
*,
error: str | None = None,
result: object = None,
) -> None
Move a stage, writing the error and result columns with it.
Mutates record in place and does not persist it — the caller
owns the session and decides when to flush, which is what lets
several stage writes share one transaction.
The error column is cleared on any status other than FAILED, so
a restarted stage stops showing the message from the run before it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
record
|
object
|
The row. |
required |
stage
|
str
|
The stage name. |
required |
status
|
StageStatusEnum
|
The new status. |
required |
error
|
str | None
|
The failure message; only meaningful with
|
None
|
result
|
object
|
What the stage produced. |
None
|
Raises:
| Type | Description |
|---|---|
KeyError
|
When the stage was not declared. |
ValueError
|
When |
cancel
¶
Cancel every requested stage that still has work to stop.
Idempotent, and deliberately partial: a stage that already finished is reported as ignored rather than raising. A screen polling for status will routinely ask to cancel something that completed a moment ago, and that is not an error.
There is no cascade, and none is needed when each stage only enqueues the next one on success: cancelling the first means the second is never created.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
record
|
object
|
The row. |
required |
stages
|
Iterable[str] | None
|
Which to cancel; |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
tuple[list[str], list[str]]: The stages cancelled, and those |
list[str]
|
ignored, each in the order requested. Duplicates in the request |
tuple[list[str], list[str]]
|
are collapsed, so a caller cannot get the same stage twice. |
Raises:
| Type | Description |
|---|---|
KeyError
|
When a requested stage was not declared. |
snapshot
¶
snapshot(record: object) -> dict[str, StageStatusEnum | None]
Read every stage's status at once.
What a status endpoint serializes, and what a test asserts on without naming a column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
record
|
object
|
The row. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, StageStatusEnum | None]
|
dict[str, StageStatusEnum | None]: Status per stage, in declaration |
dict[str, StageStatusEnum | None]
|
order. |
StageStatusEnum
¶
Bases: StrEnum
Where one stage of a pipeline is.
PENDING— queued, nobody has started it.RUNNING— a worker is on it.DONE— finished; the result column is filled.FAILED— stopped; the error column says why.CANCELLED— the user asked it to stop. Terminal like the two above, and like them it is not re-entered on its own — but it is not a failure, so an interface highlightingFAILEDshould leave it alone.
run_cancellable
async
¶
run_cancellable(
work: Awaitable[ResultT],
*,
interrupted: Callable[[], Awaitable[bool]],
poll_seconds: float = DEFAULT_POLL_SECONDS,
stop_event: Event | None = None,
) -> ResultT
Run work, aborting it as soon as interrupted() says to.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
work
|
Awaitable[ResultT]
|
The coroutine doing the long work. It
must be genuinely cancellable — async I/O, not a
|
required |
interrupted
|
Callable[[], Awaitable[bool]]
|
Polled between checks;
|
required |
poll_seconds
|
float
|
Seconds between checks. |
DEFAULT_POLL_SECONDS
|
stop_event
|
Event | None
|
Set before the coroutine is cancelled, so work running in a thread that watches this event stops too. Without it, a thread keeps going after the await is abandoned. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
ResultT |
ResultT
|
Whatever |
Raises:
| Type | Description |
|---|---|
StageInterruptedError
|
The predicate said to stop. |
ValueError
|
When |
Exception
|
Anything |
daily
¶
Return a cron expression firing once a day at hour:minute.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hour
|
int
|
Hour of day, |
0
|
minute
|
int
|
Minute past the hour, |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
e.g. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
every_minute
¶
Return a cron expression firing every minute ("* * * * *").
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The cron expression. |
every_n_minutes
¶
Return a cron expression firing every n minutes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
The minute step, |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
e.g. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
hourly
¶
Return a cron expression firing once an hour at minute.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
minute
|
int
|
Minute past the hour, |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
e.g. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
monthly
¶
Return a cron expression firing once a month on day at hour:minute.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
day
|
int
|
Day of month, |
1
|
hour
|
int
|
Hour of day, |
0
|
minute
|
int
|
Minute past the hour, |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
e.g. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
normalize_cron_offset
¶
Return cron_offset in the form TaskIQ actually applies.
TaskIQ reads cron_offset two different ways
(taskiq/cli/scheduler/run.py, measured on taskiq 0.12.6): a
:class:~datetime.timedelta is added to the current time, while a
:class:str is handed to :class:zoneinfo.ZoneInfo as an IANA key.
A numeric string such as "-03:00" is therefore not a key at all,
and reaches the scheduler loop as ZoneInfoNotFoundError — which
the loop does not catch (its except covers CronValueError
only), so it stops scheduling for every task in the process, not
just the one that declared the offset.
So the numeric forms this SDK hands out (:class:CronOffsetEnum) are
converted to the timedelta TaskIQ applies, and any other string
is resolved as an IANA key here, at declaration time, where the
traceback still names the caller.
A fixed offset also needs no time zone database, which an IANA key
does: on an image without one, ZoneInfo("UTC") already raises.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str | timedelta
|
A :class: |
required |
Returns:
| Type | Description |
|---|---|
str | timedelta
|
str | timedelta: A |
str | timedelta
|
IANA key unchanged once it is known to resolve. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
normalize_schedule
¶
Return spec with every entry's cron_offset normalized.
Applies :func:normalize_cron_offset to each entry that declares
one, so a raw schedule spec reaches the broker in the form TaskIQ
applies. Entries are shallow-copied, leaving the caller's list and
dicts untouched.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
Iterable[dict[str, Any]]
|
Schedule entries, each carrying
one of |
required |
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
list[dict[str, Any]]: The normalized entries, in order. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When an entry's |
weekdays
¶
Return a cron expression firing Mon-Fri at hour:minute.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hour
|
int
|
Hour of day, |
0
|
minute
|
int
|
Minute past the hour, |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
e.g. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
weekends
¶
Return a cron expression firing Sat-Sun at hour:minute.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hour
|
int
|
Hour of day, |
0
|
minute
|
int
|
Minute past the hour, |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
e.g. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
weekly
¶
weekly(day: WeekdayEnum | str, hour: int = 0, minute: int = 0) -> str
Return a cron expression firing once a week on day at hour:minute.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
day
|
WeekdayEnum | str
|
The weekday ( |
required |
hour
|
int
|
Hour of day, |
0
|
minute
|
int
|
Minute past the hour, |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
e.g. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
make_dead_letter_admin_model
¶
make_dead_letter_admin_model(
model: type[BaseDeadLetterModel],
*,
tq: TaskQueue | None = None,
requeue_label: str = "Requeue task",
delete_after: bool = True,
) -> AdminModel[Any]
Build a read-mostly :class:AdminModel over a dead-letter table.
Register the result on your :class:~tempest_fastapi_sdk.admin.AdminSite to
get the dead-letter panel: a filterable, searchable list of terminal
failures. Pass tq to add the requeue bulk action.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
type[BaseDeadLetterModel]
|
The concrete dead-letter table. |
required |
tq
|
TaskQueue | None
|
When given, adds a requeue bulk action wired to this queue. |
None
|
requeue_label
|
str
|
Label for the requeue action. |
'Requeue task'
|
delete_after
|
bool
|
Delete a row once requeued. |
True
|
Returns:
| Type | Description |
|---|---|
AdminModel[Any]
|
AdminModel[Any]: A preconfigured admin registration (no create/edit). |
make_dead_letter_model
¶
make_dead_letter_model(
*, tablename: str = "dead_letters", class_name: str = "DeadLetterModel"
) -> type[BaseDeadLetterModel]
Build a concrete dead-letter model bound to tablename.
For tests and lightweight scripts; production code should subclass
:class:BaseDeadLetterModel by hand so migrations pick it up statically.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tablename
|
str
|
The table name. |
'dead_letters'
|
class_name
|
str
|
The generated class name. |
'DeadLetterModel'
|
Returns:
| Type | Description |
|---|---|
type[BaseDeadLetterModel]
|
type[BaseDeadLetterModel]: The concrete model class. |
make_requeue_action
¶
make_requeue_action(
tq: TaskQueue, *, label: str = "Requeue task", delete_after: bool = True
) -> Callable[[AdminActionContext], Awaitable[AdminActionResult | None]]
Build an admin bulk action that re-enqueues selected dead letters.
Each selected row is re-enqueued on tq's broker with its stored
args / kwargs; rows whose task is no longer registered are skipped.
Successfully requeued rows are deleted when delete_after is set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tq
|
TaskQueue
|
The queue to re-enqueue onto. |
required |
label
|
str
|
The action label shown in the admin dropdown. |
'Requeue task'
|
delete_after
|
bool
|
Delete a row once its call is re-enqueued. |
True
|
Returns:
| Type | Description |
|---|---|
Callable[[AdminActionContext], Awaitable[AdminActionResult | None]]
|
Callable[[AdminActionContext], Awaitable[AdminActionResult | None]]: |
Callable[[AdminActionContext], Awaitable[AdminActionResult | None]]
|
An |
Callable[[AdminActionContext], Awaitable[AdminActionResult | None]]
|
|
task_inventory
¶
List every task registered on tq's broker, sorted by name.
Reads the declared task set (name + schedule + retry labels) off the broker — no live queue state is involved.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tq
|
TaskQueue
|
The task queue whose broker to inspect. |
required |
Returns:
| Type | Description |
|---|---|
list[TaskInfo]
|
list[TaskInfo]: One entry per registered task, sorted by name. |
heartbeat_age
¶
Return how many seconds ago the heartbeat in path was written.
The age comes from the timestamp inside the file, not from its modification time, so copying or touching the file does not make a dead process look alive.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
The heartbeat file. |
required |
now
|
datetime | None
|
The reference instant; defaults to the current time. |
None
|
Returns:
| Type | Description |
|---|---|
float | None
|
float | None: The age in seconds (negative when the file is from |
float | None
|
the future, e.g. clock skew between containers sharing a volume), |
float | None
|
or |
is_heartbeat_fresh
¶
Return whether the heartbeat in path is younger than max_age.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
The heartbeat file. |
required |
max_age
|
float
|
The oldest acceptable heartbeat, in seconds. Pick about three times the heartbeat period, so one late beat does not flip the container to unhealthy. |
required |
now
|
datetime | None
|
The reference instant; defaults to the current time. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
seconds old and no more than |
|
bool
|
data: |
|
bool
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
read_heartbeat
¶
Read the timestamp a heartbeat file holds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
The heartbeat file. |
required |
Returns:
| Type | Description |
|---|---|
datetime | None
|
datetime | None: The recorded instant (timezone-aware, UTC), or |
datetime | None
|
|
datetime | None
|
timestamp. |
validate_max_age
¶
Refuse a max_age no heartbeat can be judged against.
nan compares false with everything, so age <= nan would call
every file stale — and inf would call every file fresh, forever.
Zero or a negative value can never be met.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_age
|
float
|
The oldest acceptable heartbeat, in seconds. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
write_heartbeat
¶
Atomically write the current UTC time to path.
The timestamp goes to a temporary file in the same directory, which
then replaces path with :func:os.replace. A reader therefore
sees the previous timestamp or the new one, never a half-written
file — which a healthcheck running every few seconds would otherwise
hit sooner or later and report as a failure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
The heartbeat file. Its directory must exist. |
required |
now
|
datetime | None
|
The instant to record; defaults to the current time. A naive value is read as UTC. |
None
|
The file ends up with :data:HEARTBEAT_FILE_MODE (0644), so a
checker running as another user can read it.
Raises:
| Type | Description |
|---|---|
OSError
|
When the directory is missing, read-only or full. |
make_job_admin_model
¶
make_job_admin_model(
model: type[BaseJobModel], *, can_delete: bool = False
) -> AdminModel[Any]
Build a read-mostly :class:AdminModel over a job table.
Register the result on your
:class:~tempest_fastapi_sdk.admin.AdminSite and the admin gets the
list half of the task panel for free — pagination, filtering, sorting
and CSV/JSON export over the same rows the workers write. Symmetric to
:func:~tempest_fastapi_sdk.tasks.make_dead_letter_admin_model, which
does the same for terminal failures.
Create and edit are off: a job row is a record of what a worker did, and an operator typing a new one describes work nobody will run. Deleting is off by default for the same reason, and available for the retention sweep an operator does want.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
type[BaseJobModel]
|
The concrete job table. |
required |
can_delete
|
bool
|
Whether the admin may delete rows. Defaults to
|
False
|
Returns:
| Type | Description |
|---|---|
AdminModel[Any]
|
AdminModel[Any]: A preconfigured admin registration (no |
AdminModel[Any]
|
create/edit). The admin package is imported under |
AdminModel[Any]
|
|
AdminModel[Any]
|
imports without it. |
make_job_model
¶
make_job_model(
*, tablename: str = "jobs", class_name: str = "JobModel"
) -> type[BaseJobModel]
Build a concrete job model bound to tablename.
For tests and lightweight scripts; production code should subclass
:class:BaseJobModel by hand so Alembic picks it up statically.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tablename
|
str
|
The table name. |
'jobs'
|
class_name
|
str
|
The generated class name. |
'JobModel'
|
Returns:
| Type | Description |
|---|---|
type[BaseJobModel]
|
type[BaseJobModel]: The concrete model class. |
make_dead_letter_middleware
¶
make_dead_letter_middleware(
sink: DeadLetterSink, *, default_max_retries: int = 3
) -> TaskiqMiddleware
Build a TaskIQ middleware routing terminally-failed tasks to sink.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sink
|
DeadLetterSink
|
Where dead letters go. Its own failures are swallowed (logged) so a broken sink never crashes the worker. |
required |
default_max_retries
|
int
|
Fallback attempt cap for tasks that enable
retries without setting their own |
3
|
Returns:
| Name | Type | Description |
|---|---|---|
TaskiqMiddleware |
TaskiqMiddleware
|
The middleware instance (needs the |
TaskiqMiddleware
|
extra). |
make_registered_labels_middleware
¶
Build the worker middleware that restores a task's registered labels.
A call sent by name (:meth:TaskQueue.enqueue_by_name) comes from a
process that never imported the task, so the message carries none of
the labels the task was registered with — retry_on_error /
max_retries from a :class:RetryPolicy, timeout,
ack_type. TaskIQ's worker reads only the message labels, so
without this the retry policy silently stops applying. Before any
other middleware runs, it merges the labels of the task as the worker
registered it under the message's own, which still win.
Returns:
| Name | Type | Description |
|---|---|---|
TaskiqMiddleware |
TaskiqMiddleware
|
The middleware instance (needs the |
TaskiqMiddleware
|
extra). |
task_method
¶
task_method(
name: str | None = None, *, retry: RetryPolicy | None = None, **options: Any
) -> Callable[[Callable[..., Awaitable[Any]]], Callable[..., Awaitable[Any]]]
Mark a :class:TaskDef method as a background task (grouped form).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str | None
|
Override the auto-generated |
None
|
retry
|
RetryPolicy | None
|
Per-task retry configuration, the same
keyword :meth: |
None
|
**options
|
Any
|
Extra TaskIQ labels / options forwarded to the task registration. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Callable |
Callable[[Callable[..., Awaitable[Any]]], Callable[..., Awaitable[Any]]]
|
The same method, tagged so |
SchedulerLock
¶
Bases: Protocol
The three calls leader election needs from a lease.
A service with its own coordination — etcd, ZooKeeper, a Postgres
advisory lock — implements this and passes it to
:meth:~tempest_fastapi_sdk.tasks.TaskQueue.lifespan; nothing here
knows about Redis.
Every method is a coroutine because acquiring a lease is I/O in every implementation worth having.
acquire
async
¶
Try to take the lease without waiting.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
when another one does. Must not block: a replica that |
|
bool
|
waited here would delay its own startup behind the leader's |
|
bool
|
entire lifetime. |
renew
async
¶
Extend a lease this process already holds.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
it was lost — expired, or taken over. |
|
bool
|
the scheduler loop: a lost lease means another replica is |
|
bool
|
already running it. |
release
async
¶
Give up the lease, if this process still holds it.
Releasing on shutdown is what lets another replica take over in seconds instead of after the TTL. Must tolerate being called when the lease was never acquired or was already lost.
RedisSchedulerLock
¶
RedisSchedulerLock(
client: RedisLockClient,
*,
name: str = DEFAULT_LOCK_NAME,
ttl_seconds: float = DEFAULT_LOCK_TTL_SECONDS,
)
A :class:SchedulerLock over the lock redis-py ships.
Example:
>>> import redis.asyncio as redis
>>> from tempest_fastapi_sdk.tasks import RedisSchedulerLock
>>>
>>> lock: RedisSchedulerLock = RedisSchedulerLock(
... redis.Redis.from_url("redis://localhost:6379/0"),
... )
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The Redis key the lease lives under. |
ttl_seconds |
float
|
How long the lease survives unrenewed. |
Wrap a Redis client as a scheduler lease.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
RedisLockClient
|
An async Redis client. Anything
with |
required |
name
|
str
|
The key to lock. Give two services sharing one Redis instance different names, or one of them will never schedule. |
DEFAULT_LOCK_NAME
|
ttl_seconds
|
float
|
Lease duration. See
:data: |
DEFAULT_LOCK_TTL_SECONDS
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
from_url
classmethod
¶
from_url(
url: str,
*,
name: str = DEFAULT_LOCK_NAME,
ttl_seconds: float = DEFAULT_LOCK_TTL_SECONDS,
) -> RedisSchedulerLock
Build the lease from a Redis URL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
A |
required |
name
|
str
|
The key to lock. |
DEFAULT_LOCK_NAME
|
ttl_seconds
|
float
|
Lease duration. |
DEFAULT_LOCK_TTL_SECONDS
|
Returns:
| Name | Type | Description |
|---|---|---|
RedisSchedulerLock |
RedisSchedulerLock
|
The lease, over a client of its own. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When |
acquire
async
¶
Try to take the lease without waiting.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
Whether this process now holds it. |
renew
async
¶
Extend the lease this process holds.
replace_ttl is set, so the lease is pushed to a fixed
ttl_seconds from now rather than accumulating: a leader up
for a week would otherwise hold a week-long lease, and its death
would stop the schedule until that ran out.
A renewal that fails because the transport failed is indistinguishable, from here, from one that fails because another replica took the lease. Standing down is the safe direction in both: a gap of at most one TTL costs a late tick, while guessing the other way runs two schedulers. The key is released on the way out, so a lease this process still owned goes back immediately instead of waiting out the TTL.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
Whether the lease is still held afterwards. |
bool
|
once it has been lost, and it stays |
release
async
¶
Give up the lease if it is still held.
A failure here is logged and swallowed: this runs on shutdown,
and raising would replace whatever actually stopped the process.
The lease expires on its own within ttl_seconds anyway.
TaskIQSettingsLike
¶
Bases: Protocol
The two settings fields :meth:TaskQueue.from_settings reads.
Typed as a protocol rather than as
:class:~tempest_fastapi_sdk.settings.TaskIQSettings so a service
composing its own Settings from the mixins passes without an
import cycle, and so a test can hand over a plain object.
Every member is a read-only @property. A bare annotation in a
Protocol declares a settable attribute, and
:class:~tempest_fastapi_sdk.settings.BaseAppSettings is
frozen=True — so mypy rejected the very Settings the mixins
build (expected settable variable, got read-only attribute) and
the documented TaskQueue.from_settings(Settings()) needed a
type: ignore. A property accepts both the frozen settings and a
plain object with ordinary attributes.
Attributes:
| Name | Type | Description |
|---|---|---|
TASKIQ_BROKER_URL |
str
|
Broker URL. Empty selects the in-memory broker, which is the shape a test suite and a dev box without Redis actually run in. |
TASKIQ_RESULT_BACKEND_URL |
str | None
|
Where task results go.
|
TASKIQ_STORE_RESULTS |
bool
|
Whether results are stored at all.
|
TASKIQ_RESULT_TTL_SECONDS |
int
|
Seconds a stored result
survives; |
LifecycleResource
¶
Bases: Protocol
Anything the queue can open on startup and close on shutdown.
:class:~tempest_fastapi_sdk.db.AsyncDatabaseManager,
:class:~tempest_fastapi_sdk.queue.MessageBroker and
:class:~tempest_fastapi_sdk.storage.AsyncMinIOClient all satisfy
it, which is what makes resources=[db, broker] work without the
SDK naming any of them.
LifecycleScope
module-attribute
¶
Which process a lifecycle hook runs in.
"worker" is the taskiq worker process, "client" is whoever
calls :meth:TaskQueue.connect (typically the web application's
lifespan), "both" is either. TaskQueue.memory() runs both sides
in one process, so a worker-scoped hook fires there as well.
ResultSerializer
module-attribute
¶
How stored task results are encoded in Redis.
"json" (the default) stores data only. "pickle" is what
taskiq_redis uses on its own, and reading a pickled value runs whatever
code the stored bytes name: anyone able to write the result keys (a
co-tenant on a shared Redis, a leaked credential) gets code execution in the
process that reads the result. It stays available as an explicit opt-in for
a Redis nobody else can write.
Hook
module-attribute
¶
A lifecycle callback taking no arguments. Sync or async.
TERMINAL_JOB_STATUSES
module-attribute
¶
TERMINAL_JOB_STATUSES: frozenset[str] = frozenset(
{
JobStatusEnum.DONE.value,
JobStatusEnum.FAILED.value,
JobStatusEnum.CANCELLED.value,
}
)
Statuses a job never leaves: the poll stops, the payload is gone.
STALE_JOB_ERROR
module-attribute
¶
STALE_JOB_ERROR: str = "The worker stopped responding while this job was running, and the claim budget is spent."
error written by :meth:JobStore.reclaim_stale when it gives up.
A constant rather than a per-row message because the sweep is a single
UPDATE and interpolating each row's attempt count into it would mean
reading the rows first — the read-then-write shape this module avoids.
STORE_OWNED_JOB_COLUMNS
module-attribute
¶
STORE_OWNED_JOB_COLUMNS: frozenset[str] = frozenset(
{
"id",
"is_active",
"created_at",
"updated_at",
"kind",
"status",
"stage",
"progress",
"params",
"payload",
"result_id",
"error",
"attempts",
"max_attempts",
"started_at",
"finished_at",
}
)
Columns of :class:BaseJobModel that :meth:JobStore.succeed refuses in values.
Every column the abstract model declares — its own and the four it
inherits from :class:~tempest_fastapi_sdk.db.model.BaseModel. Each one
either is a transition the store owns (status, finished_at,
progress, payload, attempts), has a parameter of its own
(result_id), or is identity (id, kind, created_at).
values exists for the columns a project adds on its subclass, so
letting it reach these would make succeed able to write a DONE row
that says RUNNING. A test pins this set against a concrete model, so a
column added to :class:BaseJobModel fails there instead of becoming
writable by accident.
make_job_admin_model
¶
make_job_admin_model(
model: type[BaseJobModel], *, can_delete: bool = False
) -> AdminModel[Any]
Build a read-mostly :class:AdminModel over a job table.
Register the result on your
:class:~tempest_fastapi_sdk.admin.AdminSite and the admin gets the
list half of the task panel for free — pagination, filtering, sorting
and CSV/JSON export over the same rows the workers write. Symmetric to
:func:~tempest_fastapi_sdk.tasks.make_dead_letter_admin_model, which
does the same for terminal failures.
Create and edit are off: a job row is a record of what a worker did, and an operator typing a new one describes work nobody will run. Deleting is off by default for the same reason, and available for the retention sweep an operator does want.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
type[BaseJobModel]
|
The concrete job table. |
required |
can_delete
|
bool
|
Whether the admin may delete rows. Defaults to
|
False
|
Returns:
| Type | Description |
|---|---|
AdminModel[Any]
|
AdminModel[Any]: A preconfigured admin registration (no |
AdminModel[Any]
|
create/edit). The admin package is imported under |
AdminModel[Any]
|
|
AdminModel[Any]
|
imports without it. |