dilnazanlid commented on code in PR #72369:
URL: https://github.com/apache/airflow/pull/72369#discussion_r3958515925


##########
task-sdk/src/airflow/sdk/importers/zip_importer.py:
##########
@@ -0,0 +1,244 @@
+# 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 collections.abc import Iterator
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any
+
+from airflow.sdk.importers.base import (
+    AbstractDagImporter,
+    DagDefinition,
+    DagImportError,
+    DagImportResult,
+    DagSourceCode,
+)
+
+log = logging.getLogger(__name__)
+
+_sys_path_lock = threading.Lock()
+
+
[email protected]
+def _temporary_sys_path(path: str) -> Iterator[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)
+    _temp_path: Path | None = field(default=None, repr=False, compare=False)
+
+    @property
+    def freshness_token(self) -> str:
+        try:
+            stat = self.zip_path.stat()
+            return f"{stat.st_mtime_ns}-{stat.st_size}-{self.file_path}"
+        except OSError:
+            return ""
+
+    def get_relative_loc(self, root: Path | None = None) -> str:
+        if root is None:
+            return f"{self.zip_path}:{self.file_path}"
+        try:
+            rel_zip = self.zip_path.relative_to(root)
+            return f"{rel_zip}:{self.file_path}"
+        except ValueError:
+            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) -> Iterator[Path]:
+        if self._temp_path is not None and self._temp_path.exists():
+            yield self._temp_path
+            return
+
+        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, Any] | None = None):
+        super().__init__()
+        self._internal_importers: dict[str, AbstractDagImporter] = {}
+        if internal_importers is None:
+            from airflow.sdk.importers.python_importer import PythonDagImporter
+
+            self._internal_importers[".py"] = PythonDagImporter()
+        else:
+            from airflow.sdk._shared.module_loading import import_string
+
+            for ext, cfg in internal_importers.items():
+                ext_lower = ext if ext.startswith(".") else f".{ext}"
+                if isinstance(cfg, AbstractDagImporter):
+                    self._internal_importers[ext_lower.lower()] = cfg
+                elif isinstance(cfg, dict) and "classpath" in cfg:
+                    importer_class = import_string(cfg["classpath"])
+                    self._internal_importers[ext_lower.lower()] = 
importer_class(**cfg.get("kwargs", {}))

Review Comment:
   Whether configured via a list or a dict, __init__ immediately validates the 
input through `_parse_importer_specs()` and  
`DagImporterRegistry._instantiate_spec()`, raising descriptive 
AirflowConfigException errors.



##########
task-sdk/src/airflow/sdk/importers/zip_importer.py:
##########
@@ -0,0 +1,244 @@
+# 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 collections.abc import Iterator
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any
+
+from airflow.sdk.importers.base import (
+    AbstractDagImporter,
+    DagDefinition,
+    DagImportError,
+    DagImportResult,
+    DagSourceCode,
+)
+
+log = logging.getLogger(__name__)
+
+_sys_path_lock = threading.Lock()
+
+
[email protected]
+def _temporary_sys_path(path: str) -> Iterator[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)
+    _temp_path: Path | None = field(default=None, repr=False, compare=False)
+
+    @property
+    def freshness_token(self) -> str:
+        try:
+            stat = self.zip_path.stat()
+            return f"{stat.st_mtime_ns}-{stat.st_size}-{self.file_path}"
+        except OSError:
+            return ""
+
+    def get_relative_loc(self, root: Path | None = None) -> str:
+        if root is None:
+            return f"{self.zip_path}:{self.file_path}"
+        try:
+            rel_zip = self.zip_path.relative_to(root)
+            return f"{rel_zip}:{self.file_path}"
+        except ValueError:
+            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) -> Iterator[Path]:
+        if self._temp_path is not None and self._temp_path.exists():
+            yield self._temp_path
+            return
+
+        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, Any] | None = None):
+        super().__init__()
+        self._internal_importers: dict[str, AbstractDagImporter] = {}
+        if internal_importers is None:
+            from airflow.sdk.importers.python_importer import PythonDagImporter
+
+            self._internal_importers[".py"] = PythonDagImporter()
+        else:
+            from airflow.sdk._shared.module_loading import import_string
+
+            for ext, cfg in internal_importers.items():
+                ext_lower = ext if ext.startswith(".") else f".{ext}"
+                if isinstance(cfg, AbstractDagImporter):
+                    self._internal_importers[ext_lower.lower()] = cfg
+                elif isinstance(cfg, dict) and "classpath" in cfg:
+                    importer_class = import_string(cfg["classpath"])
+                    self._internal_importers[ext_lower.lower()] = 
importer_class(**cfg.get("kwargs", {}))
+
+    def import_definition(
+        self,
+        definition: DagDefinition,
+        *,
+        bundle_path: Path | None = None,
+        bundle_name: str | None = None,
+        safe_mode: bool = True,
+    ) -> DagImportResult:
+        """Import DAGs from a ZIP archive DAG definition by routing internal 
files."""
+        result = DagImportResult(definition=definition)
+
+        with definition.as_file() as local_zip_path:

Review Comment:
   Good catch! I’ve simplified this:
   
   - For regular local Dag files, as_file() doesn’t create a temp zip file—it 
just uses the existing file already on disk.
   - For the file extraction, we replaced the intermediate memory dictionary 
with z.extract(). Now files stream directly from the zip to the temp folder in 
one pass instead of reading everything into RAM and then writing it back out to 
disk.
   
   This should remove the extra memory overhead. WDYT?



-- 
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]

Reply via email to