@loaders.gl/core 5.0.0-beta.1 → 5.0.0-beta.2

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 (117) hide show
  1. package/README.md +3 -1
  2. package/dist/cluster-source.cjs +7228 -0
  3. package/dist/cluster-source.cjs.map +6 -0
  4. package/dist/cluster-source.d.ts +2 -0
  5. package/dist/cluster-source.d.ts.map +1 -0
  6. package/dist/cluster-source.js +2 -0
  7. package/dist/cluster-source.js.map +1 -0
  8. package/dist/dist.dev.js +894 -273
  9. package/dist/dist.min.js +3 -3
  10. package/dist/federated-table-scan-source.cjs +2677 -0
  11. package/dist/federated-table-scan-source.cjs.map +6 -0
  12. package/dist/federated-table-scan-source.d.ts +2 -0
  13. package/dist/federated-table-scan-source.d.ts.map +1 -0
  14. package/dist/federated-table-scan-source.js +2 -0
  15. package/dist/federated-table-scan-source.js.map +1 -0
  16. package/dist/index.cjs +12 -1045
  17. package/dist/index.cjs.map +3 -3
  18. package/dist/lib/init.js +1 -1
  19. package/dist/loader-utils/index.cjs +43 -1331
  20. package/dist/loader-utils/index.cjs.map +3 -3
  21. package/dist/loader-utils/json-loader.js +1 -1
  22. package/dist/loader-utils/lib/log-utils/log.js +1 -1
  23. package/dist/null-loader.js +1 -1
  24. package/dist/null-worker-node.js +169 -79
  25. package/dist/null-worker.js +166 -55
  26. package/dist/polyfills/images/encode-image-node.d.ts +18 -15
  27. package/dist/polyfills/images/encode-image-node.d.ts.map +1 -1
  28. package/dist/polyfills/images/encode-image-node.js +19 -33
  29. package/dist/polyfills/images/encode-image-node.js.map +1 -1
  30. package/dist/polyfills/images/image-codecs-node.d.ts +2 -6
  31. package/dist/polyfills/images/image-codecs-node.d.ts.map +1 -1
  32. package/dist/polyfills/images/image-codecs-node.js +2 -24
  33. package/dist/polyfills/images/image-codecs-node.js.map +1 -1
  34. package/dist/polyfills/images/load-sharp.d.ts +3 -0
  35. package/dist/polyfills/images/load-sharp.d.ts.map +1 -0
  36. package/dist/polyfills/images/load-sharp.js +11 -0
  37. package/dist/polyfills/images/load-sharp.js.map +1 -0
  38. package/dist/polyfills/images/node-image-bitmap.d.ts +1 -1
  39. package/dist/polyfills/images/node-image-bitmap.js +1 -1
  40. package/dist/polyfills/images/node-image-formats.d.ts +1 -1
  41. package/dist/polyfills/images/node-image-formats.d.ts.map +1 -1
  42. package/dist/polyfills/images/node-image-formats.js +10 -4
  43. package/dist/polyfills/images/node-image-formats.js.map +1 -1
  44. package/dist/polyfills/images/parse-image-node.d.ts +10 -2
  45. package/dist/polyfills/images/parse-image-node.d.ts.map +1 -1
  46. package/dist/polyfills/images/parse-image-node.js +20 -32
  47. package/dist/polyfills/images/parse-image-node.js.map +1 -1
  48. package/dist/polyfills/index.cjs +73 -149
  49. package/dist/vector-table-scan-source.cjs +1703 -0
  50. package/dist/vector-table-scan-source.cjs.map +6 -0
  51. package/dist/vector-table-scan-source.d.ts +2 -0
  52. package/dist/vector-table-scan-source.d.ts.map +1 -0
  53. package/dist/vector-table-scan-source.js +2 -0
  54. package/dist/vector-table-scan-source.js.map +1 -0
  55. package/dist/worker-utils/index.cjs +72 -1225
  56. package/dist/worker-utils/index.cjs.map +3 -3
  57. package/dist/worker-utils/lib/async-queue/async-queue.d.ts +1 -31
  58. package/dist/worker-utils/lib/async-queue/async-queue.d.ts.map +1 -1
  59. package/dist/worker-utils/lib/async-queue/async-queue.js +1 -87
  60. package/dist/worker-utils/lib/async-queue/async-queue.js.map +1 -1
  61. package/dist/worker-utils/lib/env-utils/version.js +1 -1
  62. package/dist/worker-utils/lib/worker-api/create-worker.d.ts +1 -8
  63. package/dist/worker-utils/lib/worker-api/create-worker.d.ts.map +1 -1
  64. package/dist/worker-utils/lib/worker-api/create-worker.js +1 -157
  65. package/dist/worker-utils/lib/worker-api/create-worker.js.map +1 -1
  66. package/dist/worker-utils/lib/worker-api/process-on-worker.d.ts +2 -49
  67. package/dist/worker-utils/lib/worker-api/process-on-worker.d.ts.map +1 -1
  68. package/dist/worker-utils/lib/worker-api/process-on-worker.js +1 -345
  69. package/dist/worker-utils/lib/worker-api/process-on-worker.js.map +1 -1
  70. package/dist/worker-utils/lib/worker-farm/worker-body.d.ts +1 -19
  71. package/dist/worker-utils/lib/worker-farm/worker-body.d.ts.map +1 -1
  72. package/dist/worker-utils/lib/worker-farm/worker-body.js +1 -127
  73. package/dist/worker-utils/lib/worker-farm/worker-body.js.map +1 -1
  74. package/dist/worker-utils/lib/worker-farm/worker-farm.d.ts +1 -57
  75. package/dist/worker-utils/lib/worker-farm/worker-farm.d.ts.map +1 -1
  76. package/dist/worker-utils/lib/worker-farm/worker-farm.js +1 -112
  77. package/dist/worker-utils/lib/worker-farm/worker-farm.js.map +1 -1
  78. package/dist/worker-utils/lib/worker-farm/worker-job.d.ts +1 -33
  79. package/dist/worker-utils/lib/worker-farm/worker-job.d.ts.map +1 -1
  80. package/dist/worker-utils/lib/worker-farm/worker-job.js +1 -70
  81. package/dist/worker-utils/lib/worker-farm/worker-job.js.map +1 -1
  82. package/dist/worker-utils/lib/worker-farm/worker-pool.d.ts +1 -93
  83. package/dist/worker-utils/lib/worker-farm/worker-pool.d.ts.map +1 -1
  84. package/dist/worker-utils/lib/worker-farm/worker-pool.js +1 -242
  85. package/dist/worker-utils/lib/worker-farm/worker-pool.js.map +1 -1
  86. package/dist/worker-utils/lib/worker-farm/worker-thread.d.ts +1 -66
  87. package/dist/worker-utils/lib/worker-farm/worker-thread.d.ts.map +1 -1
  88. package/dist/worker-utils/lib/worker-farm/worker-thread.js +1 -171
  89. package/dist/worker-utils/lib/worker-farm/worker-thread.js.map +1 -1
  90. package/dist/worker-utils/null-worker-node.js +234 -144
  91. package/dist/worker-utils/null-worker-node.js.map +4 -4
  92. package/dist/worker-utils/null-worker.js +232 -121
  93. package/dist/worker-utils/null-worker.js.map +4 -4
  94. package/dist/worker-utils/types.d.ts +1 -99
  95. package/dist/worker-utils/types.d.ts.map +1 -1
  96. package/package.json +27 -29
  97. package/src/cluster-source.ts +1 -0
  98. package/src/federated-table-scan-source.ts +1 -0
  99. package/src/polyfills/README.md +2 -2
  100. package/src/polyfills/images/encode-image-node.ts +44 -37
  101. package/src/polyfills/images/image-codecs-node.ts +2 -37
  102. package/src/polyfills/images/load-sharp.ts +13 -0
  103. package/src/polyfills/images/node-image-bitmap.ts +1 -1
  104. package/src/polyfills/images/node-image-formats.ts +10 -4
  105. package/src/polyfills/images/parse-image-node.ts +31 -40
  106. package/src/vector-table-scan-source.ts +1 -0
  107. package/src/worker-utils/lib/async-queue/async-queue.ts +1 -96
  108. package/src/worker-utils/lib/worker-api/create-worker.ts +1 -201
  109. package/src/worker-utils/lib/worker-api/process-on-worker.ts +8 -464
  110. package/src/worker-utils/lib/worker-farm/worker-body.ts +1 -141
  111. package/src/worker-utils/lib/worker-farm/worker-farm.ts +1 -140
  112. package/src/worker-utils/lib/worker-farm/worker-job.ts +1 -81
  113. package/src/worker-utils/lib/worker-farm/worker-pool.ts +1 -312
  114. package/src/worker-utils/lib/worker-farm/worker-thread.ts +1 -202
  115. package/src/worker-utils/types.ts +14 -144
  116. package/src/polyfills/images/encode-image.node.ts.disabled +0 -41
  117. package/src/polyfills/images/parse-image.node.ts.disabled +0 -55
