-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathuseTasks.ts
More file actions
178 lines (155 loc) · 4.86 KB
/
Copy pathuseTasks.ts
File metadata and controls
178 lines (155 loc) · 4.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useAuthStore, useUserQuery } from "@/features/auth";
import { logger } from "@/lib/logger";
import {
createTask,
deleteTask,
getTask,
getTasks,
runTaskInCloud,
updateTask,
} from "../api";
import { filterAndSortTasks, useTaskStore } from "../stores/taskStore";
import type { CreateTaskOptions, Task } from "../types";
const log = logger.scope("tasks-mutations");
const ACTIVE_TASK_POLLING_INTERVAL_MS = 5_000;
const TERMINAL_TASK_RUN_STATUSES = new Set([
"completed",
"failed",
"cancelled",
]);
export const taskKeys = {
all: ["tasks"] as const,
lists: () => [...taskKeys.all, "list"] as const,
list: (filters?: {
repository?: string;
createdBy?: number;
originProduct?: string;
}) => [...taskKeys.lists(), filters] as const,
details: () => [...taskKeys.all, "detail"] as const,
detail: (id: string) => [...taskKeys.details(), id] as const,
};
export function getTaskPollingInterval(
taskData: Task | Task[] | undefined,
): number | false {
if (!taskData) {
return false;
}
if (Array.isArray(taskData)) {
return taskData.some((task) => {
const status = task.latest_run?.status;
return !!status && !TERMINAL_TASK_RUN_STATUSES.has(status);
})
? ACTIVE_TASK_POLLING_INTERVAL_MS
: false;
}
const status = taskData.latest_run?.status;
return status && !TERMINAL_TASK_RUN_STATUSES.has(status)
? ACTIVE_TASK_POLLING_INTERVAL_MS
: false;
}
export function useTasks(filters?: {
repository?: string;
originProduct?: string;
}) {
const { projectId, oauthAccessToken } = useAuthStore();
const { data: currentUser } = useUserQuery();
const { sortMode, filter } = useTaskStore();
const queryFilters = {
...filters,
createdBy: currentUser?.id,
};
const query = useQuery({
queryKey: taskKeys.list(queryFilters),
queryFn: () => getTasks(queryFilters),
enabled: !!projectId && !!oauthAccessToken && !!currentUser?.id,
refetchInterval: (query) =>
getTaskPollingInterval(query.state.data as Task[] | undefined),
});
// Mobile never runs tasks locally — hide desktop-only local runs so the
// mobile list mirrors what's actually shareable across devices.
const cloudTasks = (query.data ?? []).filter(
(task) => task.latest_run?.environment !== "local",
);
const filteredTasks = filterAndSortTasks(cloudTasks, sortMode, filter);
return {
tasks: filteredTasks,
allTasks: cloudTasks,
isLoading: query.isLoading,
error: query.error?.message ?? null,
refetch: query.refetch,
};
}
export function useTask(taskId: string) {
const { projectId, oauthAccessToken } = useAuthStore();
return useQuery({
queryKey: taskKeys.detail(taskId),
queryFn: () => getTask(taskId),
enabled: !!projectId && !!oauthAccessToken && !!taskId,
refetchInterval: (query) =>
getTaskPollingInterval(query.state.data as Task | undefined),
});
}
export function useCreateTask() {
const queryClient = useQueryClient();
const invalidateTasks = () => {
queryClient.invalidateQueries({ queryKey: taskKeys.lists() });
};
const mutation = useMutation({
mutationFn: (options: CreateTaskOptions) => createTask(options),
onSuccess: () => {
invalidateTasks();
},
onError: (error) => {
log.error("Failed to create task", error.message);
},
});
return { ...mutation, invalidateTasks };
}
export function useUpdateTask() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({
taskId,
updates,
}: {
taskId: string;
updates: Partial<Task>;
}) => updateTask(taskId, updates),
onSuccess: (updatedTask, { taskId }) => {
// Update the detail cache immediately
queryClient.setQueryData(taskKeys.detail(taskId), updatedTask);
queryClient.invalidateQueries({ queryKey: taskKeys.lists() });
},
onError: (error) => {
log.error("Failed to update task", error.message);
},
});
}
export function useDeleteTask() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (taskId: string) => deleteTask(taskId),
onSuccess: (_, taskId) => {
// Remove from detail cache
queryClient.removeQueries({ queryKey: taskKeys.detail(taskId) });
queryClient.invalidateQueries({ queryKey: taskKeys.lists() });
},
onError: (error) => {
log.error("Failed to delete task", error.message);
},
});
}
export function useRunTask() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (taskId: string) => runTaskInCloud(taskId),
onSuccess: (updatedTask, taskId) => {
queryClient.setQueryData(taskKeys.detail(taskId), updatedTask);
queryClient.invalidateQueries({ queryKey: taskKeys.lists() });
},
onError: (error) => {
log.error("Failed to run task", error.message);
},
});
}