feat: add helper function to monitor task state during execution

This commit is contained in:
Pablo Lara
2024-11-06 08:29:39 +01:00
parent 76c6065a80
commit e444e39fd0
3 changed files with 74 additions and 16 deletions
+38
View File
@@ -1,7 +1,45 @@
import { getTask } from "@/actions/task";
import { MetaDataProps } from "@/types";
export async function checkTaskStatus(
taskId: string,
): Promise<{ completed: boolean; error?: string }> {
const MAX_RETRIES = 20; // Define the maximum number of attempts before stopping the polling
const RETRY_DELAY = 1000; // Delay time between each poll (in milliseconds)
for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
const task = await getTask(taskId);
if (task.error) {
console.error(`Error retrieving task: ${task.error}`);
return { completed: false, error: task.error };
}
const state = task.data.attributes.state;
switch (state) {
case "completed":
return { completed: true };
case "failed":
return { completed: false, error: task.data.attributes.result.error };
case "available":
case "scheduled":
case "executing":
// Continue waiting if the task is still in progress
await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY));
break;
default:
console.warn(`Unexpected task state: ${state}`);
return { completed: false, error: "Unexpected task state" };
}
}
return { completed: false, error: "Max retries exceeded" };
}
export const wait = (ms: number) =>
new Promise((resolve) => setTimeout(resolve, ms));
// Helper function to create dictionaries by type
export function createDict(type: string, data: any) {
const includedField = data?.included?.filter(