@@ -2,143 +2,4 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
  // Copyright (c) vis.gl contributors
4
4
 
5
- import WorkerPool from './worker-pool';
6
- import type {WorkerPoolTarget} from './worker-pool';
7
- import WorkerThread from './worker-thread';
8
- import type {LoadWorker} from '../../types';
9
-
10
- /**
11
- * @param maxConcurrency - max count of workers
12
- * @param maxMobileConcurrency - max count of workers on mobile
13
- * @param maxConcurrency - max count of workers
14
- * @param reuseWorkers - if false, destroys workers when task is completed
15
- * @param onDebug - callback intended to allow application to log worker pool activity
16
- */
17
- export type WorkerFarmProps = {
18
- maxConcurrency?: number;
19
- maxMobileConcurrency?: number;
20
- reuseWorkers?: boolean;
21
- onDebug?: () => void;
22
- };
23
-
24
- const DEFAULT_PROPS: Required<WorkerFarmProps> = {
25
- maxConcurrency: 3,
26
- maxMobileConcurrency: 1,
27
- reuseWorkers: true,
28
- onDebug: () => {}
29
- };
30
-
31
- /** Stable ids used to distinguish worker factories in the pool cache. */
32
- const loadWorkerIds = new WeakMap<LoadWorker, number>();
33
- /** Next stable worker-factory id. */
34
- let nextLoadWorkerId = 1;
35
-
36
- /**
37
- * Process multiple jobs with a "farm" of different workers in worker pools.
38
- */
39
- export default class WorkerFarm {
40
- private props: WorkerFarmProps;
41
- private workerPools = new Map<string, WorkerPool>();
42
- // singleton
43
- private static _workerFarm?: WorkerFarm;
44
-
45
- /** Checks if workers are supported on this platform */
46
- static isSupported(): boolean {
47
- return WorkerThread.isSupported();
48
- }
49
-
50
- /** Get the singleton instance of the global worker farm */
51
- static getWorkerFarm(props: WorkerFarmProps = {}): WorkerFarm {
52
- WorkerFarm._workerFarm = WorkerFarm._workerFarm || new WorkerFarm({});
53
- WorkerFarm._workerFarm.setProps(props);
54
- return WorkerFarm._workerFarm;
55
- }
56
-
57
- /** get global instance with WorkerFarm.getWorkerFarm() */
58
- private constructor(props: WorkerFarmProps) {
59
- this.props = {...DEFAULT_PROPS};
60
- this.setProps(props);
61
- /** @type Map<string, WorkerPool>} */
62
- this.workerPools = new Map();
63
- }
64
-
65
- /**
66
- * Terminate all workers in the farm and abort active jobs.
67
- * @param reason Optional error delivered to active jobs.
68
- * @note Can free up significant memory
69
- */
70
- destroy(reason?: unknown): void {
71
- for (const workerPool of this.workerPools.values()) {
72
- workerPool.destroy(reason);
73
- }
74
- this.workerPools = new Map<string, WorkerPool>();
75
- }
76
-
77
- /**
78
- * Set props used when initializing worker pools
79
- * @param props
80
- */
81
- setProps(props: WorkerFarmProps): void {
82
- this.props = {...this.props, ...props};
83
- // Update worker pool props
84
- for (const workerPool of this.workerPools.values()) {
85
- workerPool.setProps(this._getWorkerPoolProps());
86
- }
87
- }
88
-
89
- /**
90
- * Returns a worker pool for the specified worker
91
- * @param options Worker target used to identify and initialize the pool.
92
- * @param options.name Worker name used as the base pool identity.
93
- * @param options.url Worker script URL.
94
- * @param options.source Inline worker source.
95
- * @param options.loadWorker Built-in browser worker factory.
96
- * @example
97
- * const job = WorkerFarm.getWorkerFarm().getWorkerPool({name, url}).startJob(...);
98
- */
99
- getWorkerPool(options: WorkerPoolTarget): WorkerPool {
100
- const {name, source, url, getUrl, loadWorker} = options;
101
- const workerPoolKey = getWorkerPoolKey(options);
102
- let workerPool = this.workerPools.get(workerPoolKey);
103
- if (!workerPool) {
104
- workerPool = new WorkerPool({
105
- name,
106
- source,
107
- url,
108
- getUrl,
109
- loadWorker
110
- });
111
- workerPool.setProps(this._getWorkerPoolProps());
112
- this.workerPools.set(workerPoolKey, workerPool);
113
- }
114
- return workerPool;
115
- }
116
-
117
- _getWorkerPoolProps() {
118
- return {
119
- maxConcurrency: this.props.maxConcurrency,
120
- maxMobileConcurrency: this.props.maxMobileConcurrency,
121
- reuseWorkers: this.props.reuseWorkers,
122
- onDebug: this.props.onDebug
123
- };
124
- }
125
- }
126
-
127
- /** Returns a cache key that distinguishes each worker source and factory. */
128
- function getWorkerPoolKey(options: WorkerPoolTarget): string {
129
- const {name, source, url, urlKey, loadWorker} = options;
130
- const sourceKey = source ? `source:${source}` : '';
131
- const urlKeyPart = url || urlKey ? `url:${url || urlKey}` : '';
132
- const loadWorkerKey = loadWorker ? `loadWorker:${getLoadWorkerId(loadWorker)}` : '';
133
- return [name, sourceKey, urlKeyPart, loadWorkerKey].filter(Boolean).join('|');
134
- }
135
-
136
- /** Returns a stable identifier for a worker factory function. */
137
- function getLoadWorkerId(loadWorker: LoadWorker): number {
138
- let loadWorkerId = loadWorkerIds.get(loadWorker);
139
- if (!loadWorkerId) {
140
- loadWorkerId = nextLoadWorkerId++;
141
- loadWorkerIds.set(loadWorker, loadWorkerId);
142
- }
143
- return loadWorkerId;
144
- }
5
+ export {WorkerFarm as default} from '@math.gl/core/tasks';
@@ -2,84 +2,4 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
  // Copyright (c) vis.gl contributors
