-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
149 lines (149 loc) · 3.71 KB
/
index.js
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
// offload.error.ts
class OffloadError extends Error {
constructor(message, options) {
super(message, options);
this.name = "OffloadError";
}
}
// offload.handler.ts
async function handler(fn) {
self.addEventListener("message", async (event) => {
const request = event.data;
const result = await fn(request.params);
const response = { id: request.id, value: result };
self.postMessage(response);
});
}
// offload.ts
var workerId = Symbol("workerId");
var workerTasks = new Map;
function offload(url, poolSize = 1, mode = "cb") {
switch (mode) {
case "bg":
return createPooledCallback(poolSize, () => {
const bg = withMessageInterceptor(new Worker(url.toString()));
const bgcb = createTaskCallback(bg);
return bgcb;
});
default:
return createBufferedCallback(poolSize, () => {
const worker = withMessageInterceptor(new Worker(url.toString()));
const cb = createTaskCallback(worker, () => {
worker.terminate();
});
return cb;
});
}
}
function createTaskCallback(worker, eof) {
const cb = async function(data) {
const id = createTaskId();
const errorCallback = (event) => {
const error = event.message;
workerTasks.get(worker)?.get(id)?.reject(new OffloadError(error, id));
workerTasks.get(worker)?.delete(id);
};
worker.addEventListener("error", errorCallback, { once: true });
const workerTask = Promise.withResolvers();
workerTasks.get(worker)?.set(id, workerTask);
const request = { id, params: data };
worker.postMessage(request);
try {
const result = await workerTask.promise;
workerTasks.get(worker)?.delete(id);
if (eof)
eof();
worker.removeEventListener("error", errorCallback);
return result;
} catch (error) {
workerTasks.get(worker)?.delete(id);
if (eof)
eof();
worker.removeEventListener("error", errorCallback);
throw error;
}
};
cb[workerId] = worker;
return cb;
}
function createBufferedCallback(bufSize, fun) {
let free = bufSize;
const waitFree = async () => {
if (free <= 0) {
await new Promise((resolve) => setTimeout(resolve));
return await waitFree();
}
};
const spots = [];
const term = () => {
for (const cb of spots) {
if (cb)
terminate(cb);
}
};
const call = async (data) => {
if (free <= 0)
await waitFree();
--free;
const cb = fun();
spots[free] = cb;
const result = await cb(data);
delete spots[free];
free++;
return result;
};
return [call, term];
}
function createPooledCallback(poolSize, fun) {
let free = poolSize;
const waitFree = async () => {
if (free <= 0) {
await new Promise((resolve) => setTimeout(resolve));
return await waitFree();
}
};
const spots = [];
for (let i = 0;i < poolSize; i++) {
spots[i] = fun();
}
const term = () => {
for (const cb of spots) {
terminate(cb);
}
};
const call = async (data) => {
if (free <= 0)
await waitFree();
--free;
const cb = spots[0];
const result = await cb(data);
free++;
return result;
};
return [call, term];
}
function useWorker(cb) {
return cb[workerId];
}
function terminate(cb) {
const worker = useWorker(cb);
worker.terminate();
}
function createTaskId() {
return Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
}
function withMessageInterceptor(worker) {
const promiseTable = new Map;
workerTasks.set(worker, promiseTable);
worker.onmessage = (event) => {
const { id, value } = event.data;
promiseTable.get(id)?.resolve(value);
promiseTable.delete(id);
};
return worker;
}
export {
offload,
handler,
OffloadError
};