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


##########
task-sdk/src/airflow/sdk/importers/base.py:
##########
@@ -0,0 +1,316 @@
+# 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.
+"""Abstract base class for DAG importers."""
+
+from __future__ import annotations
+
+import contextlib
+import logging
+import threading
+from abc import ABC, abstractmethod
+from collections.abc import Iterator
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+
+from airflow.sdk._shared.module_loading.file_discovery import 
find_path_from_directory
+
+if TYPE_CHECKING:
+    from airflow.sdk import DAG
+
+log = logging.getLogger(__name__)
+
+
+class DagDefinition(ABC):
+    """Abstract base class for a DAG source definition."""
+
+    @property
+    @abstractmethod
+    def freshness_token(self) -> str:
+        """Opaque, generalized token representing the current state of the 
source."""
+
+    @abstractmethod
+    def get_relative_loc(self, root: Path | None = None) -> str:
+        """Get relative location of the definition to a root directory."""
+
+    @abstractmethod
+    def read_bytes(self) -> bytes:
+        """Read and return the content of the resource as bytes."""
+
+    def read_text(self, encoding: str = "utf-8") -> str:
+        """Read and return the content of the resource as a string."""
+        return self.read_bytes().decode(encoding)
+
+    @abstractmethod
+    def as_file(self) -> contextlib.AbstractContextManager[Path]:
+        """
+        Return a context manager yielding a Path pointing to a local file.
+
+        For file-backed resources, this is the actual file path.
+        For others, a temp file is created and cleaned up.
+        """
+
+    @abstractmethod
+    def __repr__(self) -> str:
+        """Return string representation used by import error and warning 
objects."""
+
+
+@dataclass
+class FileDagDefinition(DagDefinition):
+    """A DAG definition backed by a file on the local filesystem."""
+
+    path: Path
+
+    @property
+    def freshness_token(self) -> str:
+        try:
+            stat = self.path.stat()
+            return f"{stat.st_mtime_ns}-{stat.st_size}"
+        except OSError:
+            return ""
+
+    def get_relative_loc(self, root: Path | None = None) -> str:
+        if root is None:
+            return str(self.path)
+        try:
+            return str(self.path.relative_to(root))
+        except ValueError:
+            return str(self.path)
+
+    def read_bytes(self) -> bytes:
+        return self.path.read_bytes()
+
+    @contextlib.contextmanager
+    def as_file(self) -> Iterator[Path]:
+        yield self.path
+
+    def __repr__(self) -> str:
+        return str(self.path)
+
+
+@dataclass
+class DagImportError:
+    """Structured error information for DAG import failures."""
+
+    source_reference: str
+    message: str
+    error_type: str = "import"
+    line_number: int | None = None
+    column_number: int | None = None
+    context: str | None = None
+    suggestion: str | None = None
+    stacktrace: str | None = None
+
+    def format_message(self) -> str:
+        """Format the error as a human-readable string."""
+        parts = [f"Error in {self.source_reference}"]
+        if self.line_number is not None:
+            loc = f"line {self.line_number}"
+            if self.column_number is not None:
+                loc += f", column {self.column_number}"
+            parts.append(f"Location: {loc}")
+        parts.append(f"Error ({self.error_type}): {self.message}")
+        if self.context:
+            parts.append(f"Context:\n{self.context}")
+        if self.suggestion:
+            parts.append(f"Suggestion: {self.suggestion}")
+        return "\n".join(parts)
+
+
+@dataclass
+class DagImportWarning:
+    """Warning information for non-fatal issues during DAG import."""
+
+    source_reference: str
+    message: str
+    warning_type: str = "import"
+    line_number: int | None = None
+    context: dict[str, Any] | None = None
+
+
+@dataclass
+class DagImportResult:
+    """Result of importing DAGs from a definition."""
+
+    definition: DagDefinition | None = None
+    dags: list[DAG] = field(default_factory=list)
+    errors: list[DagImportError] = field(default_factory=list)
+    skipped_definitions: list[DagDefinition] = field(default_factory=list)
+    warnings: list[DagImportWarning] = field(default_factory=list)
+    dependencies: list[DagDefinition] = field(default_factory=list)

Review Comment:
   Hmm, that makes sense actually. Missed that part. 
   
   But before going too deep into it - we need to discuss several points:
   1. moving the `LazyDeserializedDAG` into the shared module or task SDK, 
because we should avoid depending on the airflow-core (1) and external importer 
developers will need access to it, but it is is an internal implementation 
detail (2).
   2. full DAG objects contain some validation hooks (e.g., topological cycle 
detection via dag.validate(), timetable consistency checks, etc.) - should this 
be offloaded as the importer developers responsibility? Seems like a lot of 
validation is going to be missed if we just have LazyDeserializedDAG here
   3. (nit) for the default Python DAG importer, user code natively evaluates 
to sdk.DAG instances - should we serialize the DAG in the importer?
   
   Let me know what you think



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