4
4
 
5
- import type {WorkerMessageType, WorkerMessagePayload} from '../../types';
6
- import WorkerThread from './worker-thread';
7
-
8
- /**
9
- * Represents one Job handled by a WorkerPool or WorkerFarm
10
- */
11
- export default class WorkerJob {
12
- readonly name: string;
13
- readonly workerThread: WorkerThread;
14
- isRunning: boolean = true;
15
- /** Promise that resolves when Job is done */
16
- readonly result: Promise<any>;
17
-
18
- private _resolve: (value: any) => void = () => {};
19
- private _reject: (reason?: any) => void = () => {};
20
-
21
- constructor(jobName: string, workerThread: WorkerThread) {
22
- this.name = jobName;
23
- this.workerThread = workerThread;
24
- this.result = new Promise((resolve, reject) => {
25
- this._resolve = resolve;
26
- this._reject = reject;
27
- });
28
- }
29
-
30
- /**
31
- * Send a message to the job's worker thread
32
- * @param data any data structure, ideally consisting mostly of transferrable objects
33
- */
34
- postMessage(type: WorkerMessageType, payload: WorkerMessagePayload): void {
35
- if (!this.isRunning) return;
36
- this.workerThread.postMessage({
37
- source: 'loaders.gl', // Lets worker ignore unrelated messages
38
- type,
39
- payload
40
- });
41
- }
42
-
43
- /**
44
- * Call to resolve the `result` Promise with the supplied value
45
- */
46
- done(value: any): void {
47
- if (!this.isRunning) {
48
- return;
49
- }
50
- this.isRunning = false;
51
- this._resolve(value);
52
- }
53
-
54
- /**
55
- * Call to reject the `result` Promise with the supplied error
56
- */
57
- error(error: unknown): void {
58
- if (!this.isRunning) {
59
- return;
60
- }
61
- this.isRunning = false;
62
- this._reject(error);
63
- }
64
-
65
- /**
66
- * Terminates the worker executing this job and rejects its result.
67
- * @param reason Abort reason supplied by the caller, or a cross-runtime `AbortError`.
68
- */
69
- abort(reason?: unknown): void {
70
- if (!this.isRunning) {
71
- return;
72
- }
73
- this.workerThread.destroy();
74
- this.error(
75
- arguments.length ? reason : createAbortError(`Worker job "${this.name}" was aborted`)
76
- );
77
- }
78
- }
79
-
80
- /** Creates an abort error without requiring the DOMException global. */
81
- function createAbortError(message: string): Error {
82
- const error = new Error(message);
83
- error.name = 'AbortError';
84
- return error;
85
- }
5
+ export {WorkerJob as default} from '@math.gl/core/tasks';
@@ -2,315 +2,4 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
  // Copyright (c) vis.gl contributors
