uranusjr commented on code in PR #72369: URL: https://github.com/apache/airflow/pull/72369#discussion_r3988314803
########## task-sdk/src/airflow/sdk/importers/zip_importer.py: ########## @@ -0,0 +1,293 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +"""Zip archive DAG importer.""" + +from __future__ import annotations + +import contextlib +import logging +import sys +import tempfile +import threading +import zipfile +from dataclasses import dataclass, field +from pathlib import Path +from typing import TYPE_CHECKING, Any + +from airflow.sdk.exceptions import AirflowConfigException +from airflow.sdk.importers.base import ( + AbstractDagImporter, + DagDefinition, + DagImporterRegistry, + DagImportError, + DagImportResult, + DagSourceCode, + _get_importer_extensions, + _normalize_extensions, + _parse_importer_specs, + find_file_dag_definitions, + get_file_suffix, +) + +if TYPE_CHECKING: + from collections.abc import Generator, Iterator + + from airflow.dag_processing.bundles.base import BaseDagBundle # noqa: SDK002 + +log = logging.getLogger(__name__) + +_sys_path_lock = threading.Lock() + + [email protected] +def _temporary_sys_path(path: str) -> Generator[None, None, None]: + """Safely prepend a path to sys.path with synchronization and restoration.""" + with _sys_path_lock: + already_present = path in sys.path + if not already_present: + sys.path.insert(0, path) + try: + yield + finally: + if not already_present: + with contextlib.suppress(ValueError): + sys.path.remove(path) + + +@dataclass +class ZipFileDagDefinition(DagDefinition): + """A DAG definition backed by a file inside a ZIP archive.""" + + zip_path: Path + file_path: str + _content: bytes | None = field(default=None, repr=False, compare=False) + + @property + def freshness_token(self) -> str: + try: + stat = self.zip_path.stat() + except OSError: + return "" + return f"{stat.st_mtime_ns}-{stat.st_size}-{self.file_path}" + + def get_relative_loc(self, root: Path | None = None) -> str: + if root is not None: + with contextlib.suppress(ValueError): + return f"{self.zip_path.relative_to(root)}:{self.file_path}" + return f"{self.zip_path}:{self.file_path}" + + def read_bytes(self) -> bytes: + if self._content is None: + with zipfile.ZipFile(self.zip_path) as z: + self._content = z.read(self.file_path) + return self._content + + @contextlib.contextmanager + def as_file(self) -> Generator[Path, None, None]: + suffix = Path(self.file_path).suffix + with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as f: + f.write(self.read_bytes()) + temp_path = Path(f.name) + try: + yield temp_path + finally: + with contextlib.suppress(OSError): + temp_path.unlink() + + def __repr__(self) -> str: + return f"{self.zip_path}:{self.file_path}" + + +class ZipImporter(AbstractDagImporter): + """Composite importer responsible for routing archive members to internal importers.""" + + supported_extensions = [".zip"] + + def __init__( + self, + internal_importers: dict[str, AbstractDagImporter | dict[str, Any]] + | list[dict[str, Any]] + | None = None, + extensions: list[str] | None = None, + ) -> None: + if extensions is not None: + self.supported_extensions = _normalize_extensions(extensions) + self._internal_extension_importers: dict[str, AbstractDagImporter] = {} + self._ordered_internal_importers: list[AbstractDagImporter] = [] + + if internal_importers is None: + from airflow.sdk.importers.python_importer import PythonDagImporter + + self._register_internal(PythonDagImporter()) + elif isinstance(internal_importers, list): + specs = _parse_importer_specs(internal_importers, context="internal_importers of ZipImporter") + for spec in specs: + importer = DagImporterRegistry._instantiate_spec(spec) + self._register_internal(importer, extensions=spec.extensions) Review Comment: I have plans to rewrite this further. Let’s let this pass and rewrite this more substantially in a different PR. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
