@loaders.gl/worker-utils 3.4.11 → 3.4.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/es5/lib/env-utils/version.js +2 -2
  2. package/dist/es5/lib/library-utils/library-utils.js +1 -1
  3. package/dist/es5/lib/worker-api/get-worker-url.js +1 -1
  4. package/dist/esm/lib/env-utils/version.js +2 -2
  5. package/dist/esm/lib/library-utils/library-utils.js +1 -1
  6. package/dist/esm/lib/worker-api/get-worker-url.js +1 -1
  7. package/package.json +4 -5
  8. package/dist/index.js +0 -59
  9. package/dist/lib/async-queue/async-queue.js +0 -87
  10. package/dist/lib/env-utils/assert.js +0 -13
  11. package/dist/lib/env-utils/globals.js +0 -32
  12. package/dist/lib/env-utils/version.js +0 -12
  13. package/dist/lib/library-utils/library-utils.js +0 -170
  14. package/dist/lib/node/require-utils.node.js +0 -60
  15. package/dist/lib/node/worker_threads-browser.js +0 -15
  16. package/dist/lib/node/worker_threads.js +0 -33
  17. package/dist/lib/process-utils/child-process-proxy.js +0 -136
  18. package/dist/lib/process-utils/process-utils.js +0 -35
  19. package/dist/lib/worker-api/create-worker.js +0 -91
  20. package/dist/lib/worker-api/get-worker-url.js +0 -58
  21. package/dist/lib/worker-api/process-on-worker.js +0 -83
  22. package/dist/lib/worker-api/validate-worker-version.js +0 -35
  23. package/dist/lib/worker-farm/worker-body.js +0 -111
  24. package/dist/lib/worker-farm/worker-farm.js +0 -89
  25. package/dist/lib/worker-farm/worker-job.js +0 -47
  26. package/dist/lib/worker-farm/worker-pool.js +0 -155
  27. package/dist/lib/worker-farm/worker-thread.js +0 -131
  28. package/dist/lib/worker-utils/get-loadable-worker-url.js +0 -72
  29. package/dist/lib/worker-utils/get-transfer-list.js +0 -87
  30. package/dist/lib/worker-utils/remove-nontransferable-options.js +0 -27
  31. package/dist/types.js +0 -2
  32. package/dist/workers/null-worker.js +0 -7
