pierrejeambrun commented on code in PR #50443: URL: https://github.com/apache/airflow/pull/50443#discussion_r2095678496
########## airflow-core/src/airflow/api_fastapi/core_api/services/public/task_instances.py: ########## @@ -0,0 +1,285 @@ +# 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 structlog +from fastapi import HTTPException, Query, status +from fastapi.exceptions import RequestValidationError +from pydantic import ValidationError +from pytest import Session +from sqlalchemy import select +from sqlalchemy.orm import joinedload + +from airflow.api_fastapi.common.dagbag import DagBagDep +from airflow.api_fastapi.common.db.common import SessionDep +from airflow.api_fastapi.core_api.datamodels.common import ( + BulkActionNotOnExistence, + BulkActionResponse, + BulkBody, + BulkCreateAction, + BulkDeleteAction, + BulkUpdateAction, +) +from airflow.api_fastapi.core_api.datamodels.task_instances import BulkTaskInstanceBody, PatchTaskInstanceBody +from airflow.api_fastapi.core_api.security import GetUserDep +from airflow.api_fastapi.core_api.services.public.common import BulkService +from airflow.listeners.listener import get_listener_manager +from airflow.models.dag import DAG +from airflow.models.taskinstance import TaskInstance as TI +from airflow.utils.state import TaskInstanceState + +log = structlog.get_logger(__name__) + + +def _patch_ti_validate_request( + dag_id: str, + dag_run_id: str, + task_id: str, + dag_bag: DagBagDep, + body: PatchTaskInstanceBody, + session: SessionDep, + map_index: int | None = -1, + update_mask: list[str] | None = Query(None), +) -> tuple[DAG, list[TI], dict]: + dag = dag_bag.get_dag(dag_id) + if not dag: + raise HTTPException(status.HTTP_404_NOT_FOUND, f"DAG {dag_id} not found") + + if not dag.has_task(task_id): + raise HTTPException(status.HTTP_404_NOT_FOUND, f"Task '{task_id}' not found in DAG '{dag_id}'") + + query = ( + select(TI) + .where(TI.dag_id == dag_id, TI.run_id == dag_run_id, TI.task_id == task_id) + .join(TI.dag_run) + .options(joinedload(TI.rendered_task_instance_fields)) + ) + if map_index is not None: + query = query.where(TI.map_index == map_index) + + tis = session.scalars(query).all() + + err_msg_404 = ( + f"The Task Instance with dag_id: `{dag_id}`, run_id: `{dag_run_id}`, task_id: `{task_id}` and map_index: `{map_index}` was not found.", + ) + if len(tis) == 0: + raise HTTPException(status.HTTP_404_NOT_FOUND, err_msg_404) + + fields_to_update = body.model_fields_set + if update_mask: + fields_to_update = fields_to_update.intersection(update_mask) + else: + try: + PatchTaskInstanceBody.model_validate(body) + except ValidationError as e: + raise RequestValidationError(errors=e.errors()) + + return dag, list(tis), body.model_dump(include=fields_to_update, by_alias=True) + + +class BulkTaskInstanceService(BulkService[BulkTaskInstanceBody]): + """Service for handling bulk operations on task instances.""" + + def __init__( + self, + session: Session, + request: BulkBody[BulkTaskInstanceBody], + dag_id: str, + dag_run_id: str, + dag_bag: DagBagDep, + user: GetUserDep, + ): + super().__init__(session, request) + self.dag_id = dag_id + self.dag_run_id = dag_run_id + self.dag_bag = dag_bag + self.user = user + + def categorize_task_instances( + self, task_ids: set + ) -> tuple[dict[tuple[str, int], TI], set[str], set[str]]: + """ + Categorize the given task_ids into matched_task_ids and not_found_task_ids based on existing task_ids. + + :param task_ids: set of task_ids + :return: tuple of (task_instances_map, matched_task_ids, not_found_task_ids) + """ + query = select(TI).where( + TI.dag_id == self.dag_id, TI.run_id == self.dag_run_id, TI.task_id.in_(task_ids) + ) + task_instances = self.session.scalars(query).all() + task_instances_map = { + (ti.task_id, ti.map_index if ti.map_index is not None else -1): ti for ti in task_instances + } + matched_task_ids = {task_id for (task_id, _) in task_instances_map.keys()} + not_found_task_ids = task_ids - matched_task_ids + return task_instances_map, matched_task_ids, not_found_task_ids Review Comment: I think `matched_task_ids` and `not_found_task_ids` should be tuples of `(task_id, map_index)` too. This will later on simplify the implementation because we have two layers to check for existing tasks, the first layer is `task_id` only, then we do another check on the map_index too. We can do all of that in `categorize_task_instances` I believe. ```suggestion return task_instances_map, matched_task_ids, not_found_task_ids ``` ########## airflow-core/src/airflow/api_fastapi/core_api/services/public/task_instances.py: ########## @@ -0,0 +1,285 @@ +# 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 structlog +from fastapi import HTTPException, Query, status +from fastapi.exceptions import RequestValidationError +from pydantic import ValidationError +from pytest import Session +from sqlalchemy import select +from sqlalchemy.orm import joinedload + +from airflow.api_fastapi.common.dagbag import DagBagDep +from airflow.api_fastapi.common.db.common import SessionDep +from airflow.api_fastapi.core_api.datamodels.common import ( + BulkActionNotOnExistence, + BulkActionResponse, + BulkBody, + BulkCreateAction, + BulkDeleteAction, + BulkUpdateAction, +) +from airflow.api_fastapi.core_api.datamodels.task_instances import BulkTaskInstanceBody, PatchTaskInstanceBody +from airflow.api_fastapi.core_api.security import GetUserDep +from airflow.api_fastapi.core_api.services.public.common import BulkService +from airflow.listeners.listener import get_listener_manager +from airflow.models.dag import DAG +from airflow.models.taskinstance import TaskInstance as TI +from airflow.utils.state import TaskInstanceState + +log = structlog.get_logger(__name__) + + +def _patch_ti_validate_request( + dag_id: str, + dag_run_id: str, + task_id: str, + dag_bag: DagBagDep, + body: PatchTaskInstanceBody, + session: SessionDep, + map_index: int | None = -1, + update_mask: list[str] | None = Query(None), +) -> tuple[DAG, list[TI], dict]: + dag = dag_bag.get_dag(dag_id) + if not dag: + raise HTTPException(status.HTTP_404_NOT_FOUND, f"DAG {dag_id} not found") + + if not dag.has_task(task_id): + raise HTTPException(status.HTTP_404_NOT_FOUND, f"Task '{task_id}' not found in DAG '{dag_id}'") + + query = ( + select(TI) + .where(TI.dag_id == dag_id, TI.run_id == dag_run_id, TI.task_id == task_id) + .join(TI.dag_run) + .options(joinedload(TI.rendered_task_instance_fields)) + ) + if map_index is not None: + query = query.where(TI.map_index == map_index) + + tis = session.scalars(query).all() + + err_msg_404 = ( + f"The Task Instance with dag_id: `{dag_id}`, run_id: `{dag_run_id}`, task_id: `{task_id}` and map_index: `{map_index}` was not found.", + ) + if len(tis) == 0: + raise HTTPException(status.HTTP_404_NOT_FOUND, err_msg_404) + + fields_to_update = body.model_fields_set + if update_mask: + fields_to_update = fields_to_update.intersection(update_mask) + else: + try: + PatchTaskInstanceBody.model_validate(body) + except ValidationError as e: + raise RequestValidationError(errors=e.errors()) + + return dag, list(tis), body.model_dump(include=fields_to_update, by_alias=True) + + +class BulkTaskInstanceService(BulkService[BulkTaskInstanceBody]): + """Service for handling bulk operations on task instances.""" + + def __init__( + self, + session: Session, + request: BulkBody[BulkTaskInstanceBody], + dag_id: str, + dag_run_id: str, + dag_bag: DagBagDep, + user: GetUserDep, + ): + super().__init__(session, request) + self.dag_id = dag_id + self.dag_run_id = dag_run_id + self.dag_bag = dag_bag + self.user = user + + def categorize_task_instances( + self, task_ids: set + ) -> tuple[dict[tuple[str, int], TI], set[str], set[str]]: + """ + Categorize the given task_ids into matched_task_ids and not_found_task_ids based on existing task_ids. + + :param task_ids: set of task_ids + :return: tuple of (task_instances_map, matched_task_ids, not_found_task_ids) + """ + query = select(TI).where( + TI.dag_id == self.dag_id, TI.run_id == self.dag_run_id, TI.task_id.in_(task_ids) + ) + task_instances = self.session.scalars(query).all() + task_instances_map = { + (ti.task_id, ti.map_index if ti.map_index is not None else -1): ti for ti in task_instances + } + matched_task_ids = {task_id for (task_id, _) in task_instances_map.keys()} + not_found_task_ids = task_ids - matched_task_ids + return task_instances_map, matched_task_ids, not_found_task_ids + + def _patch_task_instance_state( + self, + dag: DAG, + task_instance_body: BulkTaskInstanceBody, + data: dict, + tis: list[TI], + ) -> None: + if task_instance_body.map_index is None: + task_instance_body.map_index = -1 + Review Comment: Why are we forcing this ? For patch TI endpoint, specifying `None` for a mapped task instance will operate on all map_indexes, that should already work and I think we should allow this for bulk action too. -- 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: commits-unsubscr...@airflow.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org