Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@ class DAGDetailsResponse(DAGResponse):
last_parsed: datetime | None
default_args: abc.Mapping | None
owner_links: dict[str, str] | None = None
is_favorite: bool = False

@field_validator("timezone", mode="before")
@classmethod
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ class DAGWithLatestDagRunsResponse(DAGResponse):
asset_expression: dict | None
latest_dag_runs: list[DAGRunResponse]
pending_actions: list[HITLDetail]
is_favorite: bool


class DAGWithLatestDagRunsCollectionResponse(BaseModel):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1686,6 +1686,9 @@ components:
$ref: '#/components/schemas/HITLDetail'
type: array
title: Pending Actions
is_favorite:
type: boolean
title: Is Favorite
file_token:
type: string
title: File Token
Expand Down Expand Up @@ -1721,6 +1724,7 @@ components:
- asset_expression
- latest_dag_runs
- pending_actions
- is_favorite
- file_token
title: DAGWithLatestDagRunsResponse
description: DAG with latest dag runs response serializer.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10017,6 +10017,10 @@ components:
type: object
- type: 'null'
title: Owner Links
is_favorite:
type: boolean
title: Is Favorite
default: false
file_token:
type: string
title: File Token
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,9 @@ def get_dag(
),
dependencies=[Depends(requires_access_dag(method="GET"))],
)
def get_dag_details(dag_id: str, session: SessionDep, dag_bag: DagBagDep) -> DAGDetailsResponse:
def get_dag_details(
dag_id: str, session: SessionDep, dag_bag: DagBagDep, user: GetUserDep
) -> DAGDetailsResponse:
"""Get details of DAG."""
dag = get_latest_version_of_dag(dag_bag, dag_id, session)

Expand All @@ -221,7 +223,19 @@ def get_dag_details(dag_id: str, session: SessionDep, dag_bag: DagBagDep) -> DAG
if not key.startswith("_") and not hasattr(dag_model, key):
setattr(dag_model, key, value)

return dag_model
# Check if this DAG is marked as favorite by the current user
user_id = str(user.get_id())
is_favorite = (
session.scalar(
select(DagFavorite.dag_id).where(DagFavorite.user_id == user_id, DagFavorite.dag_id == dag_id)
)
is not None
)

# Add is_favorite field to the DAG model
setattr(dag_model, "is_favorite", is_favorite)

return DAGDetailsResponse.model_validate(dag_model)