@@ -1,136 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- /* eslint-disable no-console */
27
- // Avoid using named imports for Node builtins to help with "empty" resolution
28
- // for bundlers targeting browser environments. Access imports & types
29
- // through the `ChildProcess` object (e.g. `ChildProcess.spawn`, `ChildProcess.ChildProcess`).
30
- const ChildProcess = __importStar(require("child_process"));
31
- const process_utils_1 = require("./process-utils");
32
- const DEFAULT_PROPS = {
33
- command: '',
34
- arguments: [],
35
- port: 5000,
36
- autoPort: true,
37
- wait: 2000,
38
- onSuccess: (processProxy) => {
39
- console.log(`Started ${processProxy.props.command}`);
40
- }
41
- };
42
- /**
43
- * Manager for a Node.js child process
44
- * Prepares arguments, starts, stops and tracks output
45
- */
46
- class ChildProcessProxy {
47
- // constructor(props?: {id?: string});
48
- constructor({ id = 'browser-driver' } = {}) {
49
- this.props = { ...DEFAULT_PROPS };
50
- this.childProcess = null;
51
- this.port = 0;
52
- this.id = id;
53
- }
54
- /** Starts a child process with the provided props */
55
- async start(props) {
56
- props = { ...DEFAULT_PROPS, ...props };
57
- this.props = props;
58
- const args = [...props.arguments];
59
- // If portArg is set, we can look up an available port
60
- this.port = Number(props.port);
61
- if (props.portArg) {
62
- if (props.autoPort) {
63
- this.port = await (0, process_utils_1.getAvailablePort)(props.port);
64
- }
65
- args.push(props.portArg, String(this.port));
66
- }
67
- return await new Promise((resolve, reject) => {
68
- try {
69
- this._setTimeout(() => {
70
- if (props.onSuccess) {
71
- props.onSuccess(this);
72
- }
73
- resolve({});
74
- });
75
- console.log(`Spawning ${props.command} ${props.arguments.join(' ')}`);
76
- const childProcess = ChildProcess.spawn(props.command, args, props.spawn);
77
- this.childProcess = childProcess;
78
- childProcess.stdout.on('data', (data) => {
79
- console.log(data.toString());
80
- });
81
- childProcess.stderr.on('data', (data) => {
82
- console.log(`Child process wrote to stderr: "${data}".`);
83
- if (!props.ignoreStderr) {
84
- this._clearTimeout();
85
- reject(new Error(data));
86
- }
87
- });
88
- childProcess.on('error', (error) => {
89
- console.log(`Child process errored with ${error}`);
90
- this._clearTimeout();
91
- reject(error);
92
- });
93
- childProcess.on('close', (code) => {
94
- console.log(`Child process exited with ${code}`);
95
- this.childProcess = null;
96
- this._clearTimeout();
97
- resolve({});
98
- });
99
- }
100
- catch (error) {
101
- reject(error);
102
- }
103
- });
104
- }
105
- /** Stops a running child process */
106
- async stop() {
107
- if (this.childProcess) {
108
- this.childProcess.kill();
109
- this.childProcess = null;
110
- }
111
- }
112
- /** Exits this process */
113
- async exit(statusCode = 0) {
114
- try {
115
- await this.stop();
116
- // eslint-disable-next-line no-process-exit
117
- process.exit(statusCode);
118
- }
119
- catch (error) {
120
- console.error(error.message || error);
121
- // eslint-disable-next-line no-process-exit
122
- process.exit(1);
123
- }
124
- }
125
- _setTimeout(callback) {
126
- if (Number(this.props.wait) > 0) {
127
- this.successTimer = setTimeout(callback, this.props.wait);
128
- }
129
- }
130
- _clearTimeout() {
131
- if (this.successTimer) {
132
- clearTimeout(this.successTimer);
133
- }
134
- }
135
- }
136
- exports.default = ChildProcessProxy;
@@ -1,35 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.getAvailablePort = void 0;
7
- const child_process_1 = __importDefault(require("child_process"));
8
- // Get an available port
9
- // Works on Unix systems
10
- function getAvailablePort(defaultPort = 3000) {
11
- return new Promise((resolve) => {
12
- // Get a list of all ports in use
13
- child_process_1.default.exec('lsof -i -P -n | grep LISTEN', (error, stdout) => {
14
- if (error) {
15
- // likely no permission, e.g. CI
16
- resolve(defaultPort);
17
- return;
18
- }
19
- const portsInUse = [];
20
- const regex = /:(\d+) \(LISTEN\)/;
21
- stdout.split('\n').forEach((line) => {
22
- const match = regex.exec(line);
23
- if (match) {
24
- portsInUse.push(Number(match[1]));
25
- }
26
- });
27
- let port = defaultPort;
28
- while (portsInUse.includes(port)) {
29
- port++;
30
- }
31
- resolve(port);
32
- });
33
- });
34
- }
35
- exports.getAvailablePort = getAvailablePort;
@@ -1,91 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.createWorker = void 0;
7
- const async_queue_1 = __importDefault(require("../async-queue/async-queue"));
8
- const worker_body_1 = __importDefault(require("../worker-farm/worker-body"));
9
- // import {validateWorkerVersion} from './validate-worker-version';
10
- /** Counter for jobs */
11
- let requestId = 0;
12
- let inputBatches;
13
- let options;
14
- /**
15
- * Set up a WebWorkerGlobalScope to talk with the main thread
16
- */
17
- function createWorker(process, processInBatches) {
18
- if (!worker_body_1.default.inWorkerThread()) {
19
- return;
20
- }
21
- const context = {
22
- process: processOnMainThread
23
- };
24
- // eslint-disable-next-line complexity
25
- worker_body_1.default.onmessage = async (type, payload) => {
26
- try {
27
- switch (type) {
28
- case 'process':
29
- if (!process) {
30
- throw new Error('Worker does not support atomic processing');
31
- }
32
- const result = await process(payload.input, payload.options || {}, context);
33
- worker_body_1.default.postMessage('done', { result });
34
- break;
35
- case 'process-in-batches':
36
- if (!processInBatches) {
37
- throw new Error('Worker does not support batched processing');
38
- }
39
- inputBatches = new async_queue_1.default();
40
- options = payload.options || {};
41
- const resultIterator = processInBatches(inputBatches, options, context);
42
- for await (const batch of resultIterator) {
43
- worker_body_1.default.postMessage('output-batch', { result: batch });
44
- }
45
- worker_body_1.default.postMessage('done', {});
46
- break;
47
- case 'input-batch':
48
- inputBatches.push(payload.input);
49
- break;
50
- case 'input-done':
51
- inputBatches.close();
52
- break;
53
- default:
54
- }
55
- }
56
- catch (error) {
57
- const message = error instanceof Error ? error.message : '';
58
- worker_body_1.default.postMessage('error', { error: message });
59
- }
60
- };
61
- }
62
- exports.createWorker = createWorker;
63
- function processOnMainThread(arrayBuffer, options = {}) {
64
- return new Promise((resolve, reject) => {
65
- const id = requestId++;
66
- /**
67
- */
68
- const onMessage = (type, payload) => {
69
- if (payload.id !== id) {
70
- // not ours
71
- return;
72
- }
73
- switch (type) {
74
- case 'done':
75
- worker_body_1.default.removeEventListener(onMessage);
76
- resolve(payload.result);
77
- break;
78
- case 'error':
79
- worker_body_1.default.removeEventListener(onMessage);
80
- reject(payload.error);
81
- break;
82
- default:
83
- // ignore
84
- }
85
- };
86
- worker_body_1.default.addEventListener(onMessage);
87
- // Ask the main thread to decode data
88
- const payload = { id, input: arrayBuffer, options };
89
- worker_body_1.default.postMessage('process', payload);
90
- });
91
- }
@@ -1,58 +0,0 @@
1
- "use strict";
2
- // loaders.gl, MIT license
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.getWorkerURL = exports.getWorkerName = void 0;
5
- const assert_1 = require("../env-utils/assert");
6
- const version_1 = require("../env-utils/version");
7
- const NPM_TAG = 'latest'; // 'beta', or 'latest' on release-branch
8
- const VERSION = typeof version_1.VERSION !== 'undefined' ? version_1.VERSION : NPM_TAG;
9
- /**
10
- * Gets worker object's name (for debugging in Chrome thread inspector window)
11
- */
12
- function getWorkerName(worker) {
13
- const warning = worker.version !== VERSION ? ` (worker-utils@${VERSION})` : '';
14
- return `${worker.name}@${worker.version}${warning}`;
15
- }
16
- exports.getWorkerName = getWorkerName;
17
- /**
18
- * Generate a worker URL based on worker object and options
19
- * @returns A URL to one of the following:
20
- * - a published worker on unpkg CDN
21
- * - a local test worker
22
- * - a URL provided by the user in options
23
- */
24
- function getWorkerURL(worker, options = {}) {
25
- const workerOptions = options[worker.id] || {};
26
- const workerFile = `${worker.id}-worker.js`;
27
- let url = workerOptions.workerUrl;
28
- // HACK: Allow for non-nested workerUrl for the CompressionWorker.
29
- // For the compression worker, workerOptions is currently not nested correctly. For most loaders,
30
- // you'd have options within an object, i.e. `{mvt: {coordinates: ...}}` but the CompressionWorker
31
- // puts options at the top level, not within a `compression` key (its `id`). For this reason, the
32
- // above `workerOptions` will always be a string (i.e. `'gzip'`) for the CompressionWorker. To not
33
- // break backwards compatibility, we allow the CompressionWorker to have options at the top level.
34
- if (!url && worker.id === 'compression') {
35
- url = options.workerUrl;
36
- }
37
- // If URL is test, generate local loaders.gl url
38
- // @ts-ignore _workerType
39
- if (options._workerType === 'test') {
40
- url = `modules/${worker.module}/dist/${workerFile}`;
41
- }
42
- // If url override is not provided, generate a URL to published version on npm CDN unpkg.com
43
- if (!url) {
44
- // GENERATE
45
- let version = worker.version;
46
- // On master we need to load npm alpha releases published with the `beta` tag
47
- if (version === 'latest') {
48
- // throw new Error('latest worker version specified');
49
- version = NPM_TAG;
50
- }
51
- const versionTag = version ? `@${version}` : '';
52
- url = `https://unpkg.com/@loaders.gl/${worker.module}${versionTag}/dist/${workerFile}`;
53
- }
54
- (0, assert_1.assert)(url);
55
- // Allow user to override location
56
- return url;
57
- }
58
- exports.getWorkerURL = getWorkerURL;
@@ -1,83 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.processOnWorker = exports.canProcessOnWorker = void 0;
7
- const worker_farm_1 = __importDefault(require("../worker-farm/worker-farm"));
8
- const get_worker_url_1 = require("./get-worker-url");
9
- const get_transfer_list_1 = require("../worker-utils/get-transfer-list");
10
- /**
11
- * Determines if we can parse with worker
12
- * @param loader
13
- * @param data
14
- * @param options
15
- */
16
- function canProcessOnWorker(worker, options) {
17
- if (!worker_farm_1.default.isSupported()) {
18
- return false;
19
- }
20
- return worker.worker && options?.worker;
21
- }
22
- exports.canProcessOnWorker = canProcessOnWorker;
23
- /**
24
- * This function expects that the worker thread sends certain messages,
25
- * Creating such a worker can be automated if the worker is wrapper by a call to
26
- * createWorker in @loaders.gl/worker-utils.
27
- */
28
- async function processOnWorker(worker, data, options = {}, context = {}) {
29
- const name = (0, get_worker_url_1.getWorkerName)(worker);
30
- const workerFarm = worker_farm_1.default.getWorkerFarm(options);
31
- const { source } = options;
32
- const workerPoolProps = { name, source };
33
- if (!source) {
34
- workerPoolProps.url = (0, get_worker_url_1.getWorkerURL)(worker, options);
35
- }
36
- const workerPool = workerFarm.getWorkerPool(workerPoolProps);
37
- const jobName = options.jobName || worker.name;
38
- const job = await workerPool.startJob(jobName,
39
- // eslint-disable-next-line
40
- onMessage.bind(null, context));
41
- // Kick off the processing in the worker
42
- const transferableOptions = (0, get_transfer_list_1.getTransferListForWriter)(options);
43
- job.postMessage('process', { input: data, options: transferableOptions });
44
- const result = await job.result;
45
- return result.result;
46
- }
47
- exports.processOnWorker = processOnWorker;
48
- /**
49
- * Job completes when we receive the result
50
- * @param job
51
- * @param message
52
- */
53
- async function onMessage(context, job, type, payload) {
54
- switch (type) {
55
- case 'done':
56
- // Worker is done
57
- job.done(payload);
58
- break;
59
- case 'error':
60
- // Worker encountered an error
61
- job.error(new Error(payload.error));
62
- break;
63
- case 'process':
64
- // Worker is asking for us (main thread) to process something
65
- const { id, input, options } = payload;
66
- try {
67
- if (!context.process) {
68
- job.postMessage('error', { id, error: 'Worker not set up to process on main thread' });
69
- return;
70
- }
71
- const result = await context.process(input, options);
72
- job.postMessage('done', { id, result });
73
- }
74
- catch (error) {
75
- const message = error instanceof Error ? error.message : 'unknown error';
76
- job.postMessage('error', { id, error: message });
77
- }
78
- break;
79
- default:
80
- // eslint-disable-next-line
81
- console.warn(`process-on-worker: unknown message ${type}`);
82
- }
83
- }
@@ -1,35 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.validateWorkerVersion = void 0;
4
- const assert_1 = require("../env-utils/assert");
5
- const version_1 = require("../env-utils/version");
6
- /**
7
- * Check if worker is compatible with this library version
8
- * @param worker
9
- * @param libVersion
10
- * @returns `true` if the two versions are compatible
11
- */
12
- function validateWorkerVersion(worker, coreVersion = version_1.VERSION) {
13
- (0, assert_1.assert)(worker, 'no worker provided');
14
- const workerVersion = worker.version;
15
- if (!coreVersion || !workerVersion) {
16
- return false;
17
- }
18
- // TODO enable when fix the __version__ injection
19
- // const coreVersions = parseVersion(coreVersion);
20
- // const workerVersions = parseVersion(workerVersion);
21
- // assert(
22
- // coreVersion.major === workerVersion.major && coreVersion.minor <= workerVersion.minor,
23
- // `worker: ${worker.name} is not compatible. ${coreVersion.major}.${
24
- // coreVersion.minor
25
- // }+ is required.`
26
- // );
27
- return true;
28
- }
29
- exports.validateWorkerVersion = validateWorkerVersion;
30
- // @ts-ignore
31
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
32
- function parseVersion(version) {
33
- const parts = version.split('.').map(Number);
34
- return { major: parts[0], minor: parts[1] };
35
- }
@@ -1,111 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const get_transfer_list_1 = require("../worker-utils/get-transfer-list");
4
- /** Vile hack to defeat over-zealous bundlers from stripping out the require */
5
- function getParentPort() {
6
- // const isNode = globalThis.process;
7
- let parentPort;
8
- try {
9
- // prettier-ignore
10
- eval('globalThis.parentPort = require(\'worker_threads\').parentPort'); // eslint-disable-line no-eval
11
- parentPort = globalThis.parentPort;
12
- // eslint-disable-next-line no-empty
13
- }
14
- catch { }
15
- return parentPort;
16
- }
17
- const onMessageWrapperMap = new Map();
18
- /**
19
- * Type safe wrapper for worker code
20
- */
21
- class WorkerBody {
22
- /** Check that we are actually in a worker thread */
23
- static inWorkerThread() {
24
- return typeof self !== 'undefined' || Boolean(getParentPort());
25
- }
26
- /*
27
- * (type: WorkerMessageType, payload: WorkerMessagePayload) => any
28
- */
29
- static set onmessage(onMessage) {
30
- function handleMessage(message) {
31
- // Confusingly the message itself also has a 'type' field which is always set to 'message'
32
- const parentPort = getParentPort();
33
- const { type, payload } = parentPort ? message : message.data;
34
- // if (!isKnownMessage(message)) {
35
- // return;
36
- // }
37
- onMessage(type, payload);
38
- }
39
- const parentPort = getParentPort();
40
- if (parentPort) {
41
- parentPort.on('message', handleMessage);
42
- // if (message == 'exit') { parentPort.unref(); }
43
- // eslint-disable-next-line
44
- parentPort.on('exit', () => console.debug('Node worker closing'));
45
- }
46
- else {
47
- // eslint-disable-next-line no-restricted-globals
48
- globalThis.onmessage = handleMessage;
49
- }
50
- }
51
- static addEventListener(onMessage) {
52
- let onMessageWrapper = onMessageWrapperMap.get(onMessage);
53
- if (!onMessageWrapper) {
54
- onMessageWrapper = (message) => {
55
- if (!isKnownMessage(message)) {
56
- return;
57
- }
58
- // Confusingly in the browser, the message itself also has a 'type' field which is always set to 'message'
59
- const parentPort = getParentPort();
60
- const { type, payload } = parentPort ? message : message.data;
61
- onMessage(type, payload);
62
- };
63
- }
64
- const parentPort = getParentPort();
65
- if (parentPort) {
66
- console.error('not implemented'); // eslint-disable-line
67
- }
68
- else {
69
- globalThis.addEventListener('message', onMessageWrapper);
70
- }
71
- }
72
- static removeEventListener(onMessage) {
73
- const onMessageWrapper = onMessageWrapperMap.get(onMessage);
74
- onMessageWrapperMap.delete(onMessage);
75
- const parentPort = getParentPort();
76
- if (parentPort) {
77
- console.error('not implemented'); // eslint-disable-line
78
- }
79
- else {
80
- globalThis.removeEventListener('message', onMessageWrapper);
81
- }
82
- }
83
- /**
84
- * Send a message from a worker to creating thread (main thread)
85
- * @param type
86
- * @param payload
87
- */
88
- static postMessage(type, payload) {
89
- const data = { source: 'loaders.gl', type, payload };
90
- // console.log('posting message', data);
91
- const transferList = (0, get_transfer_list_1.getTransferList)(payload);
92
- const parentPort = getParentPort();
93
- if (parentPort) {
94
- parentPort.postMessage(data, transferList);
95
- // console.log('posted message', data);
96
- }
97
- else {
98
- // @ts-ignore
99
- globalThis.postMessage(data, transferList);
100
- }
101
- }
102
- }
103
- exports.default = WorkerBody;
104
- // Filter out noise messages sent to workers
105
- function isKnownMessage(message) {
106
- const { type, data } = message;
107
- return (type === 'message' &&
108
- data &&
109
- typeof data.source === 'string' &&
110
- data.source.startsWith('loaders.gl'));
111
- }
@@ -1,89 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const worker_pool_1 = __importDefault(require("./worker-pool"));
7
- const worker_thread_1 = __importDefault(require("./worker-thread"));
8
- const DEFAULT_PROPS = {
9
- maxConcurrency: 3,
10
- maxMobileConcurrency: 1,
11
- reuseWorkers: true,
12
- onDebug: () => { }
13
- };
14
- /**
15
- * Process multiple jobs with a "farm" of different workers in worker pools.
16
- */
17
- class WorkerFarm {
18
- /** Checks if workers are supported on this platform */
19
- static isSupported() {
20
- return worker_thread_1.default.isSupported();
21
- }
22
- /** Get the singleton instance of the global worker farm */
23
- static getWorkerFarm(props = {}) {
24
- WorkerFarm._workerFarm = WorkerFarm._workerFarm || new WorkerFarm({});
25
- WorkerFarm._workerFarm.setProps(props);
26
- return WorkerFarm._workerFarm;
27
- }
28
- /** get global instance with WorkerFarm.getWorkerFarm() */
29
- constructor(props) {
30
- this.workerPools = new Map();
31
- this.props = { ...DEFAULT_PROPS };
32
- this.setProps(props);
33
- /** @type Map<string, WorkerPool>} */
34
- this.workerPools = new Map();
35
- }
36
- /**
37
- * Terminate all workers in the farm
38
- * @note Can free up significant memory
39
- */
40
- destroy() {
41
- for (const workerPool of this.workerPools.values()) {
42
- workerPool.destroy();
43
- }
44
- this.workerPools = new Map();
45
- }
46
- /**
47
- * Set props used when initializing worker pools
48
- * @param props
49
- */
50
- setProps(props) {
51
- this.props = { ...this.props, ...props };
52
- // Update worker pool props
53
- for (const workerPool of this.workerPools.values()) {
54
- workerPool.setProps(this._getWorkerPoolProps());
55
- }
56
- }
57
- /**
58
- * Returns a worker pool for the specified worker
59
- * @param options - only used first time for a specific worker name
60
- * @param options.name - the name of the worker - used to identify worker pool
61
- * @param options.url -
62
- * @param options.source -
63
- * @example
64
- * const job = WorkerFarm.getWorkerFarm().getWorkerPool({name, url}).startJob(...);
65
- */
66
- getWorkerPool(options) {
67
- const { name, source, url } = options;
68
- let workerPool = this.workerPools.get(name);
69
- if (!workerPool) {
70
- workerPool = new worker_pool_1.default({
71
- name,
72
- source,
73
- url
74
- });
75
- workerPool.setProps(this._getWorkerPoolProps());
76
- this.workerPools.set(name, workerPool);
77
- }
78
- return workerPool;
79
- }
80
- _getWorkerPoolProps() {
81
- return {
82
- maxConcurrency: this.props.maxConcurrency,
83
- maxMobileConcurrency: this.props.maxMobileConcurrency,
84
- reuseWorkers: this.props.reuseWorkers,
85
- onDebug: this.props.onDebug
86
- };
87
- }
88
- }
89
- exports.default = WorkerFarm;
@@ -1,47 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const assert_1 = require("../env-utils/assert");
4
- /**
5
- * Represents one Job handled by a WorkerPool or WorkerFarm
6
- */
7
- class WorkerJob {
8
- constructor(jobName, workerThread) {
9
- this.isRunning = true;
10
- this._resolve = () => { };
11
- this._reject = () => { };
12
- this.name = jobName;
13
- this.workerThread = workerThread;
14
- this.result = new Promise((resolve, reject) => {
15
- this._resolve = resolve;
16
- this._reject = reject;
17
- });
18
- }
19
- /**
20
- * Send a message to the job's worker thread
21
- * @param data any data structure, ideally consisting mostly of transferrable objects
22
- */
23
- postMessage(type, payload) {
24
- this.workerThread.postMessage({
25
- source: 'loaders.gl',
26
- type,
27
- payload
28
- });
29
- }
30
- /**
31
- * Call to resolve the `result` Promise with the supplied value
32
- */
33
- done(value) {
34
- (0, assert_1.assert)(this.isRunning);
35
- this.isRunning = false;
36
- this._resolve(value);
37
- }
38
- /**
39
- * Call to reject the `result` Promise with the supplied error
40
- */
41
- error(error) {
42
- (0, assert_1.assert)(this.isRunning);
43
- this.isRunning = false;
44
- this._reject(error);
45
- }
46
- }
47
- exports.default = WorkerJob;