File size: 5,255 Bytes
0ed8124
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3fd9ca4
 
 
 
 
 
 
 
0ed8124
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { EngineRuntimeError } from './errors';
import type {
  EngineErrorPayload,
  EngineEvent,
  EngineMethod,
  EngineRequest,
  EngineResponse,
  EngineResponseMap,
  EngineWorkerMessage,
} from './protocol';
import { BrowserEngineRuntime } from './runtime';

interface WorkerScope {
  onmessage: ((event: MessageEvent<EngineRequest>) => void) | null;
  postMessage(message: EngineWorkerMessage): void;
}

interface ActiveOperation {
  controller: AbortController;
  promise: Promise<unknown>;
}

const scope = globalThis as unknown as WorkerScope;
const runtime = new BrowserEngineRuntime();
const active = new Map<string, ActiveOperation>();
let quiescing = false;

function postEvent(event: EngineEvent): void {
  scope.postMessage(event);
}

function postSuccess<Method extends EngineMethod>(
  request: { requestId: string; method: Method },
  result: EngineResponseMap[Method],
): void {
  scope.postMessage({
    type: 'response',
    requestId: request.requestId,
    method: request.method,
    ok: true,
    result,
  } as EngineResponse);
}

function errorPayload(error: unknown): EngineErrorPayload {
  if (error instanceof EngineRuntimeError) {
    return {
      code: error.code,
      message: error.message,
      ...(error.details === undefined ? {} : { details: error.details }),
    };
  }
  if (error instanceof DOMException && error.name === 'AbortError') {
    return { code: 'ABORTED', message: error.message };
  }
  if (error instanceof Error) {
    return {
      code: error.name === 'AbortError' ? 'ABORTED' : 'ENGINE_ERROR',
      message: error.message,
    };
  }
  return { code: 'ENGINE_ERROR', message: String(error) };
}

function postFailure(request: { requestId: string; method: EngineMethod }, error: unknown): void {
  scope.postMessage({
    type: 'response',
    requestId: request.requestId,
    method: request.method,
    ok: false,
    error: errorPayload(error),
  } as EngineResponse);
}

async function runExclusive<Result>(
  requestId: string,
  operation: (signal: AbortSignal) => Promise<Result>,
): Promise<Result> {
  if (quiescing || active.size > 0) {
    throw new EngineRuntimeError(
      'ENGINE_BUSY',
      quiescing
        ? 'The engine is unloading or clearing storage.'
        : `Another mutable engine operation is active (${[...active.keys()].join(', ')}).`,
    );
  }
  const controller = new AbortController();
  const promise = operation(controller.signal);
  active.set(requestId, { controller, promise });
  try {
    return await promise;
  } finally {
    active.delete(requestId);
  }
}

async function stopActiveOperations(): Promise<void> {
  const operations = [...active.values()];
  for (const operation of operations) {
    operation.controller.abort();
  }
  await Promise.allSettled(operations.map((operation) => operation.promise));
}

async function runQuiesced<Result>(operation: () => Promise<Result>): Promise<Result> {
  if (quiescing) {
    throw new EngineRuntimeError('ENGINE_BUSY', 'The engine is already unloading or clearing storage.');
  }
  quiescing = true;
  try {
    await stopActiveOperations();
    return await operation();
  } finally {
    quiescing = false;
  }
}

async function handleRequest(request: EngineRequest): Promise<void> {
  try {
    switch (request.method) {
      case 'capabilities':
        postSuccess(request, await runtime.capabilities());
        return;
      case 'loadModel':
        postSuccess(
          request,
          await runExclusive(request.requestId, (signal) => (
            runtime.loadModel(request.requestId, request.params, signal, postEvent)
          )),
        );
        return;
      case 'generate':
        postSuccess(
          request,
          await runExclusive(request.requestId, (signal) => (
            runtime.generate(request.requestId, request.params, signal, postEvent)
          )),
        );
        return;
      case 'scoreSequence':
        postSuccess(
          request,
          await runExclusive(request.requestId, (signal) => (
            runtime.scoreSequence(request.params, signal)
          )),
        );
        return;
      case 'abort': {
        const operation = active.get(request.params.targetRequestId);
        const aborted = operation !== undefined && !operation.controller.signal.aborted;
        operation?.controller.abort();
        postSuccess(request, { targetRequestId: request.params.targetRequestId, aborted });
        return;
      }
      case 'unload':
        postSuccess(request, await runQuiesced(() => runtime.unload()));
        return;
      case 'backendReport':
        postSuccess(request, await runtime.backendReport());
        return;
      case 'storageEstimate':
        postSuccess(request, await runtime.storageEstimate());
        return;
      case 'storagePersist':
        postSuccess(request, await runtime.storagePersist());
        return;
      case 'storageClear':
        postSuccess(request, await runQuiesced(() => runtime.storageClear()));
        return;
    }
  } catch (error) {
    postFailure(request, error);
  }
}

scope.onmessage = (event) => {
  const request = event.data;
  if (request?.type === 'request' && typeof request.requestId === 'string') {
    void handleRequest(request);
  }
};