@dags_router.patch(
Expand Down
11 changes: 11 additions & 0 deletions airflow-core/src/airflow/api_fastapi/core_api/routes/ui/dags.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,12 @@
)
from airflow.api_fastapi.core_api.openapi.exceptions import create_openapi_http_exception_doc
from airflow.api_fastapi.core_api.security import (
GetUserDep,
ReadableDagsFilterDep,
requires_access_dag,
)
from airflow.models import DagModel, DagRun
from airflow.models.dag_favorite import DagFavorite
from airflow.models.hitl import HITLDetail
from airflow.models.taskinstance import TaskInstance
from airflow.utils.state import TaskInstanceState
Expand Down Expand Up @@ -114,6 +116,7 @@ def get_dags(
has_pending_actions: QueryPendingActionsFilter,
readable_dags_filter: ReadableDagsFilterDep,
session: SessionDep,
user: GetUserDep,
dag_runs_limit: int = 10,
) -> DAGWithLatestDagRunsCollectionResponse:
"""Get DAGs with recent DagRun."""
Expand Down Expand Up @@ -153,6 +156,13 @@ def get_dags(

dags = [dag for dag in session.scalars(dags_select)]

# Fetch favorite status for each DAG for the current user
user_id = str(user.get_id())
favorites_select = select(DagFavorite.dag_id).where(
DagFavorite.user_id == user_id, DagFavorite.dag_id.in_([dag.dag_id for dag in dags])
)
favorite_dag_ids = set(session.scalars(favorites_select))

# Populate the last 'dag_runs_limit' DagRuns for each DAG
recent_runs_subquery = (
select(
Expand Down Expand Up @@ -224,6 +234,7 @@ def get_dags(
"asset_expression": dag.asset_expression,
"latest_dag_runs": [],
"pending_actions": pending_actions_by_dag_id[dag.dag_id],
"is_favorite": dag.dag_id in favorite_dag_ids,
}
)
for dag in dags
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2041,6 +2041,11 @@ export const $DAGDetailsResponse = {
],
title: 'Owner Links'
},
is_favorite: {
type: 'boolean',
title: 'Is Favorite',
default: false
},
file_token: {
type: 'string',
title: 'File Token',
Expand Down Expand Up @@ -7343,6 +7348,10 @@ export const $DAGWithLatestDagRunsResponse = {
type: 'array',
title: 'Pending Actions'
},
is_favorite: {
type: 'boolean',
title: 'Is Favorite'
},
file_token: {
type: 'string',
title: 'File Token',
Expand All @@ -7351,7 +7360,7 @@ export const $DAGWithLatestDagRunsResponse = {
}
},
type: 'object',
required: ['dag_id', 'dag_display_name', 'is_paused', 'is_stale', 'last_parsed_time', 'last_parse_duration', 'last_expired', 'bundle_name', 'bundle_version', 'relative_fileloc', 'fileloc', 'description', 'timetable_summary', 'timetable_description', 'tags', 'max_active_tasks', 'max_active_runs', 'max_consecutive_failed_dag_runs', 'has_task_concurrency_limits', 'has_import_errors', 'next_dagrun_logical_date', 'next_dagrun_data_interval_start', 'next_dagrun_data_interval_end', 'next_dagrun_run_after', 'owners', 'asset_expression', 'latest_dag_runs', 'pending_actions', 'file_token'],
required: ['dag_id', 'dag_display_name', 'is_paused', 'is_stale', 'last_parsed_time', 'last_parse_duration', 'last_expired', 'bundle_name', 'bundle_version', 'relative_fileloc', 'fileloc', 'description', 'timetable_summary', 'timetable_description', 'tags', 'max_active_tasks', 'max_active_runs', 'max_consecutive_failed_dag_runs', 'has_task_concurrency_limits', 'has_import_errors', 'next_dagrun_logical_date', 'next_dagrun_data_interval_start', 'next_dagrun_data_interval_end', 'next_dagrun_run_after', 'owners', 'asset_expression', 'latest_dag_runs', 'pending_actions', 'is_favorite', 'file_token'],
title: 'DAGWithLatestDagRunsResponse',
description: 'DAG with latest dag runs response serializer.'
} as const;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -562,6 +562,7 @@ export type DAGDetailsResponse = {
owner_links?: {
[key: string]: (string);
} | null;
is_favorite?: boolean;
/**
* Return file token.
*/
Expand Down Expand Up @@ -1834,6 +1835,7 @@ export type DAGWithLatestDagRunsResponse = {
} | null;
latest_dag_runs: Array<DAGRunResponse>;
pending_actions: Array<HITLDetail>;
is_favorite: boolean;
/**
* Return file token.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,44 +17,39 @@
* under the License.
*/
import { Box } from "@chakra-ui/react";
import { useCallback, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { FiStar } from "react-icons/fi";

import { useDagServiceGetDagsUi } from "openapi/queries";
import { useFavoriteDag } from "src/queries/useFavoriteDag";
import { useUnfavoriteDag } from "src/queries/useUnfavoriteDag";
import { useToggleFavoriteDag } from "src/queries/useToggleFavoriteDag";

import ActionButton from "../ui/ActionButton";

type FavoriteDagButtonProps = {
readonly dagId: string;
readonly isFavorite?: boolean;
readonly withText?: boolean;
};

export const FavoriteDagButton = ({ dagId, withText = true }: FavoriteDagButtonProps) => {
export const FavoriteDagButton = ({ dagId, isFavorite = false, withText = true }: FavoriteDagButtonProps) => {
const { t: translate } = useTranslation("dags");
const { data: favorites } = useDagServiceGetDagsUi({ isFavorite: true });

const isFavorite = useMemo(
() => favorites?.dags.some((fav) => fav.dag_id === dagId) ?? false,
[favorites, dagId],
);

const { mutate: favoriteDag } = useFavoriteDag();
const { mutate: unfavoriteDag } = useUnfavoriteDag();

const onToggle = useCallback(() => {
const mutationFn = isFavorite ? unfavoriteDag : favoriteDag;
const { isLoading, toggleFavorite } = useToggleFavoriteDag(dagId);

mutationFn({ dagId });
}, [dagId, isFavorite, favoriteDag, unfavoriteDag]);
const onToggle = () => toggleFavorite(isFavorite);

return (
<Box>
<ActionButton
actionName={isFavorite ? translate("unfavoriteDag") : translate("favoriteDag")}
icon={<FiStar style={{ fill: isFavorite ? "var(--chakra-colors-brand-solid)" : "none" }} />}
icon={
<FiStar
style={{
fill: isFavorite ? "var(--chakra-colors-brand-solid)" : "none",
stroke: "var(--chakra-colors-brand-solid)",
}}
/>
}
loading={isLoading}
onClick={onToggle}
text={isFavorite ? translate("unfavoriteDag") : translate("favoriteDag")}
withText={withText}
Expand Down
4 changes: 4 additions & 0 deletions airflow-core/src/airflow/ui/src/mocks/handlers/dags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export const handlers: Array<HttpHandler> = [
fileloc: "/airflow/dags/tutorial_taskflow_api.py",
has_import_errors: false,
has_task_concurrency_limits: false,
is_favorite: true,
is_paused: false,
is_stale: false,
last_parsed_time: "2025-01-13T07:34:01.593459Z",
Expand Down Expand Up @@ -69,6 +70,7 @@ export const handlers: Array<HttpHandler> = [
fileloc: "/airflow/dags/tutorial_taskflow_api_failed.py",
has_import_errors: false,
has_task_concurrency_limits: false,
is_favorite: false,
is_paused: false,
is_stale: false,
last_parsed_time: "2025-01-13T07:34:01.593459Z",
Expand Down Expand Up @@ -128,6 +130,7 @@ export const handlers: Array<HttpHandler> = [
fileloc: "/airflow/dags/tutorial_taskflow_api_failed.py",
has_import_errors: false,
has_task_concurrency_limits: false,
is_favorite: false,
is_paused: false,
is_stale: false,
last_expired: null,
Expand Down Expand Up @@ -155,6 +158,7 @@ export const handlers: Array<HttpHandler> = [
fileloc: "/airflow/dags/tutorial_taskflow_api_success.py",
has_import_errors: false,
has_task_concurrency_limits: false,
is_favorite: true,
is_paused: false,
is_stale: false,
last_expired: null,
Expand Down
2 changes: 1 addition & 1 deletion airflow-core/src/airflow/ui/src/pages/Dag/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ export const Header = ({
text={translate("dag:header.buttons.dagDocs")}
/>
)}
<FavoriteDagButton dagId={dag.dag_id} withText={true} />
<FavoriteDagButton dagId={dag.dag_id} isFavorite={dag.is_favorite} withText />
<Menu.Root>
<Menu.Trigger asChild>
<Button aria-label={translate("dag:header.buttons.advanced")} variant="outline">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ const mockDag = {
fileloc: "/files/dags/nested_task_groups.py",
has_import_errors: false,
has_task_concurrency_limits: false,
is_favorite: false,
is_paused: false,
is_stale: false,
last_expired: null,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ export const DagCard = ({ dag }: Props) => {
isPaused={dag.is_paused}
withText={false}
/>
<FavoriteDagButton dagId={dag.dag_id} withText={false} />
<FavoriteDagButton dagId={dag.dag_id} isFavorite={dag.is_favorite} withText={false} />
<DeleteDagButton dagDisplayName={dag.dag_display_name} dagId={dag.dag_id} withText={false} />
</HStack>
</Flex>
Expand Down
5 changes: 3 additions & 2 deletions airflow-core/src/airflow/ui/src/pages/DagsList/DagsList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -164,8 +164,9 @@ const createColumns = (
header: "",
},
{
accessorKey: "favorite",
cell: ({ row: { original } }) => <FavoriteDagButton dagId={original.dag_id} withText={false} />,
cell: ({ row: { original } }) => (
<FavoriteDagButton dagId={original.dag_id} isFavorite={original.is_favorite} withText={false} />
),
enableHiding: false,
enableSorting: false,
header: "",
Expand Down
33 changes: 0 additions & 33 deletions airflow-core/src/airflow/ui/src/queries/useFavoriteDag.ts

This file was deleted.

66 changes: 66 additions & 0 deletions airflow-core/src/airflow/ui/src/queries/useToggleFavoriteDag.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*!
* 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.
*/
import { useQueryClient } from "@tanstack/react-query";
import { useCallback } from "react";

import {
useDagServiceGetDagsUiKey,
useDagServiceFavoriteDag,
useDagServiceUnfavoriteDag,
UseDagServiceGetDagDetailsKeyFn,
} from "openapi/queries";

export const useToggleFavoriteDag = (dagId: string) => {
const queryClient = useQueryClient();

const onSuccess = useCallback(async () => {
// Invalidate the DAGs list query
await queryClient.invalidateQueries({
queryKey: [useDagServiceGetDagsUiKey, UseDagServiceGetDagDetailsKeyFn({ dagId }, [{ dagId }])],
});

// Invalidate the specific DAG details query for this DAG
await queryClient.invalidateQueries({
queryKey: UseDagServiceGetDagDetailsKeyFn({ dagId }, [{ dagId }]),
});
}, [queryClient, dagId]);

const favoriteMutation = useDagServiceFavoriteDag({
onSuccess,
});

const unfavoriteMutation = useDagServiceUnfavoriteDag({
onSuccess,
});

const toggleFavorite = useCallback(
(isFavorite: boolean) => {
const mutation = isFavorite ? unfavoriteMutation : favoriteMutation;

mutation.mutate({ dagId });
},
[dagId, favoriteMutation, unfavoriteMutation],
);

return {
error: favoriteMutation.error ?? unfavoriteMutation.error,
isLoading: favoriteMutation.isPending || unfavoriteMutation.isPending,
toggleFavorite,
};
};
Loading
Loading