File size: 2,359 Bytes
9210bde
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import {DetectTaskHandler} from './tasks/DetectTaskHandler';
import {DescribeTaskHandler} from './tasks/DescribeTaskHandler';
import {AbstractModelTaskHandler} from './tasks/AbstractModelTaskHandler';
import type {
  ClusterTaskHandlerOptions,
  ClusterTaskHostContext,
  ClusterTaskKind,
  HostTaskMessage,
} from './tasks/types';

export type {ClusterTaskKind, HostTaskMessage, ClusterTaskHandlerOptions} from './tasks/types';

export class ClusterTaskHandler {
  private readonly taskQueue: HostTaskMessage[] = [];
  private processing = false;
  private readonly host: ClusterTaskHostContext;
  private readonly handlers: Map<ClusterTaskKind, AbstractModelTaskHandler>;

  constructor(options: ClusterTaskHandlerOptions) {
    this.host = {
      apiBase: options.apiBase,
      getSelectedModelId: options.getSelectedModelId,
      setStatus: options.setStatus,
    };

    this.handlers = new Map<ClusterTaskKind, AbstractModelTaskHandler>([
      ['detect', new DetectTaskHandler(this.host, options.getDetector)],
      ['describe', new DescribeTaskHandler(this.host, options.getDescriber)],
    ]);
  }

  enqueueTask(task: HostTaskMessage): void {
    this.taskQueue.push(task);
    void this.drainTaskQueue();
  }

  parseIncomingTask(
    raw: HostTaskMessage & {kind?: ClusterTaskKind},
    defaultKind: ClusterTaskKind,
  ): HostTaskMessage {
    return {
      ...raw,
      kind: raw.kind ?? defaultKind,
    };
  }

  private async drainTaskQueue(): Promise<void> {
    if (this.processing || this.taskQueue.length === 0) {
      return;
    }

    const task = this.taskQueue.shift();
    if (task) {
      await this.processTask(task);
    }
  }

  private async processTask(task: HostTaskMessage): Promise<void> {
    const handler = this.handlers.get(task.kind);
    if (!handler) {
      throw new Error(`No handler for task kind '${task.kind}'`);
    }

    this.processing = true;
    this.host.setStatus(`Processing task ${task.id.slice(0, 8)}…`);

    try {
      await handler.process(task);
      this.host.setStatus(`Task ${task.id.slice(0, 8)} complete. Waiting for requests…`);
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      this.host.setStatus(`Task failed: ${message}`);
    } finally {
      this.processing = false;
      void this.drainTaskQueue();
    }
  }
}