overture-serverless 0.1.0__py3-none-any.whl

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.
File without changes
@@ -0,0 +1,249 @@
1
+ """Airflow 2 / 3 compatibility shim.
2
+
3
+ Import Airflow symbols from this module instead of directly from ``airflow.sdk``
4
+ (3.x) or the scattered 2.x paths. Works transparently on both versions.
5
+
6
+ Usage::
7
+
8
+ from overture_serverless.airflow_compat import DAG, task, Variable, chain
9
+
10
+ Two paths to remove this file:
11
+
12
+ Upgrade path when the running Airflow ships Airflow 3:
13
+ 1. Delete this file.
14
+ 2. Global find-and-replace: ``from overture_serverless.airflow_compat import``
15
+ -> ``from airflow.sdk import``
16
+ 3. Done -- one clean commit.
17
+
18
+ Upgrade path when Airflow v2.11.1+ is the floor:
19
+ 1. Delete this file.
20
+ 2. Global find-and-replace: ``from overture_serverless.airflow_compat import``
21
+ -> ``from airflow.providers.common.compat.sdk import``
22
+ 3. Done -- one clean commit.
23
+ 4. Optional -- follow upstream and remove the common-compat shim package from
24
+ your codebase entirely once Airflow 3 is supported.
25
+
26
+ Implementation mirrors the lazy-__getattr__ approach used by the official
27
+ ``airflow.providers.common.compat.sdk`` shim so symbols are only imported on
28
+ first access, keeping DAG parse time fast.
29
+
30
+ Inspired by upstream:
31
+ https://github.com/apache/airflow/blob/main/providers/common/compat/src/airflow/providers/common/compat/sdk.py
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import importlib
37
+ from typing import Any
38
+
39
+ # ---------------------------------------------------------------------------
40
+ # Rename map: symbols that changed name between Airflow 2.x and 3.x
41
+ # Format: new_name -> (v3_module, v2_module, v2_name)
42
+ # ---------------------------------------------------------------------------
43
+ _RENAME_MAP: dict[str, tuple[str, str, str]] = {
44
+ "Asset": ("airflow.sdk", "airflow.datasets", "Dataset"),
45
+ "AssetAlias": ("airflow.sdk", "airflow.datasets", "DatasetAlias"),
46
+ "AssetAll": ("airflow.sdk", "airflow.datasets", "DatasetAll"),
47
+ "AssetAny": ("airflow.sdk", "airflow.datasets", "DatasetAny"),
48
+ }
49
+
50
+ # ---------------------------------------------------------------------------
51
+ # Import map: symbol name -> (v3_module, v2_module)
52
+ # None as v2_module means the symbol is Airflow 3-only (no 2.x equivalent).
53
+ # ---------------------------------------------------------------------------
54
+ _IMPORT_MAP: dict[str, tuple[str, str | None]] = {
55
+ # -- DAG / decorators -----------------------------------------------------
56
+ "DAG": ("airflow.sdk", "airflow.models.dag"),
57
+ "dag": ("airflow.sdk", "airflow.decorators"),
58
+ "task": ("airflow.sdk", "airflow.decorators"),
59
+ "task_group": ("airflow.sdk", "airflow.decorators"),
60
+ "setup": ("airflow.sdk", "airflow.decorators"),
61
+ "teardown": ("airflow.sdk", "airflow.decorators"),
62
+ "chain": ("airflow.sdk", "airflow.models.baseoperator"),
63
+ "chain_linear": ("airflow.sdk", "airflow.models.baseoperator"),
64
+ "cross_downstream": ("airflow.sdk", "airflow.models.baseoperator"),
65
+ # -- Models ----------------------------------------------------------------
66
+ # Variable is handled separately below (see `Variable` class) -- Variable.get()'s
67
+ # `default_var` kwarg was renamed to `default` in 3.x, so a straight symbol swap
68
+ # isn't enough; every call site would need touching otherwise.
69
+ "Connection": ("airflow.sdk", "airflow.models.connection"),
70
+ "Param": ("airflow.sdk", "airflow.models.param"),
71
+ "ParamsDict": ("airflow.sdk", "airflow.models.param"),
72
+ "XComArg": ("airflow.sdk", "airflow.models.xcom_arg"),
73
+ "XCom": ("airflow.sdk.execution_time.xcom", "airflow.models.xcom"),
74
+ "MappedOperator": (
75
+ "airflow.sdk.definitions.mappedoperator",
76
+ "airflow.models.mappedoperator",
77
+ ),
78
+ # -- Operators / base classes ----------------------------------------------
79
+ "BaseOperator": ("airflow.sdk", "airflow.models.baseoperator"),
80
+ "BaseOperatorLink": ("airflow.sdk", "airflow.models.baseoperatorlink"),
81
+ "BaseSensorOperator": ("airflow.sdk", "airflow.sensors.base"),
82
+ "PokeReturnValue": ("airflow.sdk", "airflow.sensors.base"),
83
+ "poke_mode_only": ("airflow.sdk.bases.sensor", "airflow.sensors.base"),
84
+ "BaseHook": ("airflow.sdk", "airflow.hooks.base"),
85
+ "BaseBranchOperator": (
86
+ "airflow.sdk.bases.branch",
87
+ "airflow.providers.standard.operators.branch",
88
+ ),
89
+ "BranchMixIn": (
90
+ "airflow.sdk.bases.branch",
91
+ "airflow.providers.standard.operators.branch",
92
+ ),
93
+ "SkipMixin": ("airflow.sdk.bases.skipmixin", "airflow.models.skipmixin"),
94
+ # -- Decorator internals ---------------------------------------------------
95
+ "TaskDecorator": ("airflow.sdk.bases.decorator", "airflow.decorators.base"),
96
+ "DecoratedOperator": ("airflow.sdk.bases.decorator", "airflow.decorators.base"),
97
+ "DecoratedMappedOperator": (
98
+ "airflow.sdk.bases.decorator",
99
+ "airflow.decorators.base",
100
+ ),
101
+ "task_decorator_factory": (
102
+ "airflow.sdk.bases.decorator",
103
+ "airflow.decorators.base",
104
+ ),
105
+ "get_unique_task_id": ("airflow.sdk.bases.decorator", "airflow.decorators.base"),
106
+ # -- Groups & modifiers ----------------------------------------------------
107
+ "TaskGroup": ("airflow.sdk", "airflow.utils.task_group"),
108
+ "EdgeModifier": ("airflow.sdk", "airflow.utils.edgemodifier"),
109
+ "Label": ("airflow.sdk", "airflow.utils.edgemodifier"),
110
+ # -- State / enums ---------------------------------------------------------
111
+ "TriggerRule": ("airflow.sdk", "airflow.utils.trigger_rule"),
112
+ "DagRunState": ("airflow.sdk", "airflow.utils.state"),
113
+ "TaskInstanceState": ("airflow.sdk", "airflow.utils.state"),
114
+ "WeightRule": ("airflow.sdk", "airflow.utils.weight_rule"),
115
+ # -- Context & utilities ---------------------------------------------------
116
+ "Context": ("airflow.sdk", "airflow.utils.context"),
117
+ "context_merge": ("airflow.sdk.definitions.context", "airflow.utils.context"),
118
+ "get_current_context": ("airflow.sdk", "airflow.operators.python"),
119
+ "get_parsing_context": ("airflow.sdk", "airflow.utils.dag_parsing_context"),
120
+ "TaskInstanceKey": ("airflow.sdk.types", "airflow.models.taskinstancekey"),
121
+ # -- Assets ----------------------------------------------------------------
122
+ "Metadata": ("airflow.sdk", "airflow.datasets.metadata"),
123
+ "ObjectStoragePath": ("airflow.sdk", "airflow.io.path"),
124
+ # -- Exceptions ------------------------------------------------------------
125
+ "AirflowException": ("airflow.sdk.exceptions", "airflow.exceptions"),
126
+ "AirflowConfigException": ("airflow.sdk.exceptions", "airflow.exceptions"),
127
+ "AirflowFailException": ("airflow.sdk.exceptions", "airflow.exceptions"),
128
+ "AirflowNotFoundException": ("airflow.sdk.exceptions", "airflow.exceptions"),
129
+ "AirflowOptionalProviderFeatureException": (
130
+ "airflow.sdk.exceptions",
131
+ "airflow.exceptions",
132
+ ),
133
+ "AirflowSensorTimeout": ("airflow.sdk.exceptions", "airflow.exceptions"),
134
+ "AirflowSkipException": ("airflow.sdk.exceptions", "airflow.exceptions"),
135
+ "AirflowTaskTimeout": ("airflow.sdk.exceptions", "airflow.exceptions"),
136
+ "ParamValidationError": ("airflow.sdk.exceptions", "airflow.exceptions"),
137
+ "TaskDeferred": ("airflow.sdk.exceptions", "airflow.exceptions"),
138
+ "XComNotFound": ("airflow.sdk.exceptions", "airflow.exceptions"),
139
+ # Airflow 3-only -- no 2.x equivalent
140
+ "DagRunTriggerException": ("airflow.sdk.exceptions", None),
141
+ "DownstreamTasksSkipped": ("airflow.sdk.exceptions", None),
142
+ # -- Observability ---------------------------------------------------------
143
+ "Stats": ("airflow.sdk._shared.observability.metrics.stats", "airflow.stats"),
144
+ # -- Configuration ---------------------------------------------------------
145
+ "conf": ("airflow.sdk.configuration", "airflow.configuration"),
146
+ # -- Lineage ---------------------------------------------------------------
147
+ "HookLineage": ("airflow.sdk.lineage", "airflow.lineage.hook"),
148
+ "HookLineageCollector": ("airflow.sdk.lineage", "airflow.lineage.hook"),
149
+ "HookLineageReader": ("airflow.sdk.lineage", "airflow.lineage.hook"),
150
+ "NoOpCollector": ("airflow.sdk.lineage", "airflow.lineage.hook"),
151
+ "get_hook_lineage_collector": ("airflow.sdk.lineage", "airflow.lineage.hook"),
152
+ # -- Plugins ---------------------------------------------------------------
153
+ "AirflowPlugin": ("airflow.sdk.plugins_manager", "airflow.plugins_manager"),
154
+ # -- BaseNotifier ----------------------------------------------------------
155
+ "BaseNotifier": ("airflow.sdk", "airflow.notifications.basenotifier"),
156
+ # -- Secrets -----------------------------------------------------------------
157
+ # airflow.sdk.log (not the _shared.secrets_masker it wraps) is the intended
158
+ # public entry point on 3.x -- it also notifies the supervisor process.
159
+ "mask_secret": ("airflow.sdk.log", "airflow.utils.log.secrets_masker"),
160
+ }
161
+
162
+ # ---------------------------------------------------------------------------
163
+ # Module map: symbols that are entire modules (imported with `import X`)
164
+ # Format: name -> (v3_module_path, v2_module_path)
165
+ # ---------------------------------------------------------------------------
166
+ _MODULE_MAP: dict[str, tuple[str, str]] = {
167
+ "timezone": ("airflow.sdk.timezone", "airflow.utils.timezone"),
168
+ "io": ("airflow.sdk.io", "airflow.io"),
169
+ }
170
+
171
+
172
+ def _load(module_path: str, attr: str) -> Any:
173
+ mod = importlib.import_module(module_path)
174
+ return getattr(mod, attr)
175
+
176
+
177
+ def _real_variable() -> Any:
178
+ try:
179
+ return _load("airflow.sdk", "Variable")
180
+ except (ImportError, AttributeError):
181
+ return _load("airflow.models.variable", "Variable")
182
+
183
+
184
+ _NOTSET = object()
185
+
186
+
187
+ class _VariableMeta(type):
188
+ """Delegates any attribute not defined on `Variable` (`.set`, `.delete`, ...)
189
+ straight to the real Variable class for the running Airflow version."""
190
+
191
+ def __getattr__(cls, name: str) -> Any:
192
+ return getattr(_real_variable(), name)
193
+
194
+
195
+ class Variable(metaclass=_VariableMeta):
196
+ """Variable proxy that normalizes `Variable.get()`'s `default_var` (2.x) /
197
+ `default` (3.x) kwarg rename, so call sites can keep using `default_var=`
198
+ on both versions. Everything else delegates to the real class via `_VariableMeta`.
199
+ """
200
+
201
+ @staticmethod
202
+ def get(
203
+ key: str, default_var: Any = _NOTSET, deserialize_json: bool = False
204
+ ) -> Any:
205
+ real = _real_variable()
206
+ if default_var is _NOTSET:
207
+ return real.get(key, deserialize_json=deserialize_json)
208
+ try:
209
+ return real.get(key, default=default_var, deserialize_json=deserialize_json)
210
+ except TypeError:
211
+ return real.get(
212
+ key, default_var=default_var, deserialize_json=deserialize_json
213
+ )
214
+
215
+
216
+ def __getattr__(name: str) -> Any:
217
+ # Renamed symbols (e.g. Dataset -> Asset)
218
+ if name in _RENAME_MAP:
219
+ v3_mod, v2_mod, v2_name = _RENAME_MAP[name]
220
+ try:
221
+ return _load(v3_mod, name)
222
+ except (ImportError, AttributeError):
223
+ return _load(v2_mod, v2_name)
224
+
225
+ # Whole-module symbols
226
+ if name in _MODULE_MAP:
227
+ v3_path, v2_path = _MODULE_MAP[name]
228
+ for path in (v3_path, v2_path):
229
+ try:
230
+ return importlib.import_module(path)
231
+ except ImportError:
232
+ continue
233
+ raise ImportError(f"airflow_compat: cannot import module {name!r}")
234
+
235
+ # Regular symbols
236
+ if name in _IMPORT_MAP:
237
+ v3_mod, v2_mod = _IMPORT_MAP[name]
238
+ try:
239
+ return _load(v3_mod, name)
240
+ except (ImportError, AttributeError):
241
+ pass
242
+ if v2_mod is not None:
243
+ return _load(v2_mod, name)
244
+ raise ImportError(f"airflow_compat: {name!r} requires Airflow 3+")
245
+
246
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
247
+
248
+
249
+ __all__ = ["Variable", *_RENAME_MAP, *_IMPORT_MAP, *_MODULE_MAP]
@@ -0,0 +1,19 @@
1
+ """Backend contract implementations for ``serverless_python_task_group``.
2
+
3
+ A backend is an Airflow-facing function that provisions managed compute,
4
+ injects the runner-contract env vars (``MODULE_NAME``, ``CLASS_NAME``,
5
+ ``PYTHON_PACKAGES``, ``PIP_INDEX_URL``, ``PARAMS``), and runs the container.
6
+ :mod:`overture_serverless.backends.fargate` is the AWS ECS Fargate
7
+ implementation shipped today.
8
+
9
+ Every cloud- or account-specific value (network configuration, IAM role,
10
+ container image URI, ECS task-definition composition) is a parameter the
11
+ caller supplies rather than something a backend resolves for itself, so this
12
+ package stays free of any one deployment's account IDs, VPC layout, or naming
13
+ conventions.
14
+
15
+ Import from the specific backend module (e.g. ``.fargate``) rather than a
16
+ top-level re-export: this keeps ``overture_serverless``'s base install free of
17
+ the ``apache-airflow`` / ``apache-airflow-providers-amazon`` dependencies that
18
+ only backend users need (see the ``fargate`` extra).
19
+ """
@@ -0,0 +1,421 @@
1
+ """AWS ECS Fargate backend for the ``serverless_python`` framework.
2
+
3
+ One implementation of the ``serverless_python_task_group`` contract. It
4
+ launches the reference runner container (``overture-python-runner``) on
5
+ Fargate; at run time the container installs the requested Python packages
6
+ from a pip index and dispatches to the caller's job class.
7
+
8
+ The runner container is cloud-agnostic -- it speaks a simple runner contract
9
+ (``MODULE_NAME``, ``CLASS_NAME``, ``PYTHON_PACKAGES``, ``PIP_INDEX_URL``,
10
+ ``PARAMS`` env vars) and takes a single ``PIP_INDEX_URL``. This backend
11
+ assembles that URL from CodeArtifact credentials before passing it in; a
12
+ hypothetical GCP Cloud Run or Azure Container Apps backend would live
13
+ alongside this file and assemble the URL from its own artifact registry.
14
+
15
+ Every value specific to a deployment's AWS account -- VPC/subnet layout, IAM
16
+ role ARNs, container image URI, and how the underlying ECS task definition is
17
+ registered/run/torn down -- is supplied by the caller rather than resolved
18
+ here, so this module has no dependency on any one deployment's private
19
+ helpers. See ``network_config``, ``task_role_arn``, ``image_uri``, and
20
+ ``ecs_task_builder_factory`` on :func:`serverless_python_task_group`.
21
+
22
+ Task pipeline::
23
+
24
+ register_task_definition -> execute_job -> deregister_task_definition
25
+
26
+ - ``register_task_definition`` / ``deregister_task_definition`` come from the
27
+ injected ``ecs_task_builder_factory`` and manage the ephemeral Fargate task
28
+ definition.
29
+ - ``execute_job`` fetches a short-lived CodeArtifact auth token inside the
30
+ operator's ``execute()`` and injects a fully-formed ``PIP_INDEX_URL`` into
31
+ ``containerOverrides`` in memory before calling ECS ``RunTask``. The token
32
+ never lands in XCom, task logs, or the metadata DB.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import json
38
+ import logging
39
+ from typing import Any, Literal, Protocol
40
+
41
+ from airflow.providers.amazon.aws.operators.ecs import EcsRunTaskOperator
42
+
43
+ from overture_serverless.airflow_compat import TaskGroup, chain, mask_secret
44
+
45
+ _DEFAULT_ECS_CLUSTER = "overture-python-runner"
46
+ _DEFAULT_LOG_GROUP = "/ecs/overture-python-runner"
47
+
48
+ log = logging.getLogger(__name__)
49
+
50
+ _CONTAINER_NAME = "runner"
51
+ _CODEARTIFACT_TOKEN_DURATION_SECONDS = (
52
+ 3600 # 1 hour, plenty for Fargate cold start + pip install
53
+ )
54
+
55
+ # T-shirt-sized presets. All combos are valid Fargate CPU/memory pairings.
56
+ _SIZE_PRESETS: dict[str, tuple[str, str]] = {
57
+ "xs": ("256", "512"),
58
+ "s": ("512", "1024"),
59
+ "m": ("1024", "2048"),
60
+ "l": ("2048", "4096"),
61
+ }
62
+
63
+
64
+ class EcsTaskBuilderLike(Protocol):
65
+ """Duck-typed contract for the ECS register -> run -> teardown builder.
66
+
67
+ Matches ``EcsTaskBuilder`` from Overture's internal ``ecs_helper`` module
68
+ (and any equivalent a caller wants to substitute) without this package
69
+ importing that class directly.
70
+ """
71
+
72
+ def register(self, task_id: str = ...) -> Any: ...
73
+
74
+ def run(
75
+ self,
76
+ overrides: dict,
77
+ task_id: str = ...,
78
+ awslogs_stream_prefix: str = ...,
79
+ retries: int = ...,
80
+ reattach: bool = ...,
81
+ ) -> Any: ...
82
+
83
+ def teardown(
84
+ self,
85
+ container_name: str,
86
+ run_op: Any | None = ...,
87
+ task_id: str = ...,
88
+ ) -> list: ...
89
+
90
+
91
+ def _build_fargate_combos() -> set[tuple[str, str]]:
92
+ """Enumerate every valid Fargate (cpu_units, memory_mib) combination.
93
+
94
+ Sourced from
95
+ https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-cpu-memory-error.html - no enum in botocore model
96
+ Used to fail fast at DAG-parse time when a caller passes an invalid
97
+ exact override, instead of surfacing an ECS ``InvalidParameterException``
98
+ at task-run time.
99
+ """
100
+ combos: set[tuple[str, str]] = set()
101
+ combos.update((("256", m) for m in ("512", "1024", "2048")))
102
+ combos.update((("512", m) for m in ("1024", "2048", "3072", "4096")))
103
+ combos.update((("1024", str(m)) for m in range(2048, 8193, 1024)))
104
+ combos.update((("2048", str(m)) for m in range(4096, 16385, 1024)))
105
+ combos.update((("4096", str(m)) for m in range(8192, 30721, 1024)))
106
+ combos.update((("8192", str(m)) for m in range(16384, 61441, 4096)))
107
+ combos.update((("16384", str(m)) for m in range(32768, 122881, 8192)))
108
+ return combos
109
+
110
+
111
+ _FARGATE_VALID_COMBOS = _build_fargate_combos()
112
+
113
+
114
+ def _resolve_cpu_memory(
115
+ size: str | None, cpu: str | None, memory: str | None
116
+ ) -> tuple[str, str]:
117
+ if size is not None and (cpu is not None or memory is not None):
118
+ raise ValueError("Set either `size` or (`cpu` and `memory`), not both.")
119
+ if cpu is None and memory is None:
120
+ preset = size or "xs"
121
+ if preset not in _SIZE_PRESETS:
122
+ raise ValueError(
123
+ f"Unknown size preset: {preset!r}. Valid: {sorted(_SIZE_PRESETS)}. "
124
+ "If you think this is a valid preset, check "
125
+ "https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-cpu-memory-error.html "
126
+ "and update _build_fargate_combos() accordingly."
127
+ )
128
+ return _SIZE_PRESETS[preset]
129
+ if cpu is None or memory is None:
130
+ raise ValueError(
131
+ "Both `cpu` and `memory` must be set when using an exact override."
132
+ )
133
+ if (cpu, memory) not in _FARGATE_VALID_COMBOS:
134
+ raise ValueError(
135
+ f"cpu={cpu!r}, memory={memory!r} is not a valid Fargate combo. "
136
+ "See https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-cpu-memory-error.html "
137
+ "and update _build_fargate_combos() accordingly."
138
+ )
139
+ return cpu, memory
140
+
141
+
142
+ class _CodeArtifactPipIndexUrlEcsOperator(EcsRunTaskOperator):
143
+ """``EcsRunTaskOperator`` that mints a CodeArtifact-backed
144
+ ``PIP_INDEX_URL`` inside ``execute()`` and injects it into
145
+ ``containerOverrides`` in memory just before submitting to ECS.
146
+
147
+ The token is registered with Airflow's secrets masker so it is redacted
148
+ from task logs. It never lands in XCom, the Airflow metadata DB, or any
149
+ templated field.
150
+ """
151
+
152
+ def __init__(
153
+ self,
154
+ *,
155
+ codeartifact_domain: str,
156
+ codeartifact_owner: str,
157
+ codeartifact_repo: str,
158
+ codeartifact_region: str,
159
+ target_container_name: str,
160
+ **kwargs,
161
+ ) -> None:
162
+ super().__init__(**kwargs)
163
+ self._ca_domain = codeartifact_domain
164
+ self._ca_owner = codeartifact_owner
165
+ self._ca_repo = codeartifact_repo
166
+ self._ca_region = codeartifact_region
167
+ self._target_container_name = target_container_name
168
+
169
+ def execute(self, context):
170
+ import boto3
171
+
172
+ ca = boto3.client("codeartifact", region_name=self._ca_region)
173
+ token = ca.get_authorization_token(
174
+ domain=self._ca_domain,
175
+ domainOwner=self._ca_owner,
176
+ durationSeconds=_CODEARTIFACT_TOKEN_DURATION_SECONDS,
177
+ )["authorizationToken"]
178
+ mask_secret(token)
179
+ pip_index_url = (
180
+ f"https://aws:{token}"
181
+ f"@{self._ca_domain}-{self._ca_owner}"
182
+ f".d.codeartifact.{self._ca_region}.amazonaws.com"
183
+ f"/pypi/{self._ca_repo}/simple/"
184
+ )
185
+ mask_secret(pip_index_url)
186
+ containers = self.overrides.get("containerOverrides", [])
187
+ target = next(
188
+ (c for c in containers if c.get("name") == self._target_container_name),
189
+ None,
190
+ )
191
+ if target is None:
192
+ raise ValueError(
193
+ f"target_container_name={self._target_container_name!r} not found "
194
+ f"in containerOverrides; cannot inject PIP_INDEX_URL"
195
+ )
196
+ # NativeEnvironment can literal_eval a JSON string back to a dict.
197
+ environment = target.setdefault("environment", [])
198
+ for env in environment:
199
+ if not isinstance(env.get("value"), str):
200
+ env["value"] = json.dumps(env["value"])
201
+ # Retries re-run execute() on the same operator instance, so drop any
202
+ # PIP_INDEX_URL this method injected on a prior attempt before adding
203
+ # the freshly minted one -- otherwise the container sees duplicate,
204
+ # increasingly stale entries.
205
+ environment[:] = [e for e in environment if e.get("name") != "PIP_INDEX_URL"]
206
+ environment.append({"name": "PIP_INDEX_URL", "value": pip_index_url})
207
+ return super().execute(context)
208
+
209
+ def _start_task(self):
210
+ # Superclass populates self.arn after the RunTask call. Emit a
211
+ # clickable console URL as soon as the task ID is known so
212
+ # engineers can jump straight from Airflow logs to the running
213
+ # job. Label stays platform-neutral ("Job console") so future
214
+ # backends can supply their own URL template without a rename.
215
+ result = super()._start_task()
216
+ if self.arn:
217
+ # arn:aws:ecs:<region>:<account>:task/<cluster>/<task-id>
218
+ region = self.arn.split(":")[3]
219
+ task_id = self.arn.rsplit("/", 1)[-1]
220
+ self.log.info(
221
+ "Job console: https://%s.console.aws.amazon.com/ecs/v2/clusters/%s/tasks/%s?region=%s",
222
+ region,
223
+ self.cluster,
224
+ task_id,
225
+ region,
226
+ )
227
+ return result
228
+
229
+
230
+ def serverless_python_task_group(
231
+ group_id: str,
232
+ *,
233
+ module_name: str,
234
+ class_name: str,
235
+ python_packages: str,
236
+ task_role_arn: str,
237
+ network_config: dict,
238
+ image_uri: str,
239
+ ecs_task_builder_factory: "type[EcsTaskBuilderLike] | Any",
240
+ parameters: str = "{}",
241
+ size: Literal["xs", "s", "m", "l"] | None = None,
242
+ cpu: str | None = None,
243
+ memory: str | None = None,
244
+ ephemeral_storage_gib: int = 21,
245
+ retries: int = 0,
246
+ job_name: str = "",
247
+ region: str = "us-west-2",
248
+ log_region: str | None = None,
249
+ ecs_cluster: str = _DEFAULT_ECS_CLUSTER,
250
+ log_group: str = _DEFAULT_LOG_GROUP,
251
+ codeartifact_domain: str = "overture-pypi",
252
+ codeartifact_owner: str = "505071440022",
253
+ codeartifact_repo: str = "overture",
254
+ output_path: str | None = None,
255
+ ):
256
+ """Run a Python job on the AWS ECS Fargate serverless backend.
257
+
258
+ Callers implement a class exposing ``run(params: str) -> None`` --
259
+ typically a ``ServerlessPythonJob`` subclass, but any object with that
260
+ shape works. The class is cloud-agnostic; only this factory ties the
261
+ invocation to Fargate.
262
+
263
+ Args:
264
+ group_id: Airflow task group ID shown in the UI.
265
+ module_name: Dotted Python module containing the job class,
266
+ e.g. ``"overture_addresses.collect"``.
267
+ class_name: Name of the class to instantiate, e.g. ``"CollectionJob"``.
268
+ python_packages: Space-separated pip specs installed at run time.
269
+ task_role_arn: Full ARN of the IAM role used as both ``taskRoleArn``
270
+ and ``executionRoleArn``. Required -- resolve it (e.g. from an
271
+ IAM role name via STS) before calling in; this module has no
272
+ opinion on how role names map to ARNs in your account.
273
+ network_config: ECS ``networkConfiguration`` dict (subnets, security
274
+ groups, ``assignPublicIp``) as accepted by the ECS ``RunTask``
275
+ API. Required -- resolve it from wherever your deployment stores
276
+ VPC/subnet/security-group configuration before calling in.
277
+ image_uri: Fully resolved runner container image URI (registry,
278
+ repository, and tag). Required -- build it however your
279
+ deployment maps environments/versions to image tags (e.g. via an
280
+ ECR-URI builder keyed by account and region) before calling in.
281
+ ecs_task_builder_factory: Callable with the same call signature as
282
+ ``EcsTaskBuilder.__init__`` (``family``, ``container_definitions``,
283
+ ``role_arn``, ``network_configuration``, ``cpu``, ``memory``,
284
+ ``ephemeral_storage_gib``, ``cluster``, ``awslogs_group``,
285
+ ``awslogs_region``, ``launch_type``, ``network_mode``,
286
+ ``output_path``) that returns an object satisfying
287
+ :class:`EcsTaskBuilderLike` (``register()``/``run()``/``teardown()``).
288
+ Required -- pass your deployment's ECS task-definition builder
289
+ (e.g. Overture's internal ``EcsTaskBuilder``); this module never
290
+ constructs ECS task definitions on its own.
291
+ parameters: JSON string forwarded to ``cls().run(params)``.
292
+ size: T-shirt preset. ``xs`` (default) covers streaming I/O, API
293
+ calls, and lightweight transforms. Presets:
294
+
295
+ +------+-----------+------------+-----------+---------+
296
+ | size | CPU units | Memory MiB | real vCPU | RAM |
297
+ +======+===========+============+===========+=========+
298
+ | xs | 256 | 512 | 0.25 | 0.5 GB |
299
+ | s | 512 | 1024 | 0.5 | 1 GB |
300
+ | m | 1024 | 2048 | 1 | 2 GB |
301
+ | l | 2048 | 4096 | 2 | 4 GB |
302
+ +------+-----------+------------+-----------+---------+
303
+
304
+ If ``l`` is not enough, pass ``cpu``/``memory`` explicitly.
305
+ cpu, memory: Escape hatch for exact Fargate CPU units / memory MiB.
306
+ Must form a valid Fargate combo; the wrapper validates at parse
307
+ time. Mutually exclusive with ``size``.
308
+ ephemeral_storage_gib: Fargate ephemeral storage in GiB (minimum 21
309
+ when set explicitly, max 200).
310
+ retries: Airflow-level retries on the ECS run task.
311
+ job_name: Optional display suffix appended to the task definition
312
+ family name in the ECS console.
313
+ region: AWS region for Fargate, ECS, and CodeArtifact.
314
+ log_region: AWS region for CloudWatch Logs. Defaults to ``region`` --
315
+ override when logs live in a different region than compute.
316
+ ecs_cluster: ECS cluster name. Defaults to Overture's reference
317
+ runner cluster (``"overture-python-runner"``); override for any
318
+ other deployment.
319
+ log_group: CloudWatch Logs group for the task's container logs.
320
+ Defaults to Overture's reference runner log group; override for
321
+ any other deployment.
322
+ codeartifact_domain, codeartifact_owner, codeartifact_repo:
323
+ CodeArtifact coordinates. This backend fetches an auth token
324
+ and assembles a ``PIP_INDEX_URL`` before invoking the runner;
325
+ the container itself is not CodeArtifact-aware.
326
+ output_path: Forwarded to ``ecs_task_builder_factory`` so an
327
+ injected builder can record container image provenance; this
328
+ module does not interpret it itself.
329
+ """
330
+ resolved_cpu, resolved_memory = _resolve_cpu_memory(size, cpu, memory)
331
+
332
+ if not 21 <= ephemeral_storage_gib <= 200:
333
+ raise ValueError(
334
+ f"ephemeral_storage_gib={ephemeral_storage_gib} is invalid; Fargate requires 21..200 GiB"
335
+ )
336
+ resolved_log_region = log_region or region
337
+
338
+ family_suffix = "-".join(
339
+ part.replace(".", "-") for part in (module_name, class_name, job_name) if part
340
+ )
341
+ family = f"serverless-python-{family_suffix}"
342
+
343
+ with TaskGroup(group_id=group_id) as tg:
344
+ ecs = ecs_task_builder_factory(
345
+ family=family,
346
+ cluster=ecs_cluster,
347
+ awslogs_group=log_group,
348
+ container_definitions=[
349
+ {
350
+ "name": _CONTAINER_NAME,
351
+ "image": image_uri,
352
+ "essential": True,
353
+ "logConfiguration": {
354
+ "logDriver": "awslogs",
355
+ "options": {
356
+ "awslogs-group": log_group,
357
+ "awslogs-region": resolved_log_region,
358
+ "awslogs-stream-prefix": f"serverless-python/{group_id}",
359
+ },
360
+ },
361
+ }
362
+ ],
363
+ role_arn=task_role_arn,
364
+ network_configuration=network_config,
365
+ cpu=resolved_cpu,
366
+ memory=resolved_memory,
367
+ ephemeral_storage_gib=ephemeral_storage_gib,
368
+ output_path=output_path,
369
+ )
370
+
371
+ # Task IDs use platform-agnostic names (setup / execute_job / cleanup)
372
+ # rather than the ECS-specific "register_task_definition" /
373
+ # "deregister_task_definition" defaults, so future backends
374
+ # (k8s Jobs, Cloud Run, Azure Container Apps) can slot into the
375
+ # same UI shape without leaking cloud vocabulary.
376
+ register = ecs.register(task_id="setup")
377
+ # Build the run operator directly rather than via ``ecs.run()`` so we
378
+ # can use the custom subclass that mints and injects PIP_INDEX_URL at
379
+ # execute time. Mirrors ``EcsTaskBuilder.run()`` internals; register()
380
+ # must have been called to expose the task-definition XCom.
381
+ run = _CodeArtifactPipIndexUrlEcsOperator(
382
+ task_id="execute_job",
383
+ cluster=ecs_cluster,
384
+ task_definition=str(register.output),
385
+ launch_type="FARGATE",
386
+ overrides={
387
+ "containerOverrides": [
388
+ {
389
+ "name": _CONTAINER_NAME,
390
+ "environment": [
391
+ {"name": "MODULE_NAME", "value": module_name},
392
+ {"name": "CLASS_NAME", "value": class_name},
393
+ {"name": "PYTHON_PACKAGES", "value": python_packages},
394
+ {"name": "PARAMS", "value": parameters},
395
+ ],
396
+ }
397
+ ]
398
+ },
399
+ network_configuration=network_config,
400
+ awslogs_group=log_group,
401
+ awslogs_region=resolved_log_region,
402
+ awslogs_stream_prefix=f"serverless-python/{group_id}",
403
+ do_xcom_push=True,
404
+ retries=retries,
405
+ codeartifact_domain=codeartifact_domain,
406
+ codeartifact_owner=codeartifact_owner,
407
+ codeartifact_repo=codeartifact_repo,
408
+ codeartifact_region=region,
409
+ target_container_name=_CONTAINER_NAME,
410
+ )
411
+
412
+ chain(
413
+ register,
414
+ run,
415
+ ecs.teardown(_CONTAINER_NAME, run_op=run, task_id="cleanup"),
416
+ )
417
+
418
+ return tg
419
+
420
+
421
+ __all__ = ["serverless_python_task_group", "EcsTaskBuilderLike"]
@@ -0,0 +1,42 @@
1
+ """Lightweight base class for a portable "serverless job" contract.
2
+
3
+ Subclass and implement ``execute_job()``; a runner (container, script, cron
4
+ job, whatever) instantiates the subclass and calls ``run()``.
5
+
6
+ Plain Python by design — no cloud SDKs, no framework dependencies. The same
7
+ subclass runs identically on any backend or on a developer laptop for local
8
+ iteration.
9
+ """
10
+
11
+ import json
12
+ from abc import ABC, abstractmethod
13
+
14
+
15
+ class ServerlessPythonJob(ABC):
16
+ def __init__(self) -> None:
17
+ self._params: dict = {}
18
+
19
+ def run(self, params: "str | dict" = "{}") -> None:
20
+ print(f"Starting job {self.__class__.__name__}")
21
+ self._params = json.loads(params) if isinstance(params, str) else params
22
+ if not isinstance(self._params, dict):
23
+ raise TypeError(
24
+ f"params must decode to a JSON object/dict, got {type(self._params).__name__}"
25
+ )
26
+ print(f"Received params: {sorted(self._params.keys())}")
27
+ self.execute_job()
28
+ print(f"Job {self.__class__.__name__} completed successfully")
29
+
30
+ def get_param(self, name: str, default=None, is_required: bool = True):
31
+ value = self._params.get(name, default)
32
+ if isinstance(value, str):
33
+ value = value.strip() or None
34
+ if is_required and value is None:
35
+ raise ValueError(f"Missing required parameter: {name}")
36
+ return default if value is None else value
37
+
38
+ def log(self, msg: str) -> None:
39
+ print(msg)
40
+
41
+ @abstractmethod
42
+ def execute_job(self) -> None: ...
@@ -0,0 +1,92 @@
1
+ Metadata-Version: 2.4
2
+ Name: overture-serverless
3
+ Version: 0.1.0
4
+ Summary: Base classes for portable, framework-agnostic serverless Python jobs.
5
+ Author: Overture Maps Foundation
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/OvertureMaps/overture-core
8
+ Project-URL: Source, https://github.com/OvertureMaps/overture-core/tree/main/packages/overture_serverless
9
+ Project-URL: Issues, https://github.com/OvertureMaps/overture-core/issues
10
+ Keywords: overture,overturemaps,serverless,jobs
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Provides-Extra: fargate
21
+ Requires-Dist: apache-airflow<3,>=2.9; extra == "fargate"
22
+ Requires-Dist: apache-airflow-providers-amazon<9,>=8.13.0; extra == "fargate"
23
+ Provides-Extra: dev
24
+ Requires-Dist: pytest>=9.1.1; extra == "dev"
25
+ Requires-Dist: pytest-cov>=7.0.0; extra == "dev"
26
+ Requires-Dist: apache-airflow<3,>=2.9; extra == "dev"
27
+ Requires-Dist: apache-airflow-providers-amazon<9,>=8.13.0; extra == "dev"
28
+ Dynamic: license-file
29
+
30
+ # overture-serverless
31
+
32
+ [![PyPI](https://img.shields.io/pypi/v/overture-serverless.svg)](https://pypi.org/project/overture-serverless/)
33
+ [![Python versions](https://img.shields.io/pypi/pyversions/overture-serverless.svg)](https://pypi.org/project/overture-serverless/)
34
+
35
+ Base class for portable, framework-agnostic "job" classes, plus the Airflow-facing backends that launch them. A published package that gets installed at run time wherever a job actually executes, and provides the contract your job subclasses.
36
+
37
+ It contains:
38
+ - `ServerlessPythonJob` — abstract base class your jobs subclass (`execute_job()`), with parameter parsing (`get_param()`) and logging (`log()`). Plain Python, no cloud dependencies — runs identically on any backend or on your laptop.
39
+ - `backends.fargate.serverless_python_task_group` — an Airflow `TaskGroup` factory that runs a job on AWS ECS Fargate. Requires the `fargate` extra (`pip install overture-serverless[fargate]`), which pulls in `apache-airflow` and `apache-airflow-providers-amazon`; the base install stays dependency-free since `ServerlessPythonJob` runs inside the job container, not inside Airflow.
40
+
41
+ ## Writing a job
42
+
43
+ ```python
44
+ from overture_serverless.job import ServerlessPythonJob
45
+
46
+
47
+ class CollectionJob(ServerlessPythonJob):
48
+ def execute_job(self) -> None:
49
+ path = self.get_param("input_path")
50
+ self.log(f"Processing {path}")
51
+ # ... your logic
52
+ ```
53
+
54
+ ## Testing locally
55
+
56
+ ```bash
57
+ cd packages/overture_serverless
58
+ uv run python -c "
59
+ from overture_serverless.job import ServerlessPythonJob
60
+
61
+ class ExampleJob(ServerlessPythonJob):
62
+ def execute_job(self) -> None:
63
+ self.log(self.get_param('input_path'))
64
+
65
+ ExampleJob().run('{\"input_path\": \"s3://...\"}')
66
+ "
67
+ ```
68
+
69
+ ## Launching a job on Fargate
70
+
71
+ `serverless_python_task_group` builds an Airflow `TaskGroup` that provisions an ECS Fargate task, runs your job's runner container, and tears the task definition down afterward. It has no opinion on your AWS account's VPC layout, IAM roles, or container registry — you resolve those and pass them in:
72
+
73
+ ```python
74
+ from overture_serverless.backends.fargate import serverless_python_task_group
75
+
76
+ collect = serverless_python_task_group(
77
+ group_id="collection_job",
78
+ module_name="overture_addresses.collect",
79
+ class_name="CollectionJob",
80
+ python_packages="overture-addresses",
81
+ task_role_arn=my_resolved_role_arn, # e.g. via STS in your own DAG code
82
+ network_config=my_ecs_network_config, # ECS `networkConfiguration` dict
83
+ image_uri=my_resolved_runner_image_uri, # e.g. from your own ECR-URI builder
84
+ ecs_task_builder_factory=MyEcsTaskBuilder, # your register/run/teardown builder
85
+ )
86
+ ```
87
+
88
+ See the `serverless_python_task_group` docstring for the full parameter list (sizing presets, CodeArtifact coordinates, retries, etc.).
89
+
90
+ ## Publishing
91
+
92
+ See [`PACKAGE_VERSIONING.md`](../PACKAGE_VERSIONING.md) for how a version bump here turns into a PyPI release.
@@ -0,0 +1,10 @@
1
+ overture_serverless/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ overture_serverless/airflow_compat.py,sha256=gpb4cd4K20KylY189IR-fCGjCNZlBIKqEKusrQvTvOE,11779
3
+ overture_serverless/job.py,sha256=TzgJ-soiMNIHGGcHH7JbXBggwU6wljOE2C7khN4ThEg,1547
4
+ overture_serverless/backends/__init__.py,sha256=0WcREfe4kH82HyKanfYuEuHIloYI_ewESJ0umnCKHAU,998
5
+ overture_serverless/backends/fargate.py,sha256=mpLH0aaBtgHqQoRvMJH7J6M7UmQWTU0cp_0VClshutE,18378
6
+ overture_serverless-0.1.0.dist-info/licenses/LICENSE,sha256=24ta8OgpjROjE-HE1FWF9T3w46CiGzvcFzxjuEOFIUI,1070
7
+ overture_serverless-0.1.0.dist-info/METADATA,sha256=hrvCxAvqNXwgL4aDu6kTIBAW1JWkc0_5yU3IdFhLZHo,4239
8
+ overture_serverless-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
9
+ overture_serverless-0.1.0.dist-info/top_level.txt,sha256=UlY7jr7QD9r-mrw3G3cvlkb2OVmiFwWC-i6_p91Rbpo,20
10
+ overture_serverless-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Overture Maps
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ overture_serverless