-
-
Notifications
You must be signed in to change notification settings - Fork 168
/
Copy pathimplementation-node.ts
292 lines (243 loc) · 9.56 KB
/
implementation-node.ts
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
/// <reference lib="dom" />
// tslint:disable function-constructor no-eval no-duplicate-super max-classes-per-file
import getCallsites, { CallSite } from "callsites"
import { EventEmitter } from "events"
import { cpus } from 'os'
import * as path from "path"
import {
ImplementationExport,
ThreadsWorkerOptions,
WorkerImplementation
} from "../types/master"
interface WorkerGlobalScope {
addEventListener(eventName: string, listener: (event: Event) => void): void
postMessage(message: any, transferables?: any[]): void
removeEventListener(eventName: string, listener: (event: Event) => void): void
}
declare const __non_webpack_require__: typeof require
declare const self: WorkerGlobalScope
type WorkerEventName = "error" | "message"
let tsNodeAvailable: boolean | undefined
export const defaultPoolSize = cpus().length
function detectTsNode() {
if (typeof __non_webpack_require__ === "function") {
// Webpack build: => No ts-node required or possible
return false
}
if (tsNodeAvailable) {
return tsNodeAvailable
}
try {
eval("require").resolve("ts-node")
tsNodeAvailable = true
} catch (error) {
if (error && error.code === "MODULE_NOT_FOUND") {
tsNodeAvailable = false
} else {
// Re-throw
throw error
}
}
return tsNodeAvailable
}
function createTsNodeModule(scriptPath: string) {
const content = `
require("ts-node/register/transpile-only");
require(${JSON.stringify(scriptPath)});
`
return content
}
function rebaseScriptPath(scriptPath: string, ignoreRegex: RegExp) {
const parentCallSite = getCallsites().find((callsite: CallSite) => {
const filename = callsite.getFileName()
return Boolean(
filename &&
!filename.match(ignoreRegex) &&
!filename.match(/[\/\\]master[\/\\]implementation/) &&
!filename.match(/^internal\/process/)
)
})
const rawCallerPath = parentCallSite ? parentCallSite.getFileName() : null
const callerPath = rawCallerPath ? rawCallerPath.replace(/^file:\//, "") : null
const rebasedScriptPath = callerPath ? path.join(path.dirname(callerPath), scriptPath) : scriptPath
return rebasedScriptPath
}
function resolveScriptPath(scriptPath: string, baseURL?: string | undefined) {
const makeRelative = (filePath: string) => {
// eval() hack is also webpack-related
return path.isAbsolute(filePath) ? filePath : path.join(baseURL || eval("__dirname"), filePath)
}
const workerFilePath = typeof __non_webpack_require__ === "function"
? __non_webpack_require__.resolve(makeRelative(scriptPath))
: eval("require").resolve(makeRelative(rebaseScriptPath(scriptPath, /[\/\\]worker_threads[\/\\]/)))
return workerFilePath
}
export function initWorkerThreadsWorker(): ImplementationExport {
isTinyWorker = false
// Webpack hack
const NativeWorker = typeof __non_webpack_require__ === "function"
? __non_webpack_require__("worker_threads").Worker
: eval("require")("worker_threads").Worker
let allWorkers: Array<typeof NativeWorker> = []
class Worker extends NativeWorker {
private mappedEventListeners: WeakMap<EventListener, EventListener>
constructor(scriptPath: string, options?: ThreadsWorkerOptions & { fromSource: boolean }) {
const resolvedScriptPath = options && options.fromSource
? null
: resolveScriptPath(scriptPath, (options || {})._baseURL)
if (!resolvedScriptPath) {
// `options.fromSource` is true
const sourceCode = scriptPath
super(sourceCode, { ...options, eval: true })
} else if (resolvedScriptPath.match(/\.tsx?$/i) && detectTsNode()) {
super(createTsNodeModule(resolvedScriptPath), { ...options, eval: true })
} else if (resolvedScriptPath.match(/\.asar[\/\\]/)) {
// See <https://github.com/andywer/threads-plugin/issues/17>
super(resolvedScriptPath.replace(/\.asar([\/\\])/, ".asar.unpacked$1"), options)
} else {
super(resolvedScriptPath, options)
}
this.mappedEventListeners = new WeakMap()
allWorkers.push(this)
}
public addEventListener(eventName: string, rawListener: EventListener) {
const listener = (message: any) => {
rawListener({ data: message } as any)
}
this.mappedEventListeners.set(rawListener, listener)
this.on(eventName, listener)
}
public removeEventListener(eventName: string, rawListener: EventListener) {
const listener = this.mappedEventListeners.get(rawListener) || rawListener
this.off(eventName, listener)
}
}
const terminateWorkersAndMaster = () => {
// we should terminate all workers and then gracefully shutdown self process
Promise.all(allWorkers.map(worker => worker.terminate())).then(
() => process.exit(0),
() => process.exit(1),
)
allWorkers = []
}
// Take care to not leave orphaned processes behind. See #147.
process.on("SIGINT", () => terminateWorkersAndMaster())
process.on("SIGTERM", () => terminateWorkersAndMaster())
class BlobWorker extends Worker {
constructor(blob: Uint8Array, options?: ThreadsWorkerOptions) {
super(Buffer.from(blob).toString("utf-8"), { ...options, fromSource: true })
}
public static fromText(source: string, options?: ThreadsWorkerOptions): WorkerImplementation {
return new Worker(source, { ...options, fromSource: true }) as any
}
}
return {
blob: BlobWorker as any,
default: Worker as any
}
}
export function initTinyWorker(): ImplementationExport {
isTinyWorker = true
const TinyWorker = require("tiny-worker")
let allWorkers: Array<typeof TinyWorker> = []
class Worker extends TinyWorker {
private emitter: EventEmitter
constructor(scriptPath: string, options?: ThreadsWorkerOptions & { fromSource?: boolean }) {
// Need to apply a work-around for Windows or it will choke upon the absolute path
// (`Error [ERR_INVALID_PROTOCOL]: Protocol 'c:' not supported`)
const resolvedScriptPath = options && options.fromSource
? null
: process.platform === "win32"
? `file:///${resolveScriptPath(scriptPath).replace(/\\/g, "/")}`
: resolveScriptPath(scriptPath)
if (!resolvedScriptPath) {
// `options.fromSource` is true
const sourceCode = scriptPath
super(new Function(sourceCode), [], { esm: true })
} else if (resolvedScriptPath.match(/\.tsx?$/i) && detectTsNode()) {
super(new Function(createTsNodeModule(resolveScriptPath(scriptPath))), [], { esm: true })
} else if (resolvedScriptPath.match(/\.asar[\/\\]/)) {
// See <https://github.com/andywer/threads-plugin/issues/17>
super(resolvedScriptPath.replace(/\.asar([\/\\])/, ".asar.unpacked$1"), [], { esm: true })
} else {
super(resolvedScriptPath, [], { esm: true })
}
allWorkers.push(this)
this.emitter = new EventEmitter()
this.onerror = (error: Error) => this.emitter.emit("error", error)
this.onmessage = (message: MessageEvent) => this.emitter.emit("message", message)
}
public addEventListener(eventName: WorkerEventName, listener: EventListener) {
this.emitter.addListener(eventName, listener)
}
public removeEventListener(eventName: WorkerEventName, listener: EventListener) {
this.emitter.removeListener(eventName, listener)
}
public terminate() {
allWorkers = allWorkers.filter(worker => worker !== this)
return super.terminate()
}
}
const terminateWorkersAndMaster = () => {
// we should terminate all workers and then gracefully shutdown self process
Promise.all(allWorkers.map(worker => worker.terminate())).then(
() => process.exit(0),
() => process.exit(1),
)
allWorkers = []
}
// Take care to not leave orphaned processes behind
// See <https://github.com/avoidwork/tiny-worker#faq>
process.on("SIGINT", () => terminateWorkersAndMaster())
process.on("SIGTERM", () => terminateWorkersAndMaster())
class BlobWorker extends Worker {
constructor(blob: Uint8Array, options?: ThreadsWorkerOptions) {
super(Buffer.from(blob).toString("utf-8"), { ...options, fromSource: true })
}
public static fromText(source: string, options?: ThreadsWorkerOptions): WorkerImplementation {
return new Worker(source, { ...options, fromSource: true }) as any
}
}
return {
blob: BlobWorker as any,
default: Worker as any
}
}
let implementation: ImplementationExport
let isTinyWorker: boolean
function selectWorkerImplementation(selection?: string): ImplementationExport {
if (!selection) {
// automatic version based selection
try {
return initWorkerThreadsWorker()
} catch(error) {
// tslint:disable-next-line no-console
console.debug("Node worker_threads not available. Trying to fall back to tiny-worker polyfill...")
return initTinyWorker()
}
// manual selection
} else if (selection === "node") {
return initWorkerThreadsWorker()
} else if (selection === "tiny") {
return initTinyWorker()
} else {
throw new Error("selection is not supported" + selection)
}
}
export function getWorkerImplementation(selection?: string): ImplementationExport {
if (!implementation) {
implementation = selectWorkerImplementation(selection)
}
return implementation
}
export function isWorkerRuntime() {
if (isTinyWorker) {
return typeof self !== "undefined" && self.postMessage ? true : false
} else {
// Webpack hack
const isMainThread = typeof __non_webpack_require__ === "function"
? __non_webpack_require__("worker_threads").isMainThread
: eval("require")("worker_threads").isMainThread
return !isMainThread
}
}