4
4
 
5
- import type {LoadWorker, WorkerMessageType, WorkerMessagePayload} from '../../types';
6
- import {isMobile} from '../env-utils/globals';
7
- import WorkerThread from './worker-thread';
8
- import WorkerJob from './worker-job';
9
-
10
- /** WorkerPool onDebug Callback Parameters */
11
- type OnDebugParameters = {
12
- message: string;
13
- worker: string;
14
- name: string;
15
- job: string;
16
- backlog: number;
17
- workerThread: WorkerThread;
18
- };
19
-
20
- /** WorkerPool Properties */
21
- export type WorkerPoolProps = {
22
- name?: string;
23
- source?: string; // | Function;
24
- url?: string;
25
- /** Lazily resolves a classic worker fallback URL. */
26
- getUrl?: () => string;
27
- /** Creates a browser Worker directly. */
28
- loadWorker?: LoadWorker;
29
- maxConcurrency?: number;
30
- maxMobileConcurrency?: number;
31
- onDebug?: (options: OnDebugParameters) => any;
32
- reuseWorkers?: boolean;
33
- };
34
-
35
- /** Worker-pool target, including values used only to distinguish cached pools. */
36
- export type WorkerPoolTarget = WorkerPoolProps & {
37
- /** Worker name used as the base pool identity. */
38
- name: string;
39
- /** Stable identity for a lazily resolved URL. */
40
- urlKey?: string;
41
- };
42
-
43
- /** Private helper types */
44
- type OnMessage = (job: WorkerJob, type: WorkerMessageType, payload: WorkerMessagePayload) => void;
45
- type OnError = (job: WorkerJob, error: Error) => void;
46
-
47
- type QueuedJob = {
48
- name: string;
49
- onMessage: OnMessage;
50
- onError: OnError;
51
- onStart: (value: any) => void; // Resolve job start promise
52
- onReject: (reason: unknown) => void; // Reject job start promise
53
- /** Removes the queued cancellation listener when the job leaves the queue. */
54
- removeAbortListener: () => void;
55
- /** Cancels this queued or active job. */
56
- signal?: AbortSignal;
57
- };
58
-
59
- /**
60
- * Process multiple data messages with small pool of identical workers
61
- */
62
- export default class WorkerPool {
63
- name: string = 'unnamed';
64
- source?: string; // | Function;
65
- url?: string;
66
- /** Lazily resolves a classic worker fallback URL. */
67
- getUrl?: () => string;
68
- /** Creates a browser Worker directly. */
69
- loadWorker?: LoadWorker;
70
- maxConcurrency: number = 1;
71
- maxMobileConcurrency: number = 1;
72
- onDebug: (options: OnDebugParameters) => any = () => {};
73
- reuseWorkers: boolean = true;
74
-
75
- private props: WorkerPoolProps = {};
76
- private jobQueue: QueuedJob[] = [];
77
- private idleQueue: WorkerThread[] = [];
78
- private activeJobs = new Set<WorkerJob>();
79
- private count = 0;
80
- private isDestroyed = false;
81
-
82
- /** Checks if workers are supported on this platform */
83
- static isSupported(): boolean {
84
- return WorkerThread.isSupported();
85
- }
86
-
87
- /**
88
- * @param processor - worker function
89
- * @param maxConcurrency - max count of workers
90
- */
91
- constructor(props: WorkerPoolProps) {
92
- this.source = props.source;
93
- this.url = props.url;
94
- this.getUrl = props.getUrl;
95
- this.loadWorker = props.loadWorker;
96
- this.setProps(props);
97
- }
98
-
99
- /**
100
- * Terminates all workers in the pool and aborts active jobs.
101
- * @param reason Optional error delivered to active jobs.
102
- * @note Can free up significant memory
103
- */
104
- destroy(reason: unknown = new Error('Worker pool was destroyed')): void {
105
- // Abort active jobs so callers receive an error when a development worker is invalidated.
106
- this.isDestroyed = true;
107
- this.activeJobs.forEach(job => job.abort(reason));
108
- const queuedJobs = this.jobQueue.splice(0);
109
- queuedJobs.forEach(queuedJob => {
110
- queuedJob.removeAbortListener();
111
- queuedJob.onReject(reason);
112
- });
113
- this.idleQueue.forEach(worker => worker.destroy());
114
- this.isDestroyed = true;
115
- }
116
-
117
- setProps(props: WorkerPoolProps) {
118
- this.props = {...this.props, ...props};
119
-
120
- if (props.name !== undefined) {
121
- this.name = props.name;
122
- }
123
- if (props.maxConcurrency !== undefined) {
124
- this.maxConcurrency = props.maxConcurrency;
125
- }
126
- if (props.maxMobileConcurrency !== undefined) {
127
- this.maxMobileConcurrency = props.maxMobileConcurrency;
128
- }
129
- if (props.reuseWorkers !== undefined) {
130
- this.reuseWorkers = props.reuseWorkers;
131
- }
132
- if (props.onDebug !== undefined) {
133
- this.onDebug = props.onDebug;
134
- }
135
- }
136
-
137
- async startJob(
138
- name: string,
139
- onMessage: OnMessage = (job, type, data) => job.done(data),
140
- onError: OnError = (job, error) => job.error(error),
141
- signal?: AbortSignal
142
- ): Promise<WorkerJob> {
143
- if (signal?.aborted) {
144
- throw signal.reason;
145
- }
146
- if (this.isDestroyed) {
147
- return Promise.reject(new Error('Worker pool was destroyed'));
148
- }
149
- // Promise resolves when thread starts working on this job
150
- const startPromise = new Promise<WorkerJob>((onStart, onReject) => {
151
- // Promise resolves when thread completes or fails working on this job
152
- const abortQueuedJob = (): void => {
153
- const index = this.jobQueue.indexOf(queuedJob);
154
- if (index >= 0) {
155
- this.jobQueue.splice(index, 1);
156
- queuedJob.removeAbortListener();
157
- onReject(signal?.reason);
158
- }
159
- };
160
- const queuedJob: QueuedJob = {
161
- name,
162
- onMessage,
163
- onError,
164
- onStart,
165
- onReject,
166
- signal,
167
- removeAbortListener: () => signal?.removeEventListener('abort', abortQueuedJob)
168
- };
169
- this.jobQueue.push(queuedJob);
170
- signal?.addEventListener('abort', abortQueuedJob, {once: true});
171
- return this;
172
- });
173
- this._startQueuedJob(); // eslint-disable-line @typescript-eslint/no-floating-promises
174
- return await startPromise;
175
- }
176
-
177
- // PRIVATE
178
-
179
- /**
180
- * Starts first queued job if worker is available or can be created
181
- * Called when job is started and whenever a worker returns to the idleQueue
182
- */
183
- async _startQueuedJob(): Promise<void> {
184
- if (!this.jobQueue.length) {
185
- return;
186
- }
187
-
188
- let workerThread: WorkerThread | null;
189
- try {
190
- workerThread = this._getAvailableWorker();
191
- } catch (error) {
192
- const queuedJob = this.jobQueue.shift();
193
- queuedJob?.removeAbortListener();
194
- queuedJob?.onReject(error);
195
- void this._startQueuedJob();
196
- return;
197
- }
198
- if (!workerThread) {
199
- return;
200
- }
201
-
202
- // We have a worker, dequeue and start the job
203
- const queuedJob = this.jobQueue.shift();
204
- if (queuedJob) {
205
- // Emit a debug event
206
- // @ts-ignore
207
- this.onDebug({
208
- message: 'Starting job',
209
- name: queuedJob.name,
210
- workerThread,
211
- backlog: this.jobQueue.length
212
- });
213
-
214
- // Create a worker job to let the app access thread and manage job completion
215
- const job = new WorkerJob(queuedJob.name, workerThread);
216
- queuedJob.removeAbortListener();
217
- const abortJob = (): void => job.abort(queuedJob.signal?.reason);
218
- queuedJob.signal?.addEventListener('abort', abortJob, {once: true});
219
- if (queuedJob.signal?.aborted) abortJob();
220
- this.activeJobs.add(job);
221
- workerThread.ref();
222
-
223
- // Set the worker thread's message handlers
224
- workerThread.onMessage = data => {
225
- if (job.isRunning) queuedJob.onMessage(job, data.type, data.payload);
226
- };
227
- workerThread.onError = error => queuedJob.onError(job, error);
228
-
229
- // Resolve the start promise so that the app can start sending messages to worker
230
- queuedJob.onStart(job);
231
-
232
- // Wait for the app to signal that the job is complete, then return worker to queue
233
- try {
234
- await job.result;
235
- } catch {
236
- // The job result promise carries worker errors back to the caller; do not duplicate-log
237
- // handled rejections here.
238
- } finally {
239
- queuedJob.signal?.removeEventListener('abort', abortJob);
240
- this.activeJobs.delete(job);
241
- this.returnWorkerToQueue(workerThread);
242
- }
243
- } else {
244
- this.returnWorkerToQueue(workerThread);
245
- }
246
- }
247
-
248
- /**
249
- * Returns a worker to the idle queue
250
- * Destroys the worker if
251
- * - pool is destroyed
252
- * - if this pool doesn't reuse workers
253
- * - if maxConcurrency has been lowered
254
- * @param worker
255
- */
256
- returnWorkerToQueue(worker: WorkerThread) {
257
- const shouldDestroyWorker =
258
- // Aborted jobs terminate their worker immediately.
259
- worker.terminated ||
260
- // If the pool is destroyed, there is no reason to keep the worker around
261
- this.isDestroyed ||
262
- // If the app has disabled worker reuse, any completed workers should be destroyed
263
- !this.reuseWorkers ||
264
- // If concurrency has been lowered, this worker might be surplus to requirements
265
- this.count > this._getMaxConcurrency();
266
-
267
- if (shouldDestroyWorker) {
268
- if (!worker.terminated) {
269
- worker.destroy();
270
- }
271
- this.count--;
272
- } else {
273
- worker.unref();
274
- this.idleQueue.push(worker);
275
- }
276
-
277
- if (!this.isDestroyed) {
278
- this._startQueuedJob(); // eslint-disable-line @typescript-eslint/no-floating-promises
279
- }
280
- }
281
-
282
- /**
283
- * Returns idle worker or creates new worker if maxConcurrency has not been reached
284
- */
285
- _getAvailableWorker(): WorkerThread | null {
286
- // If a worker has completed and returned to the queue, it can be used
287
- if (this.idleQueue.length > 0) {
288
- return this.idleQueue.shift() || null;
289
- }
290
-
291
- // Create fresh worker if we haven't yet created the max amount of worker threads for this worker source
292
- if (this.count < this._getMaxConcurrency()) {
293
- this.count++;
294
- const name = `${this.name.toLowerCase()} (#${this.count} of ${this.maxConcurrency})`;
295
- try {
296
- return new WorkerThread({
297
- name,
298
- source: this.source,
299
- url: this.url,
300
- getUrl: this.getUrl,
301
- loadWorker: this.loadWorker
302
- });
303
- } catch (error) {
304
- this.count--;
305
- throw error;
306
- }
307
- }
308
-
309
- // No worker available, have to wait
310
- return null;
311
- }
312
-
313
- _getMaxConcurrency() {
314
- return isMobile ? this.maxMobileConcurrency : this.maxConcurrency;
315
- }
316
- }
5
+ export {WorkerPool as default} from '@math.gl/core/tasks';