taskferry-cloudtasks 0.2.0__tar.gz → 0.3.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,38 @@
1
+ # Changelog
2
+
3
+ All notable changes to `taskferry-cloudtasks` are documented here.
4
+ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and
5
+ this project adheres to [Semantic Versioning](https://semver.org/).
6
+
7
+ ## Unreleased
8
+
9
+ ## [0.3.1] — 2026-11-27
10
+
11
+ ### Added
12
+
13
+ - `ATTEMPT_COUNT` through `get_task()` while Cloud Tasks retains the task, and
14
+ `DELETE_PENDING` through `delete_task()` for scheduled or dispatched tasks.
15
+ - Current attempt propagation from Cloud Tasks retry headers into execution
16
+ context.
17
+
18
+ ### Changed
19
+
20
+ - Keep `STATE`, `RESULT`, and `CANCEL` unadvertised; attempt inspection and
21
+ pending-task deletion do not provide those semantics.
22
+ - Align `taskferry_cloudtasks.__version__` with the distribution version `0.3.1`.
23
+
24
+ ## [0.3.0] — 2026-09-19
25
+
26
+ ### Added
27
+
28
+ - **Native async submit** via `CloudTasksAsyncClient`. `asubmit` creates the task
29
+ through the async client (injected, or built from the existing `gcp` extra),
30
+ skipping the worker thread, and falls back to the thread path when the SDK is
31
+ absent. No new dependency — the async client ships with `google-cloud-tasks`.
32
+
33
+ ## [0.2.0] — 2026-07-26
34
+
35
+ ### Added
36
+
37
+ - Initial release of the Google Cloud Tasks backend, implementing Taskferry's
38
+ framework-independent `TaskBackend` contract.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: taskferry-cloudtasks
3
- Version: 0.2.0
3
+ Version: 0.3.1
4
4
  Summary: Google Cloud Tasks backend for Taskferry — push-based serverless tasks.
5
5
  Project-URL: Homepage, https://github.com/xiidigital/taskferry
6
6
  Project-URL: Documentation, https://taskferry.dev
@@ -110,10 +110,23 @@ that is what makes it portable, and it is why this part is yours.
110
110
  | ---------- | :-------: | --- |
111
111
  | `SUBMIT` · `DELAY` · `RETRY` | yes | `create_task`, `schedule_time`, queue retry config |
112
112
  | `DEDUPLICATION` | yes | task names are unique per queue for a bounded window |
113
- | `STATE` · `RESULT` | **no** | Cloud Tasks reports nothing per task after creation |
113
+ | `EXECUTION_CONTEXT` | yes | The push request includes the task identity and retry count |
114
+ | `ATTEMPT_COUNT` | yes, while retained | `get_task()` reports `dispatch_count` for an existing task |
115
+ | `DELETE_PENDING` | yes | `delete_task()` removes a scheduled or dispatched delivery |
116
+ | `STATE` · `RESULT` · `CANCEL` | **no** | No durable outcome store, return value, or guaranteed interruption |
114
117
 
115
118
  A handle refuses `status()` here instead of returning a plausible `UNKNOWN`
116
- forever. Record what you need in your own database, where it is actually true.
119
+ forever. `handle.attempt_count()` is a separate, temporary query: Cloud Tasks
120
+ returns `dispatch_count` only while the task exists. Successfully completed or
121
+ exhausted tasks are deleted, so this is neither durable state nor a result.
122
+ `handle.delete_pending()` calls Cloud Tasks `delete_task`; it removes a scheduled
123
+ or dispatched task, but it cannot promise to stop a handler that has already
124
+ started. This is deliberately distinct from `cancel()`.
125
+
126
+ The push request's `X-CloudTasks-TaskRetryCount` header is passed through as the
127
+ current Django `TaskContext.attempt` (`retry count + 1`). Cloud Tasks does not
128
+ provide a worker id or the original enqueue timestamp to this adapter. Record
129
+ durable progress, return values, or retry history in application-owned storage.
117
130
 
118
131
  ## License
119
132
 
@@ -86,10 +86,23 @@ that is what makes it portable, and it is why this part is yours.
86
86
  | ---------- | :-------: | --- |
87
87
  | `SUBMIT` · `DELAY` · `RETRY` | yes | `create_task`, `schedule_time`, queue retry config |
88
88
  | `DEDUPLICATION` | yes | task names are unique per queue for a bounded window |
89
- | `STATE` · `RESULT` | **no** | Cloud Tasks reports nothing per task after creation |
89
+ | `EXECUTION_CONTEXT` | yes | The push request includes the task identity and retry count |
90
+ | `ATTEMPT_COUNT` | yes, while retained | `get_task()` reports `dispatch_count` for an existing task |
91
+ | `DELETE_PENDING` | yes | `delete_task()` removes a scheduled or dispatched delivery |
92
+ | `STATE` · `RESULT` · `CANCEL` | **no** | No durable outcome store, return value, or guaranteed interruption |
90
93
 
91
94
  A handle refuses `status()` here instead of returning a plausible `UNKNOWN`
92
- forever. Record what you need in your own database, where it is actually true.
95
+ forever. `handle.attempt_count()` is a separate, temporary query: Cloud Tasks
96
+ returns `dispatch_count` only while the task exists. Successfully completed or
97
+ exhausted tasks are deleted, so this is neither durable state nor a result.
98
+ `handle.delete_pending()` calls Cloud Tasks `delete_task`; it removes a scheduled
99
+ or dispatched task, but it cannot promise to stop a handler that has already
100
+ started. This is deliberately distinct from `cancel()`.
101
+
102
+ The push request's `X-CloudTasks-TaskRetryCount` header is passed through as the
103
+ current Django `TaskContext.attempt` (`retry count + 1`). Cloud Tasks does not
104
+ provide a worker id or the original enqueue timestamp to this adapter. Record
105
+ durable progress, return values, or retry history in application-owned storage.
93
106
 
94
107
  ## License
95
108
 
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "taskferry-cloudtasks"
7
- version = "0.2.0"
7
+ version = "0.3.1"
8
8
  description = "Google Cloud Tasks backend for Taskferry — push-based serverless tasks."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.12"
@@ -42,7 +42,7 @@ from __future__ import annotations
42
42
  from .backend import CLOUD_TASKS_CAPABILITIES, CloudTasksBackend, make_backend
43
43
  from .receiver import handle_request, parse_request
44
44
 
45
- __version__ = "0.2.0"
45
+ __version__ = "0.3.1"
46
46
 
47
47
  __all__ = [
48
48
  "CLOUD_TASKS_CAPABILITIES",
@@ -7,9 +7,11 @@ Advertised: ``SUBMIT``, ``DELAY`` (``schedule_time``), ``RETRY`` (the queue's ow
7
7
  retry configuration), ``DEDUPLICATION`` (a task *name* is unique per queue, which
8
8
  is real deduplication with a documented window).
9
9
 
10
- Not advertised: ``STATE`` and ``RESULT``. Cloud Tasks is fire-and-forget — once a
11
- task is created there is no per-task status to read and no place a return value
12
- is kept. A handle from this backend therefore raises
10
+ Not advertised: ``STATE``, ``RESULT`` or ``CANCEL``. Cloud Tasks retains a task
11
+ while it is scheduled or retrying, so the adapter separately exposes its
12
+ ``dispatch_count`` and can delete the pending task resource. Those operations do
13
+ not provide durable lifecycle state, a return value, or guaranteed interruption
14
+ of an already-running handler. A handle from this backend therefore raises
13
15
  :class:`~taskferry.errors.UnsupportedCapability` on ``status()`` rather than
14
16
  returning a plausible-looking ``UNKNOWN`` forever, and an application that needs
15
17
  to know whether the work happened records that itself, in its own database, where
@@ -24,6 +26,8 @@ by accident.
24
26
  from __future__ import annotations
25
27
 
26
28
  import json
29
+ from collections.abc import AsyncIterator
30
+ from contextlib import asynccontextmanager
27
31
  from datetime import UTC, datetime
28
32
  from typing import Any
29
33
 
@@ -34,6 +38,7 @@ from taskferry.envelope import ENVELOPE_VERSION, Envelope, build_envelope
34
38
  from taskferry.errors import ConfigurationError, SubmissionError
35
39
  from taskferry.execution import (
36
40
  Execution,
41
+ ExecutionId,
37
42
  ExecutionKind,
38
43
  ExecutionState,
39
44
  new_execution_id,
@@ -50,6 +55,9 @@ CLOUD_TASKS_CAPABILITIES = frozenset(
50
55
  Capability.DELAY,
51
56
  Capability.RETRY,
52
57
  Capability.DEDUPLICATION,
58
+ Capability.EXECUTION_CONTEXT,
59
+ Capability.ATTEMPT_COUNT,
60
+ Capability.DELETE_PENDING,
53
61
  }
54
62
  )
55
63
 
@@ -90,6 +98,7 @@ class CloudTasksBackend(BaseBackend):
90
98
  service_account_email: str | None = None,
91
99
  audience: str | None = None,
92
100
  client: Any = None,
101
+ async_client: Any = None,
93
102
  name: str = "cloudtasks",
94
103
  ) -> None:
95
104
  missing = [
@@ -110,7 +119,9 @@ class CloudTasksBackend(BaseBackend):
110
119
  self._service_account_email = service_account_email
111
120
  self._audience = audience
112
121
  self._client = client
122
+ self._async_client = async_client
113
123
  self._name = name
124
+ self._provider_ids: dict[str, str] = {}
114
125
 
115
126
  @property
116
127
  def name(self) -> str:
@@ -143,12 +154,18 @@ class CloudTasksBackend(BaseBackend):
143
154
  return str(builder(self._project, self._location, queue))
144
155
  return f"projects/{self._project}/locations/{self._location}/queues/{queue}"
145
156
 
157
+ def _queue_path_str(self, queue: str) -> str:
158
+ """Fully-qualified queue path without needing a client (async path)."""
159
+ return f"projects/{self._project}/locations/{self._location}/queues/{queue}"
160
+
146
161
  # -- submission -------------------------------------------------------------- #
147
- def _submit(self, spec: ExecutionSpec) -> Execution:
148
- assert isinstance(spec, TaskSpec)
162
+ def _queue_for(self, spec: TaskSpec) -> str:
149
163
  options = spec.options_for("cloudtasks")
150
- queue = str(options.get("queue") or spec.queue or self._queue)
164
+ return str(options.get("queue") or spec.queue or self._queue)
151
165
 
166
+ def _build_task(self, spec: TaskSpec, queue_path: str) -> dict[str, Any]:
167
+ """The Cloud Tasks task body. Pure, shared by the sync and async paths."""
168
+ options = spec.options_for("cloudtasks")
152
169
  http_request: dict[str, Any] = {
153
170
  "http_method": "POST",
154
171
  "url": self._url,
@@ -175,21 +192,15 @@ class CloudTasksBackend(BaseBackend):
175
192
  # A named task is refused if the name was used recently — Cloud Tasks'
176
193
  # own, real, time-bounded deduplication. The window is Google's, not
177
194
  # ours, and this is not an exactly-once promise.
178
- task["name"] = f"{self.queue_path(queue)}/tasks/{_safe_name(spec.idempotency_key)}"
179
-
180
- try:
181
- created = self._tasks().create_task(
182
- request={"parent": self.queue_path(queue), "task": task}
183
- )
184
- except Exception as exc:
185
- raise SubmissionError(
186
- f"Cloud Tasks could not create a task for {spec.task!r} on queue {queue!r}: {exc}",
187
- backend=self._name,
188
- ) from exc
195
+ task["name"] = f"{queue_path}/tasks/{_safe_name(spec.idempotency_key)}"
196
+ return task
189
197
 
198
+ def _execution_from(
199
+ self, spec: TaskSpec, created: Any, queue_path: str, queue: str
200
+ ) -> Execution:
190
201
  external_id = getattr(created, "name", None)
191
- return Execution(
192
- id=new_execution_id(ExecutionKind.TASK),
202
+ execution = Execution(
203
+ id=spec.execution_id or new_execution_id(ExecutionKind.TASK),
193
204
  kind=ExecutionKind.TASK,
194
205
  backend=self._name,
195
206
  # QUEUED is the last thing this backend can honestly observe: Cloud
@@ -203,11 +214,86 @@ class CloudTasksBackend(BaseBackend):
203
214
  provider="gcp",
204
215
  provider_id=str(external_id) if external_id else None,
205
216
  region=self._location,
206
- resource=self.queue_path(queue),
217
+ resource=queue_path,
207
218
  labels=dict(spec.labels),
208
219
  ),
209
220
  metadata={"queue": queue, "url": self._url},
210
221
  )
222
+ if external_id:
223
+ self._provider_ids[str(execution.id)] = str(external_id)
224
+ return execution
225
+
226
+ def _submit(self, spec: ExecutionSpec) -> Execution:
227
+ assert isinstance(spec, TaskSpec)
228
+ queue = self._queue_for(spec)
229
+ queue_path = self.queue_path(queue)
230
+ task = self._build_task(spec, queue_path)
231
+ try:
232
+ created = self._tasks().create_task(request={"parent": queue_path, "task": task})
233
+ except Exception as exc:
234
+ raise SubmissionError(
235
+ f"Cloud Tasks could not create a task for {spec.task!r} on queue {queue!r}: {exc}",
236
+ backend=self._name,
237
+ ) from exc
238
+ return self._execution_from(spec, created, queue_path, queue)
239
+
240
+ # -- native async (CloudTasksAsyncClient) ------------------------------------- #
241
+ @asynccontextmanager
242
+ async def _async_tasks(self) -> AsyncIterator[Any]:
243
+ if self._async_client is not None:
244
+ yield self._async_client
245
+ return
246
+ client = _async_tasks_client()
247
+ try:
248
+ yield client
249
+ finally: # pragma: no cover - real gRPC client only
250
+ close = getattr(getattr(client, "transport", None), "close", None)
251
+ if callable(close):
252
+ await close()
253
+
254
+ async def asubmit(self, spec: ExecutionSpec) -> Execution:
255
+ """Native async submit via ``CloudTasksAsyncClient``, else the thread path."""
256
+ if self._async_client is None and not _has_cloud_tasks():
257
+ return await super().asubmit(spec)
258
+ assert isinstance(spec, TaskSpec)
259
+ self.validate(spec)
260
+ self.hooks.before_submit(spec, self.name)
261
+ queue = self._queue_for(spec)
262
+ queue_path = self._queue_path_str(queue)
263
+ task = self._build_task(spec, queue_path)
264
+ try:
265
+ async with self._async_tasks() as client:
266
+ created = await client.create_task(request={"parent": queue_path, "task": task})
267
+ execution = self._execution_from(spec, created, queue_path, queue)
268
+ except Exception as exc:
269
+ error = SubmissionError(
270
+ f"Cloud Tasks could not create a task for {spec.task!r} on queue {queue!r}: {exc}",
271
+ backend=self._name,
272
+ )
273
+ self.hooks.on_submit_error(spec, self.name, error)
274
+ raise error from exc
275
+ self.hooks.after_submit(spec, execution)
276
+ return execution
277
+
278
+ def _task_name(self, execution_id: ExecutionId) -> str:
279
+ value = str(execution_id)
280
+ return self._provider_ids.get(value, value)
281
+
282
+ def _attempt_count(self, execution_id: ExecutionId) -> int:
283
+ """Return Cloud Tasks dispatch_count while the task is retained by Google."""
284
+ task = self._tasks().get_task(request={"name": self._task_name(execution_id)})
285
+ count = (
286
+ task.get("dispatch_count")
287
+ if isinstance(task, dict)
288
+ else getattr(task, "dispatch_count", None)
289
+ )
290
+ if count is None:
291
+ raise RuntimeError("Cloud Tasks get_task response did not include dispatch_count")
292
+ return int(count)
293
+
294
+ def _delete_pending(self, execution_id: ExecutionId) -> None:
295
+ """Delete a scheduled or dispatched task; an active handler may continue."""
296
+ self._tasks().delete_task(request={"name": self._task_name(execution_id)})
211
297
 
212
298
  @staticmethod
213
299
  def _correlation_headers(correlation: Correlation | None) -> dict[str, str]:
@@ -226,6 +312,29 @@ def _safe_name(key: str) -> str:
226
312
  return cleaned[:500] or "taskferry"
227
313
 
228
314
 
315
+ def _has_cloud_tasks() -> bool:
316
+ """Whether the Google Cloud Tasks SDK is importable, without importing it."""
317
+ from importlib.util import find_spec
318
+
319
+ try:
320
+ # A dotted name raises (not returns None) when a parent package like
321
+ # ``google`` is absent, so both outcomes mean "not installed".
322
+ return find_spec("google.cloud.tasks_v2") is not None
323
+ except ModuleNotFoundError:
324
+ return False
325
+
326
+
327
+ def _async_tasks_client() -> Any:
328
+ """A lazily-built ``CloudTasksAsyncClient``, with an actionable error."""
329
+ try:
330
+ from google.cloud import tasks_v2
331
+ except ImportError as exc: # pragma: no cover - depends on the environment
332
+ raise ConfigurationError(
333
+ "the Cloud Tasks backend needs the Google SDK: pip install 'taskferry-cloudtasks[gcp]'"
334
+ ) from exc
335
+ return tasks_v2.CloudTasksAsyncClient()
336
+
337
+
229
338
  def make_backend(**options: Any) -> CloudTasksBackend:
230
339
  """Entry point for ``{"factory": "cloudtasks", ...}`` configuration."""
231
340
  return CloudTasksBackend(
@@ -236,6 +345,7 @@ def make_backend(**options: Any) -> CloudTasksBackend:
236
345
  service_account_email=options.get("service_account_email"),
237
346
  audience=options.get("audience"),
238
347
  client=options.get("client"),
348
+ async_client=options.get("async_client"),
239
349
  name=str(options.get("name", "cloudtasks")),
240
350
  )
241
351
 
@@ -53,11 +53,14 @@ from __future__ import annotations
53
53
 
54
54
  import json
55
55
  from collections.abc import Mapping
56
+ from datetime import UTC, datetime
56
57
  from typing import Any
57
58
 
58
59
  from taskferry.core.correlation import Correlation, use_correlation
59
60
  from taskferry.envelope import read_envelope
60
61
  from taskferry.errors import SerializationError
62
+ from taskferry.execution import ExecutionId
63
+ from taskferry.execution_context import TaskExecutionContext, use_task_execution
61
64
  from taskferry.functions import FunctionRegistry, is_async_callable
62
65
 
63
66
  from .backend import CloudTasksMessage
@@ -106,11 +109,24 @@ def handle_request(
106
109
  kwargs = dict(message.get("kwargs") or {})
107
110
 
108
111
  with use_correlation(_correlation_from(message, headers)):
109
- if is_async_callable(func):
110
- import asyncio
111
-
112
- return asyncio.run(func(*args, **kwargs))
113
- return func(*args, **kwargs)
112
+ normalized_headers = {key.lower(): value for key, value in (headers or {}).items()}
113
+ retry_count = normalized_headers.get("x-cloudtasks-taskretrycount")
114
+ attempt = None if retry_count is None else int(retry_count) + 1
115
+ execution_context = TaskExecutionContext(
116
+ execution_id=(
117
+ None
118
+ if not message.get("execution_id")
119
+ else ExecutionId(str(message["execution_id"]))
120
+ ),
121
+ attempt=attempt,
122
+ started_at=datetime.now(UTC),
123
+ )
124
+ with use_task_execution(execution_context):
125
+ if is_async_callable(func):
126
+ import asyncio
127
+
128
+ return asyncio.run(func(*args, **kwargs))
129
+ return func(*args, **kwargs)
114
130
 
115
131
 
116
132
  def _correlation_from(message: CloudTasksMessage, headers: Mapping[str, str] | None) -> Correlation:
@@ -1,12 +0,0 @@
1
- # Changelog
2
-
3
- All notable changes to `taskferry-cloudtasks` are documented here.
4
- The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and
5
- this project adheres to [Semantic Versioning](https://semver.org/).
6
-
7
- ## [0.2.0] — 2026-07-26
8
-
9
- ### Added
10
-
11
- - Initial release, extracted from the Django-coupled backends of `taskferry-django` 0.1
12
- and rebuilt against the framework-agnostic Taskferry ports.