dabla commented on code in PR #64941:
URL: https://github.com/apache/airflow/pull/64941#discussion_r4286377191


##########
airflow-core/tests/unit/always/test_providers_manager.py:
##########
@@ -345,6 +346,101 @@ def test_dialects(self):
         assert len(dialect_class_names) == 4
         assert dialect_class_names == ["default", "db2", "mssql", "postgresql"]
 
+    def test_object_storage_providers(self):
+        provider_manager = ProvidersManager()
+        storage_types = sorted(provider_manager.object_storage_providers)
+        assert "s3" in storage_types
+        info = provider_manager.object_storage_providers["s3"]
+        assert (
+            info.provider_class_name
+            == 
"airflow.providers.amazon.aws.datafusion.object_storage.S3ObjectStorageProvider"
+        )
+        assert info.provider_name == "apache-airflow-providers-amazon"
+
+    def test_discover_object_storage_providers(self):
+        providers_manager = ProvidersManager()
+        providers_manager._provider_dict = LazyDictWithCache()
+        providers_manager._provider_dict["airflow.providers.amazon"] = 
ProviderInfo(
+            version="1.0.0",
+            data={
+                "object-storage-providers": [
+                    {
+                        "storage-type": "s3",
+                        "provider-class-name": 
"airflow.providers.amazon.aws.datafusion.object_storage.S3ObjectStorageProvider",
+                    }
+                ]
+            },
+        )
+        providers_manager._discover_hooks()
+        assert len(providers_manager._object_storage_provider_dict) == 1
+        assert providers_manager._object_storage_provider_dict["s3"] == 
ObjectStorageProviderInfo(
+            name="s3",
+            
provider_class_name="airflow.providers.amazon.aws.datafusion.object_storage.S3ObjectStorageProvider",
+            provider_name="airflow.providers.amazon",
+        )
+
+    def test_discover_object_storage_providers_empty(self):
+        providers_manager = ProvidersManager()
+        providers_manager._provider_dict = LazyDictWithCache()
+        providers_manager._provider_dict["airflow.providers.example"] = 
ProviderInfo(
+            version="1.0.0",
+            data={},
+        )
+        providers_manager._discover_hooks()
+        assert len(providers_manager._object_storage_provider_dict) == 0
+
+    def test_discover_object_storage_providers_duplicate_logs_warning(self, 
caplog):
+        providers_manager = ProvidersManager()
+        providers_manager._provider_dict = LazyDictWithCache()
+        providers_manager._provider_dict["airflow.providers.first"] = 
ProviderInfo(
+            version="1.0.0",
+            data={
+                "object-storage-providers": [
+                    {
+                        "storage-type": "s3",
+                        "provider-class-name": "first.S3Provider",
+                    }
+                ]
+            },
+        )
+        providers_manager._provider_dict["airflow.providers.second"] = 
ProviderInfo(
+            version="1.0.0",
+            data={
+                "object-storage-providers": [
+                    {
+                        "storage-type": "s3",
+                        "provider-class-name": "second.S3Provider",
+                    }
+                ]
+            },
+        )
+        with caplog.at_level(logging.WARNING):
+            providers_manager._discover_hooks()
+        assert "already registered" in caplog.text
+        assert (
+            
providers_manager._object_storage_provider_dict["s3"].provider_class_name == 
"second.S3Provider"
+        )
+
+    def test_object_storage_providers_property(self):
+        providers_manager = ProvidersManager()
+        providers_manager._provider_dict = LazyDictWithCache()
+        providers_manager._provider_dict["airflow.providers.amazon"] = 
ProviderInfo(
+            version="1.0.0",
+            data={
+                "object-storage-providers": [
+                    {
+                        "storage-type": "s3",
+                        "provider-class-name": 
"airflow.providers.amazon.aws.datafusion.object_storage.S3ObjectStorageProvider",
+                    }
+                ]
+            },
+        )
+        providers_manager._discover_hooks()
+        osp = providers_manager._object_storage_provider_dict

Review Comment:
   **[nit]** `test_object_storage_providers_property` never reads the property.
   
   It reads `providers_manager._object_storage_provider_dict` directly, so it 
covers the same ground as `test_discover_object_storage_providers` above it. 
The property's own job is calling `initialize_providers_hooks()` before 
returning the dict, and that isn't exercised here 
(`test_object_storage_providers` does cover it against the real providers). 
Either read `providers_manager.object_storage_providers` here or drop this test.



##########
providers/amazon/src/airflow/providers/amazon/aws/datafusion/object_storage.py:
##########
@@ -0,0 +1,86 @@
+# 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.
+from __future__ import annotations
+
+from typing import Any
+
+from datafusion.object_store import AmazonS3
+
+from airflow.providers.amazon.aws.hooks.base_aws import AwsGenericHook
+from airflow.providers.common.compat.sdk import BaseHook
+from airflow.providers.common.sql.config import ConnectionConfig, StorageType
+from airflow.providers.common.sql.datafusion.base import ObjectStorageProvider
+from airflow.providers.common.sql.datafusion.exceptions import 
ObjectStoreCreationException
+
+
+class S3ObjectStorageProvider(ObjectStorageProvider):
+    """S3 Object Storage Provider using DataFusion's AmazonS3."""
+
+    @property
+    def get_storage_type(self) -> StorageType:
+        """Return the storage type."""
+        return StorageType.S3
+
+    def _credentials_from_connection(self, conn_id: str) -> tuple[dict[str, 
Any], dict[str, Any]]:
+        """Derive S3 credentials and endpoint settings from an Airflow 
connection."""
+        conn = BaseHook.get_connection(conn_id)
+        aws_hook: AwsGenericHook = AwsGenericHook(aws_conn_id=conn.conn_id, 
client_type="s3")
+        creds = aws_hook.get_credentials()
+
+        credentials = {
+            "access_key_id": conn.login or creds.access_key,
+            "secret_access_key": conn.password or creds.secret_key,
+            "session_token": creds.token if creds.token else None,
+        }
+        credentials = {k: v for k, v in credentials.items() if v is not None}
+        extra_config = {k: conn.extra_dejson[k] for k in ("region", 
"endpoint") if k in conn.extra_dejson}
+        return credentials, extra_config
+
+    def create_object_store(self, path: str, connection_config: 
ConnectionConfig | None = None):
+        """
+        Create an S3 object store using DataFusion's AmazonS3.
+
+        Credentials supplied on ``connection_config`` take precedence. Only 
when
+        ``connection_config.credentials`` is empty are they resolved from the 
Airflow
+        connection named by ``conn_id`` via :class:`AwsGenericHook`, which 
picks up the
+        standard AWS credential chain. Caller-supplied ``extra_config`` keys 
always
+        override the ``region`` / ``endpoint`` derived from the connection.
+        """
+        if connection_config is None:
+            raise ValueError(f"connection_config must be provided for 
{self.get_storage_type}")

Review Comment:
   **[warning]** The `.value` that `main` has here was lost in the move, so the 
message reads `connection_config must be provided for StorageType.S3`.
   
   On `main`, `S3ObjectStorageProvider.create_object_store` raises 
`f"connection_config must be provided for {self.get_storage_type.value}"`. 
`StorageType` is a `str` mixin `Enum`, and since Python 3.12 `format()` on such 
a member goes through `Enum.__str__` 
([`Enum.__format__`](https://docs.python.org/3/library/enum.html#enum.Enum.__format__),
 "Changed in version 3.12"). On 3.12 and later this line therefore renders 
`StorageType.S3` instead of `s3`.
   
   ```suggestion
               raise ValueError(f"connection_config must be provided for 
{self.get_storage_type.value}")
   ```
   
   The test should have caught it. On `main`, 
`test_s3_provider_requires_connection_config` matched `"connection_config must 
be provided for s3"`, and its docstring says the message must name the storage 
type. The relocated `test_s3_provider_missing_connection_config` 
(`test_object_storage.py` line 206) matches only `"connection_config must be 
provided"`, so please restore `for s3` there too.



##########
providers/amazon/src/airflow/providers/amazon/aws/datafusion/object_storage.py:
##########
@@ -0,0 +1,86 @@
+# 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.
+from __future__ import annotations
+
+from typing import Any
+
+from datafusion.object_store import AmazonS3
+
+from airflow.providers.amazon.aws.hooks.base_aws import AwsGenericHook
+from airflow.providers.common.compat.sdk import BaseHook
+from airflow.providers.common.sql.config import ConnectionConfig, StorageType
+from airflow.providers.common.sql.datafusion.base import ObjectStorageProvider
+from airflow.providers.common.sql.datafusion.exceptions import 
ObjectStoreCreationException
+
+
+class S3ObjectStorageProvider(ObjectStorageProvider):
+    """S3 Object Storage Provider using DataFusion's AmazonS3."""
+
+    @property
+    def get_storage_type(self) -> StorageType:
+        """Return the storage type."""
+        return StorageType.S3
+
+    def _credentials_from_connection(self, conn_id: str) -> tuple[dict[str, 
Any], dict[str, Any]]:
+        """Derive S3 credentials and endpoint settings from an Airflow 
connection."""
+        conn = BaseHook.get_connection(conn_id)
+        aws_hook: AwsGenericHook = AwsGenericHook(aws_conn_id=conn.conn_id, 
client_type="s3")
+        creds = aws_hook.get_credentials()
+
+        credentials = {
+            "access_key_id": conn.login or creds.access_key,
+            "secret_access_key": conn.password or creds.secret_key,
+            "session_token": creds.token if creds.token else None,
+        }
+        credentials = {k: v for k, v in credentials.items() if v is not None}
+        extra_config = {k: conn.extra_dejson[k] for k in ("region", 
"endpoint") if k in conn.extra_dejson}
+        return credentials, extra_config
+
+    def create_object_store(self, path: str, connection_config: 
ConnectionConfig | None = None):
+        """
+        Create an S3 object store using DataFusion's AmazonS3.
+
+        Credentials supplied on ``connection_config`` take precedence. Only 
when
+        ``connection_config.credentials`` is empty are they resolved from the 
Airflow
+        connection named by ``conn_id`` via :class:`AwsGenericHook`, which 
picks up the
+        standard AWS credential chain. Caller-supplied ``extra_config`` keys 
always
+        override the ``region`` / ``endpoint`` derived from the connection.
+        """
+        if connection_config is None:
+            raise ValueError(f"connection_config must be provided for 
{self.get_storage_type}")
+
+        try:
+            credentials = connection_config.credentials
+            extra_config = connection_config.extra_config
+
+            if not credentials:

Review Comment:
   **[warning]** Credential resolution no longer checks `conn_type == "aws"`.
   
   On `main`, `DataFusionEngine._get_credentials` resolved S3 credentials only 
under `case "aws":`. For a connection of any other type it returned empty 
`credentials`/`extra_config`, and `AmazonS3(bucket_name=...)` fell back to 
DataFusion's own environment lookup. Now the engine passes a bare 
`ConnectionConfig` for every non-embedded storage type, and this branch runs 
`AwsGenericHook` on whatever connection `conn_id` names. Two consequences for 
an `s3://` datasource whose connection is not of type `aws`:
   
   - that connection's `login`/`password` are sent as 
`access_key_id`/`secret_access_key`, and its `region`/`endpoint` extras are 
applied;
   - if boto finds no credentials, `get_credentials()` returns `None` and 
`creds.access_key` raises `AttributeError`, wrapped as 
`ObjectStoreCreationException`, where `main` built the store without 
credentials.
   
   To keep the relocation free of behaviour changes, resolve from the 
connection only when it is an AWS connection, for example by checking 
`conn.conn_type == "aws"` in `_credentials_from_connection` and returning empty 
dicts otherwise. A test with a non-`aws` connection would pin it.



##########
providers/common/sql/pyproject.toml:
##########
@@ -100,6 +97,9 @@ dependencies = [
 "apache.iceberg" = [
     "apache-airflow-providers-apache-iceberg"
 ]
+"amazon" = [
+    "apache-airflow-providers-amazon>=9.38.0"

Review Comment:
   **[warning]** 9.38.0 has already been cut without this change, so this floor 
will miss again unless it carries the `# use next version` marker.
   
   `providers-amazon/9.38.0rc1` and `rc2` are tagged, and neither contains 
`aws/datafusion/object_storage.py`, the same way 9.36.0 and 9.37.0 went out 
during this PR. A hard-coded number keeps going stale while the PR waits. The 
project's convention for a dependency on an unreleased provider version is the 
marker, which the release manager resolves when the release containing this 
change is cut 
([contributing-docs/13_airflow_dependencies_and_extras.rst](https://github.com/apache/airflow/blob/main/contributing-docs/13_airflow_dependencies_and_extras.rst)):
   
   ```suggestion
       "apache-airflow-providers-amazon>=9.38.0",  # use next version
   ```
   
   The `amazon` row in `providers/common/sql/docs/index.rst` follows when it is 
regenerated.



##########
providers/common/sql/src/airflow/providers/common/sql/datafusion/engine.py:
##########
@@ -128,10 +132,13 @@ def execute_query(self, query: str, max_rows: int | None 
= None) -> dict[str, li
         except Exception as e:
             raise QueryExecutionException(f"Error while executing query: {e}")
 
-    def _get_connection_config(self, conn_id: str) -> ConnectionConfig:
-
+    def _get_connection_config(self, conn_id: str, storage_type: StorageType | 
None) -> ConnectionConfig:
+        """Build a ConnectionConfig, resolving credentials only for storage 
types implemented here."""
         airflow_conn = BaseHook.get_connection(conn_id)
 
+        if storage_type not in EMBEDDED_PROVIDERS:

Review Comment:
   **[nit]** For a provider-owned storage type, the connection is fetched only 
to read back `conn_id`.
   
   `BaseHook.get_connection(conn_id)` runs before this check, and the result is 
used only for `airflow_conn.conn_id`, which equals the `conn_id` argument. Then 
`S3ObjectStorageProvider._credentials_from_connection` fetches the same 
connection again, and `AwsGenericHook` fetches it a third time. In a task each 
fetch goes through the secrets backends and the Execution API. Moving the check 
above the fetch (`return ConnectionConfig(conn_id=conn_id)`) drops one of the 
three.



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