Lee-W commented on code in PR #45960:
URL: https://github.com/apache/airflow/pull/45960#discussion_r1967264748


##########
task_sdk/src/airflow/sdk/definitions/asset/__init__.py:
##########
@@ -694,6 +695,39 @@ def as_expression(self) -> Any:
         return {"all": [o.as_expression() for o in self.objects]}
 
 
[email protected](kw_only=True)

Review Comment:
   Probably not `needed`, but I think it's better to set it as `kw_only` as 
it's hard to resonate the order of these arguments when initializing



##########
airflow/api_fastapi/execution_api/routes/asset_events.py:
##########
@@ -0,0 +1,81 @@
+# 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 Annotated
+
+from fastapi import Query, status
+from sqlalchemy import and_, select
+
+from airflow.api_fastapi.common.db.common import SessionDep
+from airflow.api_fastapi.common.router import AirflowRouter
+from airflow.api_fastapi.execution_api.datamodels.asset_event import (
+    AssetEventCollectionResponse,
+)
+from airflow.models.asset import AssetAliasModel, AssetEvent, AssetModel
+
+# TODO: Add dependency on JWT token
+router = AirflowRouter(
+    responses={
+        status.HTTP_404_NOT_FOUND: {"description": "Asset not found"},
+        status.HTTP_401_UNAUTHORIZED: {"description": "Unauthorized"},
+    },
+)
+
+
+def _get_asset_events_through_sql_clauses(
+    *, join_clause, where_clause, session: SessionDep
+) -> AssetEventCollectionResponse:
+    asset_events = session.scalars(
+        
select(AssetEvent).join(join_clause).where(where_clause).order_by(AssetEvent.timestamp)
+    )
+    return AssetEventCollectionResponse.model_validate({"asset_events": 
asset_events or []})
+
+
[email protected]("/by-asset")
+def get_asset_event_by_asset_name_uri(
+    name: Annotated[str, Query(description="The name of the Asset")],
+    uri: Annotated[str, Query(description="The URI of the Asset")],
+    session: SessionDep,
+) -> AssetEventCollectionResponse:
+    if name and uri:
+        where_clause = and_(AssetModel.name == name, AssetModel.uri == uri)

Review Comment:
   I think it's ok for this one. There's a unique constraint for this. There 
might be some cases we want to get it even if it's not active.



##########
task_sdk/src/airflow/sdk/api/client.py:
##########
@@ -445,6 +466,12 @@ def assets(self) -> AssetOperations:
         """Operations related to Assets."""
         return AssetOperations(self)
 
+    @lru_cache()  # type: ignore[misc]
+    @property

Review Comment:
   I'm not sure 🤔  But this is used this way across task_sdk. @ashb 
@amoghrajesh do you know why we did not use cached_property here?



##########
task_sdk/src/airflow/sdk/execution_time/context.py:
##########
@@ -281,6 +283,84 @@ def _get_asset_from_db(name: str | None = None, uri: str | 
None = None) -> Asset
         return Asset(**msg.model_dump(exclude={"type"}))
 
 
[email protected](init=False)
+class InletEventsAccessors(Mapping[Union[int, Asset, AssetAlias, AssetRef], 
Any]):
+    _inlets: list[Any]
+    _assets: dict[AssetUniqueKey, Asset]
+    _asset_aliases: dict[AssetAliasUniqueKey, AssetAlias]
+
+    def __init__(self, inlets: list) -> None:
+        self._inlets = inlets
+        self._assets = {}
+        self._asset_aliases = {}
+
+        for inlet in inlets:
+            if isinstance(inlet, Asset):
+                self._assets[AssetUniqueKey.from_asset(inlet)] = inlet
+            elif isinstance(inlet, AssetAlias):
+                
self._asset_aliases[AssetAliasUniqueKey.from_asset_alias(inlet)] = inlet
+            elif isinstance(inlet, AssetNameRef):
+                asset = 
OutletEventAccessors._get_asset_from_db(name=inlet.name)
+                self._assets[AssetUniqueKey.from_asset(asset)] = asset
+            elif isinstance(inlet, AssetUriRef):
+                asset = OutletEventAccessors._get_asset_from_db(uri=inlet.uri)
+                self._assets[AssetUniqueKey.from_asset(asset)] = asset
+
+    def __iter__(self) -> Iterator[Asset | AssetAlias]:
+        return iter(self._inlets)
+
+    def __len__(self) -> int:
+        return len(self._inlets)
+
+    def __getitem__(self, key: int | Asset | AssetAlias | AssetRef):
+        from airflow.sdk.definitions.asset import Asset
+
+        if isinstance(key, int):  # Support index access; it's easier for 
trivial cases.
+            obj = self._inlets[key]
+            if not isinstance(obj, (Asset, AssetAlias, AssetRef)):
+                raise IndexError(key)
+        else:
+            obj = key
+
+        return self._get_asset_events_from_db(obj)
+
+    # TODO: This is temporary to avoid code duplication between here & 
airflow/models/taskinstance.py

Review Comment:
   I think this relates to 
https://github.com/apache/airflow/pull/45960/files#r1967152850. This follows 
https://github.com/apache/airflow/pull/45727/files#diff-0274e1490fa6b4fc17f3d1e06a5037d2d15d699322c554ff901aefa013bc6e89R260.
 
   
   I guess we still need to do something in task sdk to make `from 
airflow.sdk.execution_time.task_runner import SUPERVISOR_COMMS` importable in 
tests or some other places. But would like to confirm with @ashb and 
@amoghrajesh whether my understanding is correct.



##########
tests/api_fastapi/execution_api/routes/test_asset_events.py:
##########
@@ -0,0 +1,99 @@
+# 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 pytest
+
+from airflow.models.asset import AssetActive, AssetEvent, AssetModel
+from airflow.utils import timezone
+
+DEFAULT_DATE = timezone.parse("2021-01-01T00:00:00")
+
+pytestmark = pytest.mark.db_test
+
+
+class TestGetAssetEventByAsset:
+    def test_get_by_name_uri(self, client, session):

Review Comment:
   Sure. Will update it



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