File size: 10,947 Bytes
c1f12bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac29ac4
 
c1f12bf
 
 
 
ac29ac4
89b09eb
 
 
ac29ac4
 
 
 
 
 
 
 
 
c1f12bf
ac29ac4
c1f12bf
ac29ac4
 
c1f12bf
ac29ac4
 
 
c1f12bf
ac29ac4
 
d079437
ac29ac4
 
 
 
 
 
 
c1f12bf
 
 
 
 
 
 
ac29ac4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1f12bf
ac29ac4
 
 
 
 
 
 
c1f12bf
ac29ac4
 
c1f12bf
ac29ac4
c1f12bf
ac29ac4
 
 
c1f12bf
ac29ac4
 
 
 
c1f12bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89b09eb
ac29ac4
 
 
 
89b09eb
 
c1f12bf
 
ac29ac4
89b09eb
ac29ac4
 
 
 
 
 
 
 
 
 
 
 
c1f12bf
89b09eb
ac29ac4
 
 
 
 
 
 
c1f12bf
ac29ac4
89b09eb
ac29ac4
 
 
c1f12bf
ac29ac4
 
c1f12bf
 
 
ac29ac4
89b09eb
 
 
 
ac29ac4
c1f12bf
 
 
ac29ac4
 
89b09eb
ac29ac4
 
 
 
c1f12bf
 
 
ac29ac4
 
89b09eb
 
ac29ac4
c1f12bf
 
 
ac29ac4
 
 
c1f12bf
ac29ac4
 
 
 
 
 
 
 
 
c1f12bf
 
 
ac29ac4
 
c1f12bf
ac29ac4
 
 
 
 
 
c1f12bf
ac29ac4
 
 
 
c1f12bf
 
 
ac29ac4
 
c1f12bf
 
 
ac29ac4
 
 
 
 
 
c1f12bf
 
 
 
ac29ac4
 
 
 
 
c1f12bf
ac29ac4
 
 
 
 
 
 
 
 
89b09eb
ac29ac4
 
89b09eb
ac29ac4
 
 
 
 
 
 
c1f12bf
 
 
ac29ac4
 
 
c1f12bf
 
ac29ac4
 
c1f12bf
 
 
ac29ac4
 
 
 
 
c1f12bf
ac29ac4
 
 
c1f12bf
 
 
 
 
 
 
 
 
 
ac29ac4
 
 
 
c1f12bf
ac29ac4
 
 
 
 
89b09eb
c1f12bf
 
 
 
 
ac29ac4
 
 
 
 
 
 
 
 
89b09eb
ac29ac4
c1f12bf
 
ac29ac4
 
 
 
 
 
c1f12bf
 
ac29ac4
 
 
 
 
 
 
 
89b09eb
ac29ac4
c1f12bf
 
ac29ac4
 
 
 
 
c1f12bf
ac29ac4
 
 
 
 
 
 
89b09eb
ac29ac4
 
 
c1f12bf
ac29ac4
 
 
89b09eb
ac29ac4
 
89b09eb
c1f12bf
 
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
'use client'

import { create } from 'zustand'
import { toast } from 'sonner'
import { UUID } from '@aitube/clap'
import {
  TasksStore,
  NewTask,
  Task,
  TaskCategory,
  TaskProgressType,
  TaskRemoteControl,
  TaskStatus,
  TaskVisibility,
} from '@aitube/clapper-services'

import { TaskStatusUpdate } from './TaskStatusUpdate'
import { sleep } from '@/lib/utils/sleep'

// we enforce the impossibility of some transitions
function statusTransition(
  current: TaskStatus,
  requested: TaskStatus
): TaskStatus {
  switch (current) {
    case TaskStatus.UPCOMING:
    case TaskStatus.RUNNING:
    case TaskStatus.PAUSED:
      return requested

    default:
      return current
  }
}

/**
 * A task manager, used for downloads, processing..
 *
 * It may seem a bit complicated, but that's because it can handle various modes:
 *
 * - Promise (you pass a function returning a promise, and it will wait the end)
 * - Progressive (no function, no promise, instead you call yourself a progress update function)
 *
 * It is also complex, because it is bidirectional!
 * - A task can receive a helper to gets its status, but it can also sets its own status
 * - A task can finish itself, ir be finished by an external event etc..
 *
 * and it also provides tons of helper to track the status
 */
