dabla commented on code in PR #64941:
URL: https://github.com/apache/airflow/pull/64941#discussion_r4676674578
##########
airflow-core/src/airflow/provider_info.schema.json:
##########
@@ -206,6 +206,23 @@
}
}
},
+ "object-storage-providers": {
Review Comment:
**[blocker]** The new schema key needs a field on `ProviderInfoResponse`;
four core jobs fail on it.
`test_provider_info_response_declares_every_schema_key` (added on main with
`airflowctl providers get`) compares the keys of this schema with the fields of
`ProviderInfoResponse` in `api_fastapi/core_api/datamodels/providers.py`,
because a key the model does not declare is silently dropped from `GET
/providers/{package_name}`. It is the only failure in "Non-DB tests: core",
"LowestDeps", "Pendulum2" and "LatestBoto" on this head ([job
log](https://github.com/apache/airflow/actions/runs/45185897922/job/137816988141)).
The fix mirrors `dialects`: a small model with `storage_type` and
`provider_class_name` (aliases `storage-type`, `provider-class-name`), an
`object_storage_providers` field next to `dialects`, then the regenerated
OpenAPI spec, UI client and airflowctl datamodels.
##########
providers/common/sql/src/airflow/providers/common/sql/datafusion/object_storage_provider.py:
##########
@@ -223,20 +197,69 @@ def get_scheme(self) -> str:
return "file://"
+# Storage types still implemented here rather than contributed by a provider
package.
+# TODO: Add support for HTTP:
https://datafusion.apache.org/python/autoapi/datafusion/object_store/index.html
+EMBEDDED_PROVIDERS: dict[StorageType, type[ObjectStorageProvider]] = {
+ StorageType.LOCAL: LocalObjectStorageProvider,
+ StorageType.GCS: GCSObjectStorageProvider,
+ StorageType.AZURE: AzureObjectStorageProvider,
+}
+
+_STORAGE_TYPE_PROVIDER_HINTS: dict[str, str] = {
+ "s3": "apache-airflow-providers-amazon[datafusion]",
+}
+
+
+def _missing_provider_message(type_key: str) -> str:
+ hint = _STORAGE_TYPE_PROVIDER_HINTS.get(type_key, "the appropriate
provider package")
+ return f"No ObjectStorageProvider registered for storage type
'{type_key}'. Install or upgrade {hint}."
+
+
+def _get_legacy_object_storage_provider(type_key: str) ->
ObjectStorageProvider:
+ if type_key == StorageType.S3.value:
+ try:
+ from airflow.providers.amazon.aws.datafusion.object_storage import
S3ObjectStorageProvider
+ except ImportError as err:
+ raise ValueError(_missing_provider_message(type_key)) from err
+ return S3ObjectStorageProvider()
+
+ raise ValueError(_missing_provider_message(type_key))
+
+
def get_object_storage_provider(storage_type: StorageType) ->
ObjectStorageProvider:
"""Get an object storage provider based on the storage type."""
- # TODO: Add support for HTTP:
https://datafusion.apache.org/python/autoapi/datafusion/object_store/index.html
- providers: dict[StorageType, type] = {
- StorageType.S3: S3ObjectStorageProvider,
- StorageType.GCS: GCSObjectStorageProvider,
- StorageType.AZURE: AzureObjectStorageProvider,
- StorageType.LOCAL: LocalObjectStorageProvider,
- }
-
- if storage_type not in providers:
- raise ValueError(
- f"Unsupported storage type: {storage_type}. Supported types:
{list(providers.keys())}"
+ if provider_cls := EMBEDDED_PROVIDERS.get(storage_type):
+ return provider_cls()
+
+ type_key = storage_type.value
Review Comment:
**[nit]** A plain string works for the embedded types and crashes for the
registry ones.
Ran it on this head: `get_object_storage_provider("local")` returns the
local provider, because `StorageType` is a `str` enum and the dict lookup
matches the value, while `"s3"` and `"bogus"` both raise `AttributeError: 'str'
object has no attribute 'value'` here. On `main` both raised
`ValueError("Unsupported storage type ...")`, and the case that pinned it
(`get_object_storage_provider("invalid")`) went away with the move.
One line at the top of the function settles both paths: `storage_type =
StorageType(storage_type)` accepts the member or its value and raises
`ValueError: 'bogus' is not a valid StorageType` for anything else ([enum
lookup by
value](https://docs.python.org/3/library/enum.html#enum.EnumType.__call__)). A
test with `"bogus"` keeps it.
##########
providers/common/sql/tests/unit/common/sql/datafusion/test_object_storage_provider.py:
##########
@@ -341,26 +313,179 @@ def
test_azure_provider_partial_service_principal_raises_clear_error(self):
with pytest.raises(ObjectStoreCreationException, match="Failed to
create Azure object store"):
provider.create_object_store("az://demo-container/path",
connection_config)
-
@patch("airflow.providers.common.sql.datafusion.object_storage_provider.LocalFileSystem")
+
+class TestLocalObjectStorageProvider:
+ @patch(
+
"airflow.providers.common.sql.datafusion.object_storage_provider.LocalFileSystem",
+ autospec=True,
+ )
def test_local_provider(self, mock_local):
provider = LocalObjectStorageProvider()
assert provider.get_storage_type == StorageType.LOCAL
assert provider.get_scheme() == "file://"
local_store = provider.create_object_store("file://path")
assert local_store == mock_local.return_value
- def test_get_object_storage_provider(self):
- assert isinstance(get_object_storage_provider(StorageType.S3),
S3ObjectStorageProvider)
- assert isinstance(get_object_storage_provider(StorageType.GCS),
GCSObjectStorageProvider)
- assert isinstance(get_object_storage_provider(StorageType.AZURE),
AzureObjectStorageProvider)
- assert isinstance(get_object_storage_provider(StorageType.LOCAL),
LocalObjectStorageProvider)
- with pytest.raises(ValueError, match="Unsupported storage type"):
- get_object_storage_provider("invalid")
+class TestGetObjectStorageProvider:
+ def test_returns_local_provider_directly(self):
+ provider = get_object_storage_provider(StorageType.LOCAL)
+ assert isinstance(provider, LocalObjectStorageProvider)
+
+ def test_returns_gcs_provider_directly(self):
+ """GCS is still implemented in common-sql, so it resolves without the
registry."""
+ provider = get_object_storage_provider(StorageType.GCS)
+ assert isinstance(provider, GCSObjectStorageProvider)
+
+ def test_returns_azure_provider_directly(self):
+ """Azure is still implemented in common-sql, so it resolves without
the registry."""
+ provider = get_object_storage_provider(StorageType.AZURE)
+ assert isinstance(provider, AzureObjectStorageProvider)
+
+
@patch("airflow.providers.common.sql.datafusion.object_storage_provider.import_string",
autospec=True)
+ @patch("airflow.providers_manager.ProvidersManager", autospec=True)
+ def test_resolves_s3_via_registry(self, mock_pm_cls, mock_import_string):
+ mock_provider_cls = MagicMock()
+ mock_import_string.return_value = mock_provider_cls
+
+ mock_pm_cls.return_value.object_storage_providers = {
+ "s3": MagicMock(
+
provider_class_name="airflow.providers.amazon.aws.datafusion.object_storage.S3ObjectStorageProvider",
+ ),
+ }
+
+ provider = get_object_storage_provider(StorageType.S3)
+
+ mock_import_string.assert_called_once_with(
+
"airflow.providers.amazon.aws.datafusion.object_storage.S3ObjectStorageProvider"
+ )
+ assert provider == mock_provider_cls.return_value
+
+
@patch("airflow.providers.common.sql.datafusion.object_storage_provider.import_string",
autospec=True)
+ @patch("airflow.providers_manager.ProvidersManager", autospec=True)
+ def test_registry_entry_with_unimportable_class_raises_install_hint(
+ self, mock_pm_cls, mock_import_string
+ ):
+ """A registered provider whose module can't be imported yields the
hinted ValueError."""
+ mock_import_string.side_effect = ImportError("No module named
'datafusion'")
+ mock_pm_cls.return_value.object_storage_providers = {
+ "s3": MagicMock(
+
provider_class_name="airflow.providers.amazon.aws.datafusion.object_storage.S3ObjectStorageProvider",
+ ),
+ }
+
+ with pytest.raises(ValueError,
match="apache-airflow-providers-amazon"):
+ get_object_storage_provider(StorageType.S3)
+
+ @patch("airflow.providers_manager.ProvidersManager", autospec=True)
+ def test_unregistered_storage_type_raises(self, mock_pm_cls):
+ mock_pm_cls.return_value.object_storage_providers = {}
+
+ with pytest.raises(ValueError, match="No ObjectStorageProvider
registered.*Install or upgrade"):
+ get_object_storage_provider(StorageType.S3)
+
+ def test_error_message_includes_install_hint_for_s3(self):
+ with patch("airflow.providers_manager.ProvidersManager",
autospec=True) as mock_pm_cls:
+ mock_pm_cls.return_value.object_storage_providers = {}
+
+ with pytest.raises(ValueError,
match="apache-airflow-providers-amazon"):
+ get_object_storage_provider(StorageType.S3)
+
+ def test_legacy_core_resolves_s3_via_amazon_direct_import(self):
+ """On an older core without the registry property, S3 resolves via a
direct amazon import."""
+ pytest.importorskip("airflow.providers.amazon")
+ from airflow.providers.amazon.aws.datafusion.object_storage import
S3ObjectStorageProvider
+
+ with patch("airflow.providers_manager.ProvidersManager") as
mock_pm_cls:
+ mock_pm_cls.return_value = MagicMock(spec=[])
+
+ provider = get_object_storage_provider(StorageType.S3)
+
+ assert isinstance(provider, S3ObjectStorageProvider)
+
+ def test_legacy_core_s3_without_amazon_raises_install_hint(self):
+ """On an older core without the registry and amazon missing, raise the
hinted ValueError."""
+ with patch("airflow.providers_manager.ProvidersManager") as
mock_pm_cls:
+ mock_pm_cls.return_value = MagicMock(spec=[])
+
+ with patch.dict(
+ sys.modules,
+ {"airflow.providers.amazon.aws.datafusion.object_storage":
None},
+ ):
+ with pytest.raises(ValueError,
match="apache-airflow-providers-amazon"):
+ get_object_storage_provider(StorageType.S3)
+
+ def test_no_amazon_imports_at_module_level(self):
+ """Verify common-sql no longer statically imports amazon provider code
at the top level."""
+ import airflow.providers.common.sql.datafusion.object_storage_provider
as mod
+
+ top_level_names = [
+ name
+ for name, obj in vars(mod).items()
+ if not name.startswith("_")
+ and hasattr(obj, "__module__")
+ and "amazon" in getattr(obj, "__module__", "")
+ ]
+ assert top_level_names == [], f"Amazon symbols found at module level:
{top_level_names}"
+
+
+class TestS3DeprecationShim:
+ def test_old_import_path_emits_deprecation_warning(self):
+ """Importing S3ObjectStorageProvider from the old path still works but
warns."""
+ pytest.importorskip("airflow.providers.amazon")
+ import airflow.providers.common.sql.datafusion.object_storage_provider
as mod
+
+ with pytest.warns(
Review Comment:
**[nit]** The three `pytest.warns(match=...)` blocks accept any warning.
Without a category `pytest.warns` defaults to `Warning` ([pytest
docs](https://docs.pytest.org/en/stable/how-to/capture-warnings.html#warns)),
so any warning whose text matches would pass. The shim emits
`AirflowProviderDeprecationWarning`; naming it here and at lines 450 and 464
pins that.
```suggestion
with pytest.warns(
AirflowProviderDeprecationWarning,
```
--
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]