dilnazanlid commented on code in PR #72369: URL: https://github.com/apache/airflow/pull/72369#discussion_r3955877028
########## 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: 1. Do you mean in terms of "it should be serialized_dags instead of list of DAGs"? - same reasons as above comment - importers live in `task-sdk` and their role is to parse definitions into `airflow.sdk.DAG` instances. `serialized_dags` requires `LazyDeserializedDAG`, which is an internal `airflow-core` model that does not exist in `task-sdk`. Also serialization happens downstream in `processor.py` only *after* `DagBag` performs validations. 2. Do you mean "In terms of additional fields or rich classes like DagImportError, etc."? - `DagFileParsingResult` is minimal IPC wire payload sent across processes to the scheduler, while `DagImportResult` is in-process domain model of the importer. It contains rich models to save this structure so `DagBag` and upstream error reporting can provide precise diagnostics(line numbers etc.). `DagFileParsingResult` flattens errors/warnings into a simple `fileloc -> traceback` just for IPC and database storage; flattening them inside the importer would discard granular error context. Or maybe I am missing something in the context of the AIP-108 that would require the classes here to be re-done, please LMK -- 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]
