taskferry-cloudrun 0.2.0__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,34 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ .eggs/
6
+
7
+ # Build artifacts
8
+ dist/
9
+ build/
10
+ *.whl
11
+ *.tar.gz
12
+
13
+ # Environments
14
+ .venv/
15
+ .venv-*/
16
+ .env
17
+
18
+ # Tooling caches
19
+ .mypy_cache/
20
+ .ruff_cache/
21
+ .pytest_cache/
22
+ .coverage
23
+ htmlcov/
24
+ coverage.xml
25
+ node_modules/
26
+
27
+ # uv
28
+ uv.lock
29
+
30
+ # OS / editors
31
+ .DS_Store
32
+ .idea/
33
+ .vscode/
34
+ site/
@@ -0,0 +1,12 @@
1
+ # Changelog
2
+
3
+ All notable changes to `taskferry-cloudrun` 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.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or Derivative
95
+ Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,103 @@
1
+ Metadata-Version: 2.5
2
+ Name: taskferry-cloudrun
3
+ Version: 0.2.0
4
+ Summary: Google Cloud Run Jobs backend for Taskferry — serverless batch workloads.
5
+ Project-URL: Homepage, https://github.com/xiidigital/taskferry
6
+ Project-URL: Documentation, https://taskferry.dev
7
+ Project-URL: Source, https://github.com/xiidigital/taskferry
8
+ Author: Taskferry authors
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: batch,cloud-run,gcp,jobs,taskferry
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.12
20
+ Requires-Dist: taskferry<0.3,>=0.2
21
+ Provides-Extra: gcp
22
+ Requires-Dist: google-cloud-run>=0.10; extra == 'gcp'
23
+ Description-Content-Type: text/markdown
24
+
25
+ # taskferry-cloudrun
26
+
27
+ Run [Taskferry](https://github.com/xiidigital/taskferry) jobs on **Google Cloud Run
28
+ Jobs** — serverless, run-to-completion container workloads.
29
+
30
+ ```mermaid
31
+ flowchart LR
32
+ APP["Application"]
33
+ TP["Taskferry"]
34
+ AD["taskferry-cloudrun"]
35
+ CR["Cloud Run Jobs"]
36
+ C["container"]
37
+
38
+ APP --> TP --> AD --> CR --> C
39
+ ```
40
+
41
+ This is the adapter that shows why Task and Job are separate primitives. A Cloud
42
+ Run Job has its own image, its own resource envelope, its own timeout and scales
43
+ to zero — none of which is "a task that takes a while".
44
+
45
+ ## Install
46
+
47
+ ```bash
48
+ pip install 'taskferry-cloudrun[gcp]'
49
+ ```
50
+
51
+ ## Use
52
+
53
+ ```python
54
+ from taskferry import Taskferry, Resources
55
+
56
+ runtime = Taskferry.from_mapping(
57
+ {
58
+ "backends": {
59
+ "heavy": {
60
+ "factory": "cloudrun",
61
+ "project": "my-project",
62
+ "location": "europe-west1",
63
+ }
64
+ },
65
+ "defaults": {"job": "heavy"},
66
+ }
67
+ )
68
+
69
+ handle = runtime.jobs.submit(
70
+ "build-cog",
71
+ args=["--input", "gs://bucket/scene.tif"],
72
+ env={"GDAL_CACHEMAX": "512"},
73
+ timeout=3600,
74
+ )
75
+ print(handle.status())
76
+ ```
77
+
78
+ ## Capabilities
79
+
80
+ | Capability | Supported | Why |
81
+ | ---------- | :-------: | --- |
82
+ | `SUBMIT` · `STATE` · `CANCEL` · `LOGS` | yes | the Executions API |
83
+ | `ENVIRONMENT` · `PARALLELISM` · `TIMEOUT` · `RETRY` | yes | per-execution overrides |
84
+ | `CPU` · `MEMORY` · `GPU` | **no** | they live on the Job resource, not the execution |
85
+
86
+ A spec asking for `Resources(gpu=1)` is rejected at submit time rather than run
87
+ on a CPU. Route GPU work at a backend that really allocates GPUs
88
+ (`taskferry-jobs[kubernetes]`, `taskferry-jobs[aws]`).
89
+
90
+ Deploy the Job resource itself with Terraform or `gcloud`; Taskferry starts
91
+ executions of it.
92
+
93
+ ## Testing
94
+
95
+ Both clients are injectable, so the whole suite runs with no GCP account:
96
+
97
+ ```python
98
+ CloudRunJobBackend(project="p", location="eu", jobs_client=FakeJobs())
99
+ ```
100
+
101
+ ## License
102
+
103
+ Apache-2.0.
@@ -0,0 +1,79 @@
1
+ # taskferry-cloudrun
2
+
3
+ Run [Taskferry](https://github.com/xiidigital/taskferry) jobs on **Google Cloud Run
4
+ Jobs** — serverless, run-to-completion container workloads.
5
+
6
+ ```mermaid
7
+ flowchart LR
8
+ APP["Application"]
9
+ TP["Taskferry"]
10
+ AD["taskferry-cloudrun"]
11
+ CR["Cloud Run Jobs"]
12
+ C["container"]
13
+
14
+ APP --> TP --> AD --> CR --> C
15
+ ```
16
+
17
+ This is the adapter that shows why Task and Job are separate primitives. A Cloud
18
+ Run Job has its own image, its own resource envelope, its own timeout and scales
19
+ to zero — none of which is "a task that takes a while".
20
+
21
+ ## Install
22
+
23
+ ```bash
24
+ pip install 'taskferry-cloudrun[gcp]'
25
+ ```
26
+
27
+ ## Use
28
+
29
+ ```python
30
+ from taskferry import Taskferry, Resources
31
+
32
+ runtime = Taskferry.from_mapping(
33
+ {
34
+ "backends": {
35
+ "heavy": {
36
+ "factory": "cloudrun",
37
+ "project": "my-project",
38
+ "location": "europe-west1",
39
+ }
40
+ },
41
+ "defaults": {"job": "heavy"},
42
+ }
43
+ )
44
+
45
+ handle = runtime.jobs.submit(
46
+ "build-cog",
47
+ args=["--input", "gs://bucket/scene.tif"],
48
+ env={"GDAL_CACHEMAX": "512"},
49
+ timeout=3600,
50
+ )
51
+ print(handle.status())
52
+ ```
53
+
54
+ ## Capabilities
55
+
56
+ | Capability | Supported | Why |
57
+ | ---------- | :-------: | --- |
58
+ | `SUBMIT` · `STATE` · `CANCEL` · `LOGS` | yes | the Executions API |
59
+ | `ENVIRONMENT` · `PARALLELISM` · `TIMEOUT` · `RETRY` | yes | per-execution overrides |
60
+ | `CPU` · `MEMORY` · `GPU` | **no** | they live on the Job resource, not the execution |
61
+
62
+ A spec asking for `Resources(gpu=1)` is rejected at submit time rather than run
63
+ on a CPU. Route GPU work at a backend that really allocates GPUs
64
+ (`taskferry-jobs[kubernetes]`, `taskferry-jobs[aws]`).
65
+
66
+ Deploy the Job resource itself with Terraform or `gcloud`; Taskferry starts
67
+ executions of it.
68
+
69
+ ## Testing
70
+
71
+ Both clients are injectable, so the whole suite runs with no GCP account:
72
+
73
+ ```python
74
+ CloudRunJobBackend(project="p", location="eu", jobs_client=FakeJobs())
75
+ ```
76
+
77
+ ## License
78
+
79
+ Apache-2.0.
@@ -0,0 +1,41 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "taskferry-cloudrun"
7
+ version = "0.2.0"
8
+ description = "Google Cloud Run Jobs backend for Taskferry — serverless batch workloads."
9
+ readme = "README.md"
10
+ requires-python = ">=3.12"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Taskferry authors" }]
14
+ keywords = ["taskferry", "gcp", "cloud-run", "jobs", "batch"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Developers",
18
+ "License :: OSI Approved :: Apache Software License",
19
+ "Programming Language :: Python :: 3 :: Only",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Typing :: Typed",
23
+ ]
24
+ dependencies = ["taskferry>=0.2,<0.3"]
25
+
26
+ [project.optional-dependencies]
27
+ gcp = ["google-cloud-run>=0.10"]
28
+
29
+ [project.entry-points."taskferry.backends"]
30
+ cloudrun = "taskferry_cloudrun:make_backend"
31
+
32
+ [project.urls]
33
+ Homepage = "https://github.com/xiidigital/taskferry"
34
+ Documentation = "https://taskferry.dev"
35
+ Source = "https://github.com/xiidigital/taskferry"
36
+
37
+ [tool.hatch.build.targets.wheel]
38
+ packages = ["src/taskferry_cloudrun"]
39
+
40
+ [tool.hatch.build.targets.sdist]
41
+ include = ["src", "README.md", "CHANGELOG.md", "LICENSE"]
@@ -0,0 +1,63 @@
1
+ """Taskferry on Cloud Run Jobs — serverless, run-to-completion workloads.
2
+
3
+ ```mermaid
4
+ flowchart LR
5
+ APP["Application"]
6
+ TP["Taskferry"]
7
+ AD["taskferry_cloudrun"]
8
+ CR["Cloud Run Jobs"]
9
+ C["container"]
10
+
11
+ APP --> TP --> AD --> CR --> C
12
+ ```
13
+
14
+ This is the adapter that proves Task and Job are different primitives. A Cloud
15
+ Run Job has its own container image, its own CPU/memory envelope, its own
16
+ timeout, and it scales to zero when nothing is running. None of that is
17
+ expressible as "a task that takes a while", and no task engine should be asked to
18
+ grow container semantics to pretend otherwise.
19
+
20
+ from taskferry import Taskferry, Resources
21
+
22
+ runtime = Taskferry.from_mapping({
23
+ "backends": {"heavy": {
24
+ "factory": "cloudrun", "project": "my-project", "location": "europe-west1",
25
+ }},
26
+ "defaults": {"job": "heavy"},
27
+ })
28
+
29
+ handle = runtime.jobs.submit(
30
+ "build-cog",
31
+ args=["--input", "gs://bucket/scene.tif"],
32
+ resources=Resources(cpu="4000m", memory="16Gi"),
33
+ )
34
+
35
+ ``google-cloud-run`` is imported lazily, inside the method that needs a client,
36
+ so importing this package — never mind ``taskferry`` — costs nothing. Clients are
37
+ injectable, so the entire test suite runs with no GCP account and no credentials.
38
+
39
+ Cloud Run runs a **pre-declared** Job resource with per-execution overrides. The
40
+ image, CPU and memory live in the Job definition you deploy with Terraform or
41
+ ``gcloud``; a submission overrides args, env, task count and timeout. That is why
42
+ this backend advertises ``ENVIRONMENT``, ``PARALLELISM`` and ``TIMEOUT`` but not
43
+ ``CPU``, ``MEMORY`` or ``GPU`` — see :mod:`taskferry_cloudrun.backend`.
44
+ """
45
+
46
+ from __future__ import annotations
47
+
48
+ from .backend import (
49
+ CLOUD_RUN_CAPABILITIES,
50
+ CloudRunJobBackend,
51
+ make_backend,
52
+ map_execution_state,
53
+ )
54
+
55
+ __version__ = "0.2.0"
56
+
57
+ __all__ = [
58
+ "CLOUD_RUN_CAPABILITIES",
59
+ "CloudRunJobBackend",
60
+ "__version__",
61
+ "make_backend",
62
+ "map_execution_state",
63
+ ]
@@ -0,0 +1,386 @@
1
+ """The Cloud Run Jobs `JobBackend`.
2
+
3
+ State mapping
4
+ -------------
5
+
6
+ Cloud Run reports an execution as a set of counters, not a status field, so the
7
+ portable state is derived:
8
+
9
+ ```mermaid
10
+ flowchart TD
11
+ E["Execution counters<br/>task_count · succeeded · failed · running · cancelled"]
12
+
13
+ E -->|"cancelled > 0"| C["CANCELLED"]
14
+ E -->|"completion_time & failed > 0"| F["FAILED"]
15
+ E -->|"completion_time & succeeded >= task_count"| S["SUCCEEDED"]
16
+ E -->|"no completion_time & running > 0"| R["RUNNING"]
17
+ E -->|"no completion_time & running = 0"| Q["QUEUED"]
18
+ ```
19
+
20
+ :func:`map_execution_state` is a pure function of those counters, so the mapping
21
+ is unit-tested against plain objects — no emulator, no project, no credentials.
22
+
23
+ Capabilities, and why they stop where they do
24
+ ---------------------------------------------
25
+
26
+ Cloud Run's per-execution ``overrides`` cover container args, env, task count and
27
+ timeout. They do **not** cover CPU, memory or GPU: those belong to the Job
28
+ resource, which you deploy separately. So this backend advertises ``ENVIRONMENT``,
29
+ ``PARALLELISM`` and ``TIMEOUT``, and deliberately does not advertise ``CPU``,
30
+ ``MEMORY`` or ``GPU``.
31
+
32
+ The consequence is exactly the intended one: submitting a spec that asks for
33
+ ``Resources(gpu=1)`` raises :class:`~taskferry.errors.UnsupportedCapability`
34
+ instead of running the workload on a CPU and returning results that look fine.
35
+ Route GPU work at a backend that really allocates GPUs.
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ from datetime import UTC, datetime
41
+ from typing import Any
42
+
43
+ from taskferry.capabilities import Capability, CapabilitySet
44
+ from taskferry.core.provider import ProviderMetadata
45
+ from taskferry.errors import (
46
+ BackendError,
47
+ ConfigurationError,
48
+ ExecutionNotFound,
49
+ SubmissionError,
50
+ )
51
+ from taskferry.execution import (
52
+ Execution,
53
+ ExecutionId,
54
+ ExecutionKind,
55
+ ExecutionResult,
56
+ ExecutionState,
57
+ new_execution_id,
58
+ )
59
+ from taskferry.ports import BaseBackend
60
+ from taskferry.specs import ExecutionSpec, JobSpec
61
+ from taskferry.tracking import ExternalIdIndex, has_prefix
62
+
63
+ CLOUD_RUN_CAPABILITIES = frozenset(
64
+ {
65
+ Capability.SUBMIT,
66
+ Capability.STATE,
67
+ Capability.CANCEL,
68
+ Capability.LOGS,
69
+ Capability.TIMEOUT,
70
+ Capability.PARALLELISM,
71
+ Capability.ENVIRONMENT,
72
+ Capability.RETRY,
73
+ }
74
+ )
75
+
76
+
77
+ def map_execution_state(execution: Any) -> tuple[ExecutionState, str | None]:
78
+ """Map a Cloud Run ``Execution`` to a portable state and error message.
79
+
80
+ Reads every field defensively via :func:`getattr`, which keeps it working
81
+ against both real protobuf messages and the small fakes the tests use, and
82
+ stops a field being renamed upstream from turning into a crash.
83
+ """
84
+ task_count = _count(execution, "task_count")
85
+ succeeded = _count(execution, "succeeded_count")
86
+ failed = _count(execution, "failed_count")
87
+ running = _count(execution, "running_count")
88
+ cancelled = _count(execution, "cancelled_count")
89
+ completion_time = getattr(execution, "completion_time", None)
90
+
91
+ if cancelled > 0:
92
+ return ExecutionState.CANCELLED, None
93
+ if completion_time:
94
+ if failed > 0:
95
+ return ExecutionState.FAILED, f"{failed} of {task_count} task(s) failed"
96
+ if task_count > 0 and succeeded >= task_count:
97
+ return ExecutionState.SUCCEEDED, None
98
+ return ExecutionState.FAILED, "execution completed without all tasks succeeding"
99
+ if running > 0:
100
+ return ExecutionState.RUNNING, None
101
+ # Accepted by Cloud Run, no task running yet: queued, not "unknown".
102
+ return ExecutionState.QUEUED, None
103
+
104
+
105
+ def _count(execution: Any, field: str) -> int:
106
+ try:
107
+ return int(getattr(execution, field, 0) or 0)
108
+ except (TypeError, ValueError): # pragma: no cover - hostile fake
109
+ return 0
110
+
111
+
112
+ class CloudRunJobBackend(BaseBackend):
113
+ """Runs Cloud Run Job executions.
114
+
115
+ Args:
116
+ project: GCP project id.
117
+ location: Region the Job resources live in (``"europe-west1"``).
118
+ jobs_client: Injected ``run_v2.JobsClient``. Built lazily when omitted.
119
+ executions_client: Injected ``run_v2.ExecutionsClient``.
120
+ name: Backend name used in routing and errors.
121
+
122
+ Backend options, under the ``"cloudrun"`` namespace::
123
+
124
+ JobSpec(
125
+ job="build-cog",
126
+ backend_options=BackendOptions({"cloudrun": {
127
+ "job": "projects/p/locations/eu/jobs/other-name", # explicit resource
128
+ }}),
129
+ )
130
+
131
+ Thread-safe: the Google clients are safe to share, and the id map is locked.
132
+ """
133
+
134
+ def __init__(
135
+ self,
136
+ *,
137
+ project: str | None = None,
138
+ location: str | None = None,
139
+ jobs_client: Any = None,
140
+ executions_client: Any = None,
141
+ name: str = "cloudrun",
142
+ tracked_ids: int = 10_000,
143
+ ) -> None:
144
+ if not project or not location:
145
+ raise ConfigurationError(
146
+ "CloudRunJobBackend needs both 'project' and 'location' "
147
+ "(e.g. project='my-project', location='europe-west1')"
148
+ )
149
+ self._project = project
150
+ self._location = location
151
+ self._jobs_client = jobs_client
152
+ self._executions_client = executions_client
153
+ self._name = name
154
+ # Cloud Run names executions itself, so remember which of its names goes
155
+ # with which Taskferry id; a full resource path is accepted directly.
156
+ self._ids = ExternalIdIndex(capacity=tracked_ids, recognises=has_prefix("projects/"))
157
+
158
+ @property
159
+ def name(self) -> str:
160
+ return self._name
161
+
162
+ @property
163
+ def kind(self) -> ExecutionKind:
164
+ return ExecutionKind.JOB
165
+
166
+ @property
167
+ def capabilities(self) -> CapabilitySet:
168
+ return CapabilitySet(CLOUD_RUN_CAPABILITIES, provider=self._name)
169
+
170
+ @property
171
+ def project(self) -> str:
172
+ return self._project
173
+
174
+ @property
175
+ def location(self) -> str:
176
+ return self._location
177
+
178
+ # -- clients (lazy, injectable) --------------------------------------------- #
179
+ def _jobs(self) -> Any:
180
+ if self._jobs_client is None:
181
+ self._jobs_client = _run_v2().JobsClient()
182
+ return self._jobs_client
183
+
184
+ def _executions(self) -> Any:
185
+ if self._executions_client is None:
186
+ self._executions_client = _run_v2().ExecutionsClient()
187
+ return self._executions_client
188
+
189
+ # -- resource names ----------------------------------------------------------- #
190
+ def job_resource(self, spec: JobSpec) -> str:
191
+ """Fully-qualified Cloud Run Job resource this spec targets."""
192
+ override = spec.options_for("cloudrun").get("job")
193
+ if isinstance(override, str) and override:
194
+ return override
195
+ return f"projects/{self._project}/locations/{self._location}/jobs/{spec.job}"
196
+
197
+ # -- submission ---------------------------------------------------------------- #
198
+ def _submit(self, spec: ExecutionSpec) -> Execution:
199
+ assert isinstance(spec, JobSpec)
200
+ request: dict[str, Any] = {"name": self.job_resource(spec)}
201
+ overrides = self._overrides(spec)
202
+ if overrides:
203
+ request["overrides"] = overrides
204
+
205
+ try:
206
+ operation = self._jobs().run_job(request=request)
207
+ except Exception as exc:
208
+ raise SubmissionError(
209
+ f"Cloud Run could not start job {spec.job!r} in {self._location}: {exc}",
210
+ backend=self._name,
211
+ ) from exc
212
+
213
+ external_id = _execution_name(operation)
214
+ execution_id = new_execution_id(ExecutionKind.JOB)
215
+ self._ids.remember(str(execution_id), external_id)
216
+
217
+ return Execution(
218
+ id=execution_id,
219
+ kind=ExecutionKind.JOB,
220
+ backend=self._name,
221
+ state=ExecutionState.QUEUED,
222
+ name=spec.name,
223
+ created_at=datetime.now(UTC),
224
+ external_id=external_id,
225
+ correlation=spec.correlation,
226
+ provider_metadata=ProviderMetadata(
227
+ provider="gcp",
228
+ provider_id=external_id,
229
+ region=self._location,
230
+ resource=self.job_resource(spec),
231
+ labels=dict(spec.labels),
232
+ ),
233
+ metadata={"profile": spec.profile},
234
+ )
235
+
236
+ def _overrides(self, spec: JobSpec) -> dict[str, Any]:
237
+ """Translate the portable parts of a JobSpec into Cloud Run overrides."""
238
+ container: dict[str, Any] = {}
239
+ if spec.argv:
240
+ container["args"] = list(spec.argv)
241
+ if spec.env:
242
+ container["env"] = [{"name": key, "value": value} for key, value in spec.env.items()]
243
+
244
+ overrides: dict[str, Any] = {}
245
+ if container:
246
+ overrides["container_overrides"] = [container]
247
+ if spec.parallelism > 1:
248
+ overrides["task_count"] = spec.parallelism
249
+ if spec.timeout.seconds is not None:
250
+ overrides["timeout"] = {"seconds": int(spec.timeout.seconds)}
251
+ if spec.retry.enabled:
252
+ # Cloud Run counts *re*-tries, RetryPolicy counts total attempts.
253
+ overrides["task_count"] = overrides.get("task_count", spec.parallelism)
254
+ overrides["max_retries"] = spec.retry.engine_attempts - 1
255
+ return overrides
256
+
257
+ # -- observation ------------------------------------------------------------------ #
258
+ def _get(self, execution_id: ExecutionId) -> Execution:
259
+ external_id = self._ids.resolve(str(execution_id))
260
+ if external_id is None:
261
+ raise ExecutionNotFound(
262
+ f"{execution_id!r} was not submitted by this backend instance; pass the "
263
+ "Cloud Run execution name (projects/.../executions/...) to look it up "
264
+ "from another process",
265
+ backend=self._name,
266
+ )
267
+ try:
268
+ remote = self._executions().get_execution(name=external_id)
269
+ except Exception as exc:
270
+ if _is_not_found(exc):
271
+ raise ExecutionNotFound(
272
+ f"Cloud Run has no execution {external_id!r}", backend=self._name
273
+ ) from exc
274
+ raise BackendError(
275
+ f"Cloud Run could not read execution {external_id!r}: {exc}", backend=self._name
276
+ ) from exc
277
+
278
+ state, error = map_execution_state(remote)
279
+ return Execution(
280
+ id=execution_id,
281
+ kind=ExecutionKind.JOB,
282
+ backend=self._name,
283
+ state=state,
284
+ name=str(getattr(remote, "job", "") or ""),
285
+ started_at=_as_datetime(getattr(remote, "start_time", None)),
286
+ finished_at=_as_datetime(getattr(remote, "completion_time", None)),
287
+ external_id=external_id,
288
+ result=ExecutionResult(error=error, logs_uri=self.logs_uri(external_id))
289
+ if state.is_terminal
290
+ else None,
291
+ provider_metadata=ProviderMetadata(
292
+ provider="gcp",
293
+ provider_id=external_id,
294
+ region=self._location,
295
+ resource=str(getattr(remote, "job", "") or ""),
296
+ ),
297
+ metadata={"logs_uri": self.logs_uri(external_id)},
298
+ )
299
+
300
+ def _cancel(self, execution_id: ExecutionId) -> Execution:
301
+ external_id = self._ids.resolve(str(execution_id))
302
+ if external_id is None:
303
+ raise ExecutionNotFound(
304
+ f"{execution_id!r} was not submitted by this backend instance", backend=self._name
305
+ )
306
+ try:
307
+ self._executions().cancel_execution(name=external_id)
308
+ except Exception as exc:
309
+ raise BackendError(
310
+ f"Cloud Run could not cancel execution {external_id!r}: {exc}", backend=self._name
311
+ ) from exc
312
+ return self._get(execution_id)
313
+
314
+ def logs_uri(self, external_id: str) -> str:
315
+ """A Cloud Logging console link for an execution. No request is made."""
316
+ return (
317
+ "https://console.cloud.google.com/logs/query"
318
+ f"?project={self._project}&query=resource.labels.location%3D%22{self._location}%22"
319
+ )
320
+
321
+
322
+ def _run_v2() -> Any:
323
+ """Import ``google.cloud.run_v2`` lazily, with an actionable error."""
324
+ try:
325
+ from google.cloud import run_v2
326
+ except ImportError as exc: # pragma: no cover - depends on the environment
327
+ raise ConfigurationError(
328
+ "the Cloud Run backend needs the Google SDK: pip install 'taskferry-cloudrun[gcp]'"
329
+ ) from exc
330
+ return run_v2
331
+
332
+
333
+ def _execution_name(operation: Any) -> str | None:
334
+ """Pull the execution resource name out of the long-running operation."""
335
+ metadata = getattr(operation, "metadata", None)
336
+ name = getattr(metadata, "name", None)
337
+ if isinstance(name, str) and name:
338
+ return name
339
+ fallback = getattr(operation, "name", None)
340
+ return fallback if isinstance(fallback, str) and fallback else None
341
+
342
+
343
+ def _as_datetime(value: Any) -> datetime | None:
344
+ """Normalise a protobuf timestamp (or a real datetime) to an aware datetime."""
345
+ if value is None:
346
+ return None
347
+ if isinstance(value, datetime):
348
+ return value if value.tzinfo else value.replace(tzinfo=UTC)
349
+ converter = getattr(value, "ToDatetime", None)
350
+ if callable(converter):
351
+ converted = converter()
352
+ if not isinstance(converted, datetime): # pragma: no cover - hostile fake
353
+ return None
354
+ return converted.replace(tzinfo=UTC) if converted.tzinfo is None else converted
355
+ return None
356
+
357
+
358
+ def _is_not_found(exc: Exception) -> bool:
359
+ """Whether a Google API error means "no such resource".
360
+
361
+ Matched by class name rather than by importing ``google.api_core``, so this
362
+ check works even when only a fake client is installed.
363
+ """
364
+ if type(exc).__name__ == "NotFound":
365
+ return True
366
+ return getattr(exc, "code", None) == 404
367
+
368
+
369
+ def make_backend(**options: Any) -> CloudRunJobBackend:
370
+ """Entry point for ``{"factory": "cloudrun", ...}`` configuration."""
371
+ return CloudRunJobBackend(
372
+ project=options.get("project"),
373
+ location=options.get("location"),
374
+ jobs_client=options.get("jobs_client"),
375
+ executions_client=options.get("executions_client"),
376
+ name=str(options.get("name", "cloudrun")),
377
+ tracked_ids=int(options.get("tracked_ids", 10_000)),
378
+ )
379
+
380
+
381
+ __all__ = [
382
+ "CLOUD_RUN_CAPABILITIES",
383
+ "CloudRunJobBackend",
384
+ "make_backend",
385
+ "map_execution_state",
386
+ ]