Line data Source code
1 : import { z } from 'zod'
2 : import { fromZodError } from 'zod-validation-error'
3 :
4 : import type { TaskResponse } from '@comfyorg/api-client/taskSchema'
5 : import { zTaskResponse } from '@comfyorg/api-client/taskSchema'
6 : import { api } from '@/scripts/api'
7 : import { toError } from '@comfyorg/shared-frontend-utils/errorUtil'
8 :
9 2356 : const TASKS_ENDPOINT = '/tasks'
10 :
11 : /**
12 : * Result payload of a `task:download_file` task.
13 : *
14 : * `/tasks` is shared by every task type, so `TaskResponse.result` stays the
15 : * generated opaque record and each caller parses the shape its own task type
16 : * produces. Narrowing `result` on the shared response instead makes `getTask`
17 : * reject every other task type's result, which silently disables
18 : * reconciliation for those callers.
19 : */
20 2356 : const zDownloadFileResult = z.object({
21 : success: z.boolean(),
22 : file_path: z.string().optional(),
23 : bytes_downloaded: z.number().optional(),
24 : content_type: z.string().optional(),
25 : hash: z.string().optional(),
26 : filename: z.string().optional(),
27 : asset_id: z.string().optional(),
28 : metadata: z.record(z.string(), z.unknown()).optional(),
29 : error: z.string().optional()
30 : })
31 :
32 : export type TaskResult<T> = { ok: true; value: T } | { ok: false; error: Error }
33 : export type DownloadFileResult = z.infer<typeof zDownloadFileResult>
34 :
35 : /** Returns the download-file result, or `undefined` if it is absent or malformed. */
36 0 : export function parseDownloadFileResult(
37 : result: unknown
38 : ): DownloadFileResult | undefined {
39 0 : const parsed = zDownloadFileResult.safeParse(result)
40 0 : return parsed.success ? parsed.data : undefined
41 : }
42 :
43 : /**
44 : * Outcome of a cancellation request. Callers need these apart because each one
45 : * implies a different next step: wait for a terminal status, settle locally
46 : * because none is coming, or re-read the task's real status.
47 : */
48 : export type CancelTaskOutcome =
49 : /** The backend accepted it and will report a terminal status. */
50 : | 'cancelling'
51 : /** The task row is gone, so no terminal status will ever arrive. */
52 : | 'missing'
53 : /** The backend refused to cancel from the task's current state. */
54 : | 'not-cancellable'
55 :
56 : /**
57 : * Identifier for a background task tracked by the `/tasks` API.
58 : *
59 : * Backed by `TaskResponse.id` which is `z.string().uuid()`. This alias names
60 : * that primitive at use sites without changing structural typing.
61 : */
62 : export type TaskId = string
63 :
64 : /**
65 : * A `getTask` failure that proves the task row no longer exists, as opposed to
66 : * a transient failure worth retrying. Callers tracking a task that can never
67 : * reach a terminal status need to tell those apart to stop polling it.
68 : */
69 2356 : export class TaskNotFoundError extends Error {
70 : constructor(taskId: TaskId) {
71 1 : super(`Task not found: ${taskId}`)
72 1 : this.name = 'TaskNotFoundError'
73 : }
74 : }
75 :
76 2356 : function createTaskService() {
77 3 : async function getTask(taskId: TaskId): Promise<TaskResult<TaskResponse>> {
78 3 : try {
79 3 : const res = await api.fetchApi(
80 : `${TASKS_ENDPOINT}/${encodeURIComponent(taskId)}`
81 : )
82 :
83 3 : if (!res.ok) {
84 1 : return {
85 : ok: false,
86 : error:
87 : res.status === 404
88 : ? new TaskNotFoundError(taskId)
89 : : new Error(`Failed to get task ${taskId}: ${res.status}`)
90 : }
91 : }
92 :
93 2 : const data: unknown = await res.json()
94 2 : const result = zTaskResponse.safeParse(data)
95 :
96 2 : if (!result.success) {
97 0 : return {
98 : ok: false,
99 : error: new Error(fromZodError(result.error).message)
100 : }
101 : }
102 :
103 2 : return { ok: true, value: result.data }
104 : } catch (error) {
105 0 : return { ok: false, error: toError(error) }
106 : }
107 : }
108 :
109 3 : async function cancelTask(
110 : taskId: TaskId
111 : ): Promise<TaskResult<CancelTaskOutcome>> {
112 3 : try {
113 3 : const res = await api.fetchApi(
114 : `${TASKS_ENDPOINT}/${encodeURIComponent(taskId)}`,
115 : { method: 'DELETE' }
116 : )
117 3 : if (res.status === 404) return { ok: true, value: 'missing' }
118 3 : if (res.status === 409) return { ok: true, value: 'not-cancellable' }
119 3 : if (!res.ok) {
120 : // This message reaches a user-facing toast and telemetry, so the
121 : // response body stays out of it: a 5xx from a gateway or reverse proxy
122 : // is usually an HTML error page or a stack trace.
123 0 : return {
124 : ok: false,
125 : error: new Error(`Failed to cancel task ${taskId}: ${res.status}`)
126 : }
127 : }
128 3 : return { ok: true, value: 'cancelling' }
129 : } catch (error) {
130 0 : return { ok: false, error: toError(error) }
131 : }
132 : }
133 :
134 2356 : return { getTask, cancelTask }
135 : }
136 :
137 2356 : export const taskService = createTaskService()
|