-
Notifications
You must be signed in to change notification settings - Fork 15.3k
Add endpoint to watch dag run until finish #51920
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
e1e3149
Add endpoint to watch dag run until finish
uranusjr edf8787
Include xcom in result if requested
uranusjr 77ec3ac
Use 'params' instead of literal params
uranusjr f852f6b
Mark endpoint as experimental
uranusjr 58d7fa5
Rename param key
uranusjr File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
85 changes: 85 additions & 0 deletions
85
airflow-core/src/airflow/api_fastapi/core_api/services/public/dag_run.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,85 @@ | ||
# 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 asyncio | ||
import itertools | ||
import json | ||
import operator | ||
from typing import TYPE_CHECKING, Any | ||
|
||
import attrs | ||
from sqlalchemy import select | ||
|
||
from airflow.models.dagrun import DagRun | ||
from airflow.models.xcom import XCOM_RETURN_KEY, XComModel | ||
from airflow.utils.session import create_session_async | ||
from airflow.utils.state import State | ||
|
||
if TYPE_CHECKING: | ||
from collections.abc import AsyncGenerator, Iterator | ||
|
||
|
||
@attrs.define | ||
class DagRunWaiter: | ||
"""Wait for the specified dag run to finish, and collect info from it.""" | ||
|
||
dag_id: str | ||
run_id: str | ||
interval: float | ||
result_task_ids: list[str] | None | ||
|
||
async def _get_dag_run(self) -> DagRun: | ||
async with create_session_async() as session: | ||
return await session.scalar(select(DagRun).filter_by(dag_id=self.dag_id, run_id=self.run_id)) | ||
|
||
def _serialize_xcoms(self) -> dict[str, Any]: | ||
xcom_query = XComModel.get_many( | ||
run_id=self.run_id, | ||
key=XCOM_RETURN_KEY, | ||
task_ids=self.result_task_ids, | ||
dag_ids=self.dag_id, | ||
) | ||
xcom_query = xcom_query.order_by(XComModel.task_id, XComModel.map_index) | ||
|
||
def _group_xcoms(g: Iterator[XComModel]) -> Any: | ||
entries = list(g) | ||
if len(entries) == 1 and entries[0].map_index < 0: # Unpack non-mapped task xcom. | ||
return entries[0].value | ||
return [entry.value for entry in entries] # Task is mapped; return all xcoms in a list. | ||
|
||
return { | ||
task_id: _group_xcoms(g) | ||
for task_id, g in itertools.groupby(xcom_query, key=operator.attrgetter("task_id")) | ||
} | ||
|
||
def _serialize_response(self, dag_run: DagRun) -> str: | ||
resp = {"state": dag_run.state} | ||
if dag_run.state not in State.finished_dr_states: | ||
return json.dumps(resp) | ||
if self.result_task_ids: | ||
resp["results"] = self._serialize_xcoms() | ||
return json.dumps(resp) | ||
|
||
async def wait(self) -> AsyncGenerator[str, None]: | ||
yield self._serialize_response(dag_run := await self._get_dag_run()) | ||
yield "\n" | ||
while dag_run.state not in State.finished_dr_states: | ||
await asyncio.sleep(self.interval) | ||
yield self._serialize_response(dag_run := await self._get_dag_run()) | ||
yield "\n" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,7 @@ | ||
// generated with @7nohe/[email protected] | ||
|
||
import { UseQueryResult } from "@tanstack/react-query"; | ||
import { AssetService, AuthLinksService, BackfillService, CalendarService, ConfigService, ConnectionService, DagParsingService, DagReportService, DagRunService, DagService, DagSourceService, DagStatsService, DagVersionService, DagWarningService, DashboardService, DependenciesService, EventLogService, ExtraLinksService, GridService, ImportErrorService, JobService, LoginService, MonitorService, PluginService, PoolService, ProviderService, StructureService, TaskInstanceService, TaskService, VariableService, VersionService, XcomService } from "../requests/services.gen"; | ||
import { AssetService, AuthLinksService, BackfillService, CalendarService, ConfigService, ConnectionService, DagParsingService, DagReportService, DagRunService, DagService, DagSourceService, DagStatsService, DagVersionService, DagWarningService, DashboardService, DependenciesService, EventLogService, ExperimentalService, ExtraLinksService, GridService, ImportErrorService, JobService, LoginService, MonitorService, PluginService, PoolService, ProviderService, StructureService, TaskInstanceService, TaskService, VariableService, VersionService, XcomService } from "../requests/services.gen"; | ||
import { DagRunState, DagWarningType } from "../requests/types.gen"; | ||
export type AssetServiceGetAssetsDefaultResponse = Awaited<ReturnType<typeof AssetService.getAssets>>; | ||
export type AssetServiceGetAssetsQueryResult<TData = AssetServiceGetAssetsDefaultResponse, TError = unknown> = UseQueryResult<TData, TError>; | ||
|
@@ -159,6 +159,24 @@ export const UseDagRunServiceGetDagRunsKeyFn = ({ dagId, endDateGte, endDateLte, | |
updatedAtGte?: string; | ||
updatedAtLte?: string; | ||
}, queryKey?: Array<unknown>) => [useDagRunServiceGetDagRunsKey, ...(queryKey ?? [{ dagId, endDateGte, endDateLte, limit, logicalDateGte, logicalDateLte, offset, orderBy, runAfterGte, runAfterLte, runIdPattern, runType, startDateGte, startDateLte, state, updatedAtGte, updatedAtLte }])]; | ||
export type DagRunServiceWaitDagRunUntilFinishedDefaultResponse = Awaited<ReturnType<typeof DagRunService.waitDagRunUntilFinished>>; | ||
export type DagRunServiceWaitDagRunUntilFinishedQueryResult<TData = DagRunServiceWaitDagRunUntilFinishedDefaultResponse, TError = unknown> = UseQueryResult<TData, TError>; | ||
export const useDagRunServiceWaitDagRunUntilFinishedKey = "DagRunServiceWaitDagRunUntilFinished"; | ||
export const UseDagRunServiceWaitDagRunUntilFinishedKeyFn = ({ dagId, dagRunId, interval, result }: { | ||
dagId: string; | ||
dagRunId: string; | ||
interval: number; | ||
result?: string[]; | ||
}, queryKey?: Array<unknown>) => [useDagRunServiceWaitDagRunUntilFinishedKey, ...(queryKey ?? [{ dagId, dagRunId, interval, result }])]; | ||
export type ExperimentalServiceWaitDagRunUntilFinishedDefaultResponse = Awaited<ReturnType<typeof ExperimentalService.waitDagRunUntilFinished>>; | ||
export type ExperimentalServiceWaitDagRunUntilFinishedQueryResult<TData = ExperimentalServiceWaitDagRunUntilFinishedDefaultResponse, TError = unknown> = UseQueryResult<TData, TError>; | ||
export const useExperimentalServiceWaitDagRunUntilFinishedKey = "ExperimentalServiceWaitDagRunUntilFinished"; | ||
export const UseExperimentalServiceWaitDagRunUntilFinishedKeyFn = ({ dagId, dagRunId, interval, result }: { | ||
dagId: string; | ||
dagRunId: string; | ||
interval: number; | ||
result?: string[]; | ||
}, queryKey?: Array<unknown>) => [useExperimentalServiceWaitDagRunUntilFinishedKey, ...(queryKey ?? [{ dagId, dagRunId, interval, result }])]; | ||
export type DagSourceServiceGetDagSourceDefaultResponse = Awaited<ReturnType<typeof DagSourceService.getDagSource>>; | ||
export type DagSourceServiceGetDagSourceQueryResult<TData = DagSourceServiceGetDagSourceDefaultResponse, TError = unknown> = UseQueryResult<TData, TError>; | ||
export const useDagSourceServiceGetDagSourceKey = "DagSourceServiceGetDagSource"; | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.