export const useTasks = create<TasksStore>((set, get) => ({
  tasks: {} as Record<string, Task>,
  expandTasks: false,
  setExpandTasks: (expandTasks: boolean) => {
    set({ expandTasks })
  },
  get: (taskId?: string): TaskRemoteControl | undefined => {
    const { tasks } = get()
    if (!taskId) {
      return undefined
    }
    const task = (tasks[taskId || ''] || undefined) as Task | undefined
    if (!task) {
      return
    }

    // we provide a helper to whoever called us
    return {
      task,
      promise: task.promise,
      pause: () => {
        return get().pause(task.id)
      },
      continue: () => {
        return get().continue(task.id)
      },
      setStatus: (status: TaskStatus) => {
        return get().setStatus(status, task.id)
      },
      setProgress: async (options?: {
        value?: number
        sleepDelay?: number
        message?: string
        isFinished?: boolean
        hasFailed?: boolean
      }) => {
        return get().setProgress(task.id, options)
      },
      success: () => {
        return get().success(task.id)
      },
      fail: (reason?: string) => {
        return get().fail(task.id, reason)
      },
      cancel: () => {
        return get().cancel(task.id)
      },
    }
  },
  find: (params?: {
    status?: TaskStatus
    category?: TaskCategory
    visibility?: TaskVisibility
  }): Task[] => {
    const { tasks } = get()

    let list = Object.values(tasks)

    if (params?.status) {
      list = list.filter((t) => t.status === params?.status)
    }

    if (params?.category) {
      list = list.filter((t) => t.category === params?.category)
    }

    return list
  },
  add: (
    partialTask: Partial<NewTask>,
    status?: TaskStatus
  ): TaskRemoteControl => {
    const mode: TaskProgressType =
      partialTask?.mode || TaskProgressType.PERCENTAGE

    const min =
      mode === TaskProgressType.COUNTER && partialTask?.min
        ? partialTask.min
        : 0
    const max =
      mode === TaskProgressType.COUNTER && partialTask?.max
        ? partialTask.max
        : mode === TaskProgressType.RATIO
          ? 1
          : mode === TaskProgressType.PERCENTAGE
            ? 100
            : 100

    const id = UUID()

    const newTask: NewTask = {
      id,
      visibility: partialTask?.visibility || TaskVisibility.BACKGROUND,
      category: partialTask?.category || TaskCategory.GENERIC,
      initialMessage: partialTask?.initialMessage || 'Loading..',
      successMessage: partialTask?.successMessage || 'Task completed!',
      priority: partialTask?.priority || 0, // 0 = lowest, 1 or more = more and more important
      status: status || TaskStatus.RUNNING,
      value: partialTask?.value || 0,
      progress: partialTask?.progress || 0,
      min,
      max,
      mode,
      run: partialTask.run,
    }

    const task: Task = {
      ...newTask,
      currentMessage: newTask.initialMessage,
      startedAt: new Date().toISOString(),
      endedAt: '',
      promise: Promise.resolve(TaskStatus.RUNNING),
    }

    task.promise = new Promise<TaskStatus>((resolve, reject) => {
      let checkStatus = () => {
        try {
          // need to use fresh data here
          const t = get().get(id)!

          if (!t) {
            resolve(TaskStatus.SUCCESS)
            return
          }

          const status = t.task.status || 'deleted'
          const progress = t.task.progress || 0

          console.log(
            `useTasks[${id}]: checkStatus: checking task, current status is: "${status}"`
          )
          if (
            status === TaskStatus.ERROR ||
            status === TaskStatus.SUCCESS ||
            status === TaskStatus.DELETED ||
            status === TaskStatus.CANCELLED
          ) {
            console.log(
              `useTasks[${id}]: checkStatus: status is "${status}", interrupting task loop..`
            )

            // this call might be redundant
            if (status === TaskStatus.SUCCESS) {
              get().setProgress(id, { isFinished: true })
            }
            resolve(status)
          } else if (progress >= 100) {
            console.log(
              `useTasks[${id}]: checkStatus: task is completed at 100%, interrupting task loop..`
            )
            // this call might be redundant
            get().setProgress(id, { isFinished: true })
            // get().setStatus(TaskStatus.SUCCESS, id)
            resolve(TaskStatus.SUCCESS)
          } else {
            console.log(
              `useTasks[${id}]: checkStatus: status is "${status}", continuing task loop..`
            )
            setTimeout(checkStatus, 1000)
          }
        } catch (err) {
          console.error('useTasks:checkStatus: ', err)
        }
      }

      checkStatus()
    })

    toast.promise<TaskStatus>(task.promise, {
      loading: <TaskStatusUpdate taskId={id} />,
      success: (finalStatus) => {
        return finalStatus === TaskStatus.SUCCESS
          ? task.successMessage
          : `Task ended`
      },
      error: 'Task aborted',
    })

    const { tasks } = get()
    set({
      tasks: {
        ...tasks,
        [id]: task,
      },
    })

    setTimeout(async () => {
      // optionally launch the task function, if there is one
      if (!task.run) {
        return
      }
      // oh, one last thing: let's launch-and-forget the actual task

      console.log(
        `useTasks[${id}]: launching the task runner in the background..`
      )

      // we provide to the task runner a wait to get the current status
      // that wait long-running jobs will know when they have been cancelled and no longer needed
      const result = await task.run(() => {
        const remoteControl = get().get(id)!
        const status = remoteControl?.task?.status
        console.log(
          `useTasks[${id}]: task runner asked for current status (which is: "${status || 'deleted'}")`
        )
        return status || 'deleted'
      })

      console.log(`useTasks[${id}]: task runner ended with status: "${result}"`)
      get().setProgress(id, { isFinished: true })
      // get().setStatus(result, id)
    }, 100)

    // we want to return the "remote control", which is a more complex object,
    // with functions and all
    // the easiest way to do this is to call our get() function
    const remoteControl = get().get(id)!

    return remoteControl
  },
  pause: (taskId?: string) => {
    get().setStatus(TaskStatus.PAUSED, taskId)
  },
  continue: (taskId?: string) => {
    get().setStatus(TaskStatus.RUNNING, taskId)
  },
  setStatus: (status: TaskStatus, taskId?: string) => {
    const { tasks } = get()
    const task = get().get(taskId)?.task

    console.log(`useTasks[${taskId}]:setStatus("${status}")`)
    if (task) {
      console.log(
        `useTasks[${taskId}]:setStatus("${status}") -> setting one task to ${status}`
      )
      set({
        tasks: {
          ...tasks,
          [task.id]: { ...task, status: statusTransition(task.status, status) },
        },
      })
    } else {
      console.log(
        `useTasks[${taskId}]:setStatus("${status}") -> setting all tasks to ${status}`
      )
      const newTasks = {} as Record<string, Task>
      for (const [id, t] of Object.entries(tasks)) {
        newTasks[id] = { ...t, status: statusTransition(t.status, status) }
      }
      set({
        tasks: newTasks,
      })
    }
  },
  setProgress: async (
    taskId: string,
    options?: {
      value?: number
      sleepDelay?: number
      message?: string
      isFinished?: boolean
      hasFailed?: boolean
    }
  ): Promise<void> => {
    try {
      const { tasks } = get()
      const task = get().get(taskId)?.task

      const message = options?.message || ''
      const value = options?.value || task?.value || 0
      const sleepDelay = options?.sleepDelay || 100

      if (task) {
        let progress =
          task.mode === TaskProgressType.PERCENTAGE
            ? value
            : task.mode === TaskProgressType.RATIO
              ? value * 100
              : ((value - task.min) / (task.max - task.min)) * 100

        const currentMessage = message || task.initialMessage

        if (options?.hasFailed) {
          set({
            tasks: {
              ...tasks,
              [task.id]: {
                ...task,
                currentMessage,
                status: TaskStatus.ERROR,
                endedAt: new Date().toISOString(),
              },
            },
          })
        } else {
          const isFinished = options?.isFinished || progress >= 100

          if (isFinished) {
            progress = 100
          }

          set({
            tasks: {
              ...tasks,
              [task.id]: {
                ...task,
                progress,
                value,
                currentMessage,
                status: isFinished ? TaskStatus.SUCCESS : TaskStatus.RUNNING,
                endedAt: isFinished ? new Date().toISOString() : task.endedAt,
              },
            },
          })
        }

        await sleep(sleepDelay)
      }
    } catch (err) {}
  },
  clear: () => {
    get().cancel()
    set({ tasks: {} })
  },
  success: (taskId: string) => {
    get().setProgress(taskId, { isFinished: true })
    get().setStatus(TaskStatus.SUCCESS, taskId)
  },
  fail: (taskId: string, reason?: string) => {
    get().setProgress(taskId, {
      message: reason || 'unknown failure',
      isFinished: true,
      hasFailed: true,
    })
    get().setStatus(TaskStatus.ERROR, taskId)
  },
  cancel: (taskId?: string) => {
    get().setStatus(TaskStatus.CANCELLED, taskId)
  },
}))