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


##########
providers/google/src/airflow/providers/google/cloud/datafusion/object_storage.py:
##########
@@ -0,0 +1,126 @@
+# 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
+
+import json
+import os
+import tempfile
+from pathlib import Path
+from typing import Any
+
+from datafusion.object_store import GoogleCloud
+
+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
+
+_UNSUPPORTED_CONNECTION_FIELDS = ("key_secret_name", "credential_config_file", 
"impersonation_chain")
+
+
+def _get_gcp_extra_field(extra_dejson: dict[str, Any], field_name: str) -> Any:

Review Comment:
   **[warning]** `_get_gcp_extra_field` duplicates `get_field` that the google 
provider already has.
   
   This helper had to exist while the code lived in common-sql, which could not 
import from the google provider. Now that it lives here, 
[`airflow.providers.google.common.hooks.base_google.get_field`](https://github.com/apache/airflow/blob/1505b1690327ae97c52d21ad6538988e164d5368/providers/google/src/airflow/providers/google/common/hooks/base_google.py#L182-L194)
 does the same lookup (bare key first, then the 
`extra__google_cloud_platform__` prefix) and is what `GoogleBaseHook` itself 
uses. It also maps `""` to `None`, so the `or None` on `key_path` and 
`keyfile_dict` keeps working unchanged. Using it means the legacy-prefix rule 
lives in one place, which is the reason for the move in the first place.



##########
providers/google/src/airflow/providers/google/cloud/datafusion/object_storage.py:
##########
@@ -0,0 +1,126 @@
+# 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
+
+import json
+import os
+import tempfile
+from pathlib import Path
+from typing import Any
+
+from datafusion.object_store import GoogleCloud
+
+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
+
+_UNSUPPORTED_CONNECTION_FIELDS = ("key_secret_name", "credential_config_file", 
"impersonation_chain")
+
+
+def _get_gcp_extra_field(extra_dejson: dict[str, Any], field_name: str) -> Any:
+    # Older Airflow connection UIs wrote custom extra fields as
+    # extra__google_cloud_platform__<field_name> instead of the bare key; 
GoogleBaseHook
+    # still reads that legacy spelling as a fallback, so this must too.
+    if field_name in extra_dejson:
+        return extra_dejson[field_name]
+    return extra_dejson.get(f"extra__google_cloud_platform__{field_name}")
+
+
+class GCSObjectStorageProvider(ObjectStorageProvider):
+    """GCS Object Storage Provider using DataFusion's GoogleCloud."""
+
+    @property
+    def get_storage_type(self) -> StorageType:
+        """Return the storage type."""
+        return StorageType.GCS
+
+    def _credentials_from_connection(self, conn_id: str) -> dict[str, Any]:
+        """Derive GCS credentials from an Airflow connection; only 
``google_cloud_platform`` connections are supported."""
+        conn = BaseHook.get_connection(conn_id)

Review Comment:
   **[nit]** Question: could this share the connection handling with the 
provider's `filesystems:` entry instead of reading the extras by hand?
   
   The google provider now translates a `google_cloud_platform` connection into 
a GCS client in two places: 
[`cloud/fs/gcs.py`](https://github.com/apache/airflow/blob/1505b1690327ae97c52d21ad6538988e164d5368/providers/google/src/airflow/providers/google/cloud/fs/gcs.py#L42-L66)
 for fsspec / `ObjectStoragePath`, and this class for DataFusion. The fsspec 
one goes through `GoogleBaseHook(gcp_conn_id=conn_id)`; this one reads 
`conn.extra_dejson` directly. The S3 class from #64941 goes through the hook 
too 
([`AwsGenericHook`](https://github.com/apache/airflow/blob/1505b1690327ae97c52d21ad6538988e164d5368/providers/amazon/src/airflow/providers/amazon/aws/datafusion/object_storage.py#L43)),
 so GCS is the one that bypasses it.
   
   I see why the credentials object itself cannot be reused: 
`datafusion.object_store.GoogleCloud(bucket_name, service_account_path=None)` 
only takes a key file, while `gcsfs` takes the token from `get_credentials()`. 
That is also why `key_secret_name`, `credential_config_file` and 
`impersonation_chain` work for `gs://` through `ObjectStoragePath` and are 
rejected here. But reading the fields could still go through `GoogleBaseHook` 
(its `_get_field` for `key_path` / `keyfile_dict`), so a change to how the hook 
resolves them reaches both paths.
   
   If you prefer to keep that out of this PR, a short note in the class 
docstring that points at `cloud/fs/gcs.py` and says why the supported 
credential types differ would already help the two from drifting apart. Not 
blocking.



##########
providers/google/src/airflow/providers/google/cloud/datafusion/object_storage.py:
##########
@@ -0,0 +1,126 @@
+# 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
+
+import json
+import os
+import tempfile
+from pathlib import Path
+from typing import Any
+
+from datafusion.object_store import GoogleCloud
+
+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
+
+_UNSUPPORTED_CONNECTION_FIELDS = ("key_secret_name", "credential_config_file", 
"impersonation_chain")
+
+
+def _get_gcp_extra_field(extra_dejson: dict[str, Any], field_name: str) -> Any:
+    # Older Airflow connection UIs wrote custom extra fields as
+    # extra__google_cloud_platform__<field_name> instead of the bare key; 
GoogleBaseHook
+    # still reads that legacy spelling as a fallback, so this must too.
+    if field_name in extra_dejson:
+        return extra_dejson[field_name]
+    return extra_dejson.get(f"extra__google_cloud_platform__{field_name}")
+
+
+class GCSObjectStorageProvider(ObjectStorageProvider):
+    """GCS Object Storage Provider using DataFusion's GoogleCloud."""
+
+    @property
+    def get_storage_type(self) -> StorageType:
+        """Return the storage type."""
+        return StorageType.GCS
+
+    def _credentials_from_connection(self, conn_id: str) -> dict[str, Any]:
+        """Derive GCS credentials from an Airflow connection; only 
``google_cloud_platform`` connections are supported."""
+        conn = BaseHook.get_connection(conn_id)
+        if conn.conn_type != "google_cloud_platform":
+            raise ValueError(f"Unknown connection type {conn.conn_type}")
+
+        extra_dejson = conn.extra_dejson
+        for unsupported_field in _UNSUPPORTED_CONNECTION_FIELDS:
+            if _get_gcp_extra_field(extra_dejson, unsupported_field):
+                raise ValueError(
+                    f"Connection field {unsupported_field!r} is not supported 
for DataFusion "
+                    "GCS access; only key_path, keyfile_dict, 
GOOGLE_APPLICATION_CREDENTIALS, or "
+                    "ambient credentials (gcloud ADC file / metadata server) 
are used."
+                )
+        key_path = _get_gcp_extra_field(extra_dejson, "key_path") or None
+        keyfile_dict = _get_gcp_extra_field(extra_dejson, "keyfile_dict") or 
None
+        if key_path and keyfile_dict:
+            raise ValueError(
+                "The `keyfile_dict` and `key_path` fields are mutually 
exclusive. "
+                "Please provide only one value."
+            )
+        if not key_path and not keyfile_dict:
+            key_path = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS")
+        credentials = {"key_path": key_path, "keyfile_dict": keyfile_dict}
+        return {k: v for k, v in credentials.items() if v is not None}
+
+    def create_object_store(self, path: str, connection_config: 
ConnectionConfig | None = None):
+        """
+        Create a GCS object store using DataFusion's GoogleCloud.
+
+        Credentials supplied on ``connection_config`` take precedence. Only 
when
+        ``connection_config.credentials`` is empty are they resolved from the
+        ``google_cloud_platform`` Airflow connection named by ``conn_id``.
+        """
+        if connection_config is None:
+            raise ValueError(f"connection_config must be provided for 
{self.get_storage_type.value}")
+
+        credentials = connection_config.credentials
+        if not credentials:
+            credentials = 
self._credentials_from_connection(connection_config.conn_id)

Review Comment:
   **[nit]** The connection errors keep their message but not their type, which 
the description says is unchanged.
   
   Before, the engine resolved GCS credentials in `_get_connection_config`, 
outside any `try`, so an unsupported field, both keys set or a 
non-`google_cloud_platform` connection reached the user as a plain 
`ValueError`. Now they are raised from `create_object_store`, which the engine 
calls inside [`_register_object_store`'s `except 
Exception`](https://github.com/apache/airflow/blob/1505b1690327ae97c52d21ad6538988e164d5368/providers/common/sql/src/airflow/providers/common/sql/datafusion/engine.py#L84-L100),
 so the task fails with `ObjectStoreCreationException("Error while creating 
object store for StorageType.GCS: ...")`. A missing connection is wrapped the 
same way. S3 behaves like this since #64941, so I would not change the code; 
the "same errors" line in the description should say the type changed, as 
someone catching `ValueError` around the operator will notice.



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