@loaders.gl/worker-utils 3.1.0-alpha.5 → 3.1.0-beta.4

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 (120) hide show
  1. package/dist/es5/lib/env-utils/version.js +2 -2
  2. package/dist/es5/lib/env-utils/version.js.map +1 -1
  3. package/dist/es5/lib/library-utils/library-utils.js +1 -1
  4. package/dist/es5/lib/library-utils/library-utils.js.map +1 -1
  5. package/dist/es5/lib/node/require-utils.node.js +4 -8
  6. package/dist/es5/lib/node/require-utils.node.js.map +1 -1
  7. package/dist/es5/lib/process-utils/child-process-proxy.js.map +1 -1
  8. package/dist/es5/lib/worker-api/create-worker.js +1 -1
  9. package/dist/es5/lib/worker-api/create-worker.js.map +1 -1
  10. package/dist/es5/lib/worker-api/get-worker-url.js +1 -1
  11. package/dist/es5/lib/worker-api/get-worker-url.js.map +1 -1
  12. package/dist/es5/lib/worker-api/process-on-worker.js +1 -1
  13. package/dist/es5/lib/worker-api/process-on-worker.js.map +1 -1
  14. package/dist/es5/lib/worker-farm/worker-body.js.map +1 -1
  15. package/dist/es5/lib/worker-farm/worker-job.js.map +1 -1
  16. package/dist/es5/lib/worker-farm/worker-thread.js.map +1 -1
  17. package/dist/es5/lib/worker-utils/get-transfer-list.js.map +1 -1
  18. package/dist/es5/lib/worker-utils/remove-nontransferable-options.js.map +1 -1
  19. package/dist/esm/lib/env-utils/version.js +2 -2
  20. package/dist/esm/lib/env-utils/version.js.map +1 -1
  21. package/dist/esm/lib/library-utils/library-utils.js +1 -1
  22. package/dist/esm/lib/library-utils/library-utils.js.map +1 -1
  23. package/dist/esm/lib/node/require-utils.node.js +4 -8
  24. package/dist/esm/lib/node/require-utils.node.js.map +1 -1
  25. package/dist/esm/lib/process-utils/child-process-proxy.js.map +1 -1
  26. package/dist/esm/lib/worker-api/create-worker.js +1 -1
  27. package/dist/esm/lib/worker-api/create-worker.js.map +1 -1
  28. package/dist/esm/lib/worker-api/get-worker-url.js +1 -1
  29. package/dist/esm/lib/worker-api/get-worker-url.js.map +1 -1
  30. package/dist/esm/lib/worker-api/process-on-worker.js +1 -1
  31. package/dist/esm/lib/worker-api/process-on-worker.js.map +1 -1
  32. package/dist/esm/lib/worker-farm/worker-body.js.map +1 -1
  33. package/dist/esm/lib/worker-farm/worker-job.js.map +1 -1
  34. package/dist/esm/lib/worker-farm/worker-thread.js.map +1 -1
  35. package/dist/esm/lib/worker-utils/get-transfer-list.js.map +1 -1
  36. package/dist/esm/lib/worker-utils/remove-nontransferable-options.js.map +1 -1
  37. package/dist/index.d.ts +1 -0
  38. package/dist/index.d.ts.map +1 -0
  39. package/dist/index.js +58 -0
  40. package/dist/lib/async-queue/async-queue.d.ts +1 -0
  41. package/dist/lib/async-queue/async-queue.d.ts.map +1 -0
  42. package/dist/lib/async-queue/async-queue.js +87 -0
  43. package/dist/lib/env-utils/assert.d.ts +1 -0
  44. package/dist/lib/env-utils/assert.d.ts.map +1 -0
  45. package/dist/lib/env-utils/assert.js +13 -0
  46. package/dist/lib/env-utils/globals.d.ts +1 -0
  47. package/dist/lib/env-utils/globals.d.ts.map +1 -0
  48. package/dist/lib/env-utils/globals.js +32 -0
  49. package/dist/lib/env-utils/version.d.ts +2 -1
  50. package/dist/lib/env-utils/version.d.ts.map +1 -0
  51. package/dist/lib/env-utils/version.js +12 -0
  52. package/dist/lib/library-utils/library-utils.d.ts +2 -1
  53. package/dist/lib/library-utils/library-utils.d.ts.map +1 -0
  54. package/dist/lib/library-utils/library-utils.js +158 -0
  55. package/dist/lib/node/require-utils.node.d.ts +6 -2
  56. package/dist/lib/node/require-utils.node.d.ts.map +1 -0
  57. package/dist/lib/node/require-utils.node.js +60 -0
  58. package/dist/lib/process-utils/child-process-proxy.d.ts +1 -0
  59. package/dist/lib/process-utils/child-process-proxy.d.ts.map +1 -0
  60. package/dist/lib/process-utils/child-process-proxy.js +131 -0
  61. package/dist/lib/process-utils/process-utils.d.ts +1 -0
  62. package/dist/lib/process-utils/process-utils.d.ts.map +1 -0
  63. package/dist/lib/process-utils/process-utils.js +35 -0
  64. package/dist/lib/worker-api/create-worker.d.ts +3 -2
  65. package/dist/lib/worker-api/create-worker.d.ts.map +1 -0
  66. package/dist/lib/worker-api/create-worker.js +92 -0
  67. package/dist/lib/worker-api/get-worker-url.d.ts +1 -0
  68. package/dist/lib/worker-api/get-worker-url.d.ts.map +1 -0
  69. package/dist/lib/worker-api/get-worker-url.js +48 -0
  70. package/dist/lib/worker-api/process-on-worker.d.ts +1 -0
  71. package/dist/lib/worker-api/process-on-worker.d.ts.map +1 -0
  72. package/dist/lib/worker-api/process-on-worker.js +79 -0
  73. package/dist/lib/worker-api/validate-worker-version.d.ts +1 -0
  74. package/dist/lib/worker-api/validate-worker-version.d.ts.map +1 -0
  75. package/dist/lib/worker-api/validate-worker-version.js +35 -0
  76. package/dist/lib/worker-farm/worker-body.d.ts +1 -0
  77. package/dist/lib/worker-farm/worker-body.d.ts.map +1 -0
  78. package/dist/lib/worker-farm/worker-body.js +67 -0
  79. package/dist/lib/worker-farm/worker-farm.d.ts +1 -0
  80. package/dist/lib/worker-farm/worker-farm.d.ts.map +1 -0
  81. package/dist/lib/worker-farm/worker-farm.js +88 -0
  82. package/dist/lib/worker-farm/worker-job.d.ts +2 -1
  83. package/dist/lib/worker-farm/worker-job.d.ts.map +1 -0
  84. package/dist/lib/worker-farm/worker-job.js +47 -0
  85. package/dist/lib/worker-farm/worker-pool.d.ts +1 -0
  86. package/dist/lib/worker-farm/worker-pool.d.ts.map +1 -0
  87. package/dist/lib/worker-farm/worker-pool.js +151 -0
  88. package/dist/lib/worker-farm/worker-thread.d.ts +2 -1
  89. package/dist/lib/worker-farm/worker-thread.d.ts.map +1 -0
  90. package/dist/lib/worker-farm/worker-thread.js +95 -0
  91. package/dist/lib/worker-utils/get-loadable-worker-url.d.ts +1 -0
  92. package/dist/lib/worker-utils/get-loadable-worker-url.d.ts.map +1 -0
  93. package/dist/lib/worker-utils/get-loadable-worker-url.js +74 -0
  94. package/dist/lib/worker-utils/get-transfer-list.d.ts +1 -0
  95. package/dist/lib/worker-utils/get-transfer-list.d.ts.map +1 -0
  96. package/dist/lib/worker-utils/get-transfer-list.js +61 -0
  97. package/dist/lib/worker-utils/remove-nontransferable-options.d.ts +1 -0
  98. package/dist/lib/worker-utils/remove-nontransferable-options.d.ts.map +1 -0
  99. package/dist/lib/worker-utils/remove-nontransferable-options.js +35 -0
  100. package/dist/null-worker.js +189 -550
  101. package/dist/null-worker.js.map +7 -1
  102. package/dist/types.d.ts +2 -1
  103. package/dist/types.d.ts.map +1 -0
  104. package/dist/types.js +2 -0
  105. package/dist/workers/null-worker.d.ts +1 -0
  106. package/dist/workers/null-worker.d.ts.map +1 -0
  107. package/dist/workers/null-worker.js +7 -0
  108. package/package.json +7 -6
  109. package/src/lib/env-utils/version.ts +1 -1
  110. package/src/lib/library-utils/library-utils.ts +6 -4
  111. package/src/lib/node/{require-utils.node.js → require-utils.node.ts} +13 -9
  112. package/src/lib/process-utils/child-process-proxy.ts +1 -1
  113. package/src/lib/worker-api/create-worker.ts +11 -7
  114. package/src/lib/worker-api/process-on-worker.ts +1 -1
  115. package/src/lib/worker-farm/worker-body.ts +2 -2
  116. package/src/lib/worker-farm/worker-job.ts +2 -2
  117. package/src/lib/worker-farm/worker-thread.ts +2 -2
  118. package/src/lib/worker-utils/get-transfer-list.ts +1 -1
  119. package/src/lib/worker-utils/remove-nontransferable-options.ts +1 -1
  120. package/src/types.ts +1 -1
@@ -0,0 +1,79 @@
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 remove_nontransferable_options_1 = require("../worker-utils/remove-nontransferable-options");
9
+ const get_worker_url_1 = require("./get-worker-url");
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 url = (0, get_worker_url_1.getWorkerURL)(worker, options);
31
+ const workerFarm = worker_farm_1.default.getWorkerFarm(options);
32
+ const workerPool = workerFarm.getWorkerPool({ name, url });
33
+ const jobName = options.jobName || worker.name;
34
+ const job = await workerPool.startJob(jobName,
35
+ // eslint-disable-next-line
36
+ onMessage.bind(null, context));
37
+ // Kick off the processing in the worker
38
+ const transferableOptions = (0, remove_nontransferable_options_1.removeNontransferableOptions)(options);
39
+ job.postMessage('process', { input: data, options: transferableOptions });
40
+ const result = await job.result;
41
+ return result.result;
42
+ }
43
+ exports.processOnWorker = processOnWorker;
44
+ /**
45
+ * Job completes when we receive the result
46
+ * @param job
47
+ * @param message
48
+ */
49
+ async function onMessage(context, job, type, payload) {
50
+ switch (type) {
51
+ case 'done':
52
+ // Worker is done
53
+ job.done(payload);
54
+ break;
55
+ case 'error':
56
+ // Worker encountered an error
57
+ job.error(new Error(payload.error));
58
+ break;
59
+ case 'process':
60
+ // Worker is asking for us (main thread) to process something
61
+ const { id, input, options } = payload;
62
+ try {
63
+ if (!context.process) {
64
+ job.postMessage('error', { id, error: 'Worker not set up to process on main thread' });
65
+ return;
66
+ }
67
+ const result = await context.process(input, options);
68
+ job.postMessage('done', { id, result });
69
+ }
70
+ catch (error) {
71
+ const message = error instanceof Error ? error.message : 'unknown error';
72
+ job.postMessage('error', { id, error: message });
73
+ }
74
+ break;
75
+ default:
76
+ // eslint-disable-next-line
77
+ console.warn(`process-on-worker: unknown message ${type}`);
78
+ }
79
+ }
@@ -6,3 +6,4 @@ import type { WorkerObject } from '../../types';
6
6
  * @returns `true` if the two versions are compatible
7
7
  */
8
8
  export declare function validateWorkerVersion(worker: WorkerObject, coreVersion?: string): boolean;
9
+ //# sourceMappingURL=validate-worker-version.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validate-worker-version.d.ts","sourceRoot":"","sources":["../../../src/lib/worker-api/validate-worker-version.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,aAAa,CAAC;AAI9C;;;;;GAKG;AACH,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,YAAY,EACpB,WAAW,GAAE,MAAgB,GAC5B,OAAO,CAmBT"}
@@ -0,0 +1,35 @@
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
+ }
@@ -13,3 +13,4 @@ export default class WorkerBody {
13
13
  */
14
14
  static postMessage(type: WorkerMessageType, payload: WorkerMessagePayload): void;
15
15
  }
16
+ //# sourceMappingURL=worker-body.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker-body.d.ts","sourceRoot":"","sources":["../../../src/lib/worker-farm/worker-body.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAoB,iBAAiB,EAAE,oBAAoB,EAAC,MAAM,aAAa,CAAC;AAK5F;;GAEG;AACH,MAAM,CAAC,OAAO,OAAO,UAAU;IAI7B,MAAM,KAAK,SAAS,CAAC,SAAS,EAAE,CAAC,IAAI,EAAE,iBAAiB,EAAE,OAAO,EAAE,oBAAoB,KAAK,GAAG,EAW9F;IAED,MAAM,CAAC,gBAAgB,CACrB,SAAS,EAAE,CAAC,IAAI,EAAE,iBAAiB,EAAE,OAAO,EAAE,oBAAoB,KAAK,GAAG;IAoB5E,MAAM,CAAC,mBAAmB,CACxB,SAAS,EAAE,CAAC,IAAI,EAAE,iBAAiB,EAAE,OAAO,EAAE,oBAAoB,KAAK,GAAG;IAQ5E;;;;OAIG;IACH,MAAM,CAAC,WAAW,CAAC,IAAI,EAAE,iBAAiB,EAAE,OAAO,EAAE,oBAAoB,GAAG,IAAI;CASjF"}
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const get_transfer_list_1 = require("../worker-utils/get-transfer-list");
4
+ const onMessageWrapperMap = new Map();
5
+ /**
6
+ * Type safe wrapper for worker code
7
+ */
8
+ class WorkerBody {
9
+ /*
10
+ * (type: WorkerMessageType, payload: WorkerMessagePayload) => any
11
+ */
12
+ static set onmessage(onMessage) {
13
+ // eslint-disable-next-line no-restricted-globals
14
+ self.onmessage = (message) => {
15
+ if (!isKnownMessage(message)) {
16
+ return;
17
+ }
18
+ // Confusingly the message itself also has a 'type' field which is always set to 'message'
19
+ const { type, payload } = message.data;
20
+ onMessage(type, payload);
21
+ };
22
+ }
23
+ static addEventListener(onMessage) {
24
+ let onMessageWrapper = onMessageWrapperMap.get(onMessage);
25
+ if (!onMessageWrapper) {
26
+ onMessageWrapper = (message) => {
27
+ if (!isKnownMessage(message)) {
28
+ return;
29
+ }
30
+ // Confusingly the message itself also has a 'type' field which is always set to 'message'
31
+ const { type, payload } = message.data;
32
+ onMessage(type, payload);
33
+ };
34
+ }
35
+ // eslint-disable-next-line no-restricted-globals
36
+ self.addEventListener('message', onMessageWrapper);
37
+ }
38
+ static removeEventListener(onMessage) {
39
+ const onMessageWrapper = onMessageWrapperMap.get(onMessage);
40
+ onMessageWrapperMap.delete(onMessage);
41
+ // eslint-disable-next-line no-restricted-globals
42
+ self.removeEventListener('message', onMessageWrapper);
43
+ }
44
+ /**
45
+ * Send a message from a worker to creating thread (main thread)
46
+ * @param type
47
+ * @param payload
48
+ */
49
+ static postMessage(type, payload) {
50
+ if (self) {
51
+ const data = { source: 'loaders.gl', type, payload };
52
+ const transferList = (0, get_transfer_list_1.getTransferList)(payload);
53
+ // eslint-disable-next-line no-restricted-globals
54
+ // @ts-ignore
55
+ self.postMessage(data, transferList);
56
+ }
57
+ }
58
+ }
59
+ exports.default = WorkerBody;
60
+ // Filter out noise messages sent to workers
61
+ function isKnownMessage(message) {
62
+ const { type, data } = message;
63
+ return (type === 'message' &&
64
+ data &&
65
+ typeof data.source === 'string' &&
66
+ data.source.startsWith('loaders.gl'));
67
+ }
@@ -52,3 +52,4 @@ export default class WorkerFarm {
52
52
  onDebug: (() => void) | undefined;
53
53
  };
54
54
  }
55
+ //# sourceMappingURL=worker-farm.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker-farm.d.ts","sourceRoot":"","sources":["../../../src/lib/worker-farm/worker-farm.ts"],"names":[],"mappings":"AAAA,OAAO,UAAU,MAAM,eAAe,CAAC;AAGvC;;GAEG;AACH,oBAAY,eAAe,GAAG;IAC5B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;CACtB,CAAC;AASF;;GAEG;AACH,MAAM,CAAC,OAAO,OAAO,UAAU;IAC7B,OAAO,CAAC,KAAK,CAAkB;IAC/B,OAAO,CAAC,WAAW,CAAiC;IAEpD,OAAO,CAAC,MAAM,CAAC,WAAW,CAAC,CAAa;IAExC,qCAAqC;IACrC,MAAM,CAAC,WAAW,IAAI,OAAO;IAI7B,2DAA2D;IAC3D,MAAM,CAAC,aAAa,CAAC,KAAK,GAAE,eAAoB,GAAG,UAAU;IAM7D,0DAA0D;IAC1D,OAAO;IAOP;;;OAGG;IACH,OAAO,IAAI,IAAI;IAMf;;;OAGG;IACH,QAAQ,CAAC,KAAK,EAAE,eAAe,GAAG,IAAI;IAQtC;;;;;;;;OAQG;IACH,aAAa,CAAC,OAAO,EAAE;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,CAAA;KAAC,GAAG,UAAU;IAejF,mBAAmB;;;;;;CAQpB"}
@@ -0,0 +1,88 @@
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
+ onDebug: () => { },
12
+ reuseWorkers: true
13
+ };
14
+ /**
15
+ * Process multiple jobs with a "farm" of different workers in worker pools.
16
+ */
17
+ class WorkerFarm {
18
+ /** get global instance with WorkerFarm.getWorkerFarm() */
19
+ constructor(props) {
20
+ this.workerPools = new Map();
21
+ this.props = { ...DEFAULT_PROPS };
22
+ this.setProps(props);
23
+ /** @type Map<string, WorkerPool>} */
24
+ this.workerPools = new Map();
25
+ }
26
+ /** Check if Workers are supported */
27
+ static isSupported() {
28
+ return worker_thread_1.default.isSupported();
29
+ }
30
+ /** Get the singleton instance of the global worker farm */
31
+ static getWorkerFarm(props = {}) {
32
+ WorkerFarm._workerFarm = WorkerFarm._workerFarm || new WorkerFarm({});
33
+ WorkerFarm._workerFarm.setProps(props);
34
+ return WorkerFarm._workerFarm;
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
+ }
45
+ /**
46
+ * Set props used when initializing worker pools
47
+ * @param props
48
+ */
49
+ setProps(props) {
50
+ this.props = { ...this.props, ...props };
51
+ // Update worker pool props
52
+ for (const workerPool of this.workerPools.values()) {
53
+ workerPool.setProps(this._getWorkerPoolProps());
54
+ }
55
+ }
56
+ /**
57
+ * Returns a worker pool for the specified worker
58
+ * @param options - only used first time for a specific worker name
59
+ * @param options.name - the name of the worker - used to identify worker pool
60
+ * @param options.url -
61
+ * @param options.source -
62
+ * @example
63
+ * const job = WorkerFarm.getWorkerFarm().getWorkerPool({name, url}).startJob(...);
64
+ */
65
+ getWorkerPool(options) {
66
+ const { name, source, url } = options;
67
+ let workerPool = this.workerPools.get(name);
68
+ if (!workerPool) {
69
+ workerPool = new worker_pool_1.default({
70
+ name,
71
+ source,
72
+ url
73
+ });
74
+ workerPool.setProps(this._getWorkerPoolProps());
75
+ this.workerPools.set(name, workerPool);
76
+ }
77
+ return workerPool;
78
+ }
79
+ _getWorkerPoolProps() {
80
+ return {
81
+ maxConcurrency: this.props.maxConcurrency,
82
+ maxMobileConcurrency: this.props.maxMobileConcurrency,
83
+ reuseWorkers: this.props.reuseWorkers,
84
+ onDebug: this.props.onDebug
85
+ };
86
+ }
87
+ }
88
+ exports.default = WorkerFarm;
@@ -24,5 +24,6 @@ export default class WorkerJob {
24
24
  /**
25
25
  * Call to reject the `result` Promise with the supplied error
26
26
  */
27
- error(error: any): void;
27
+ error(error: Error): void;
28
28
  }
29
+ //# sourceMappingURL=worker-job.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker-job.d.ts","sourceRoot":"","sources":["../../../src/lib/worker-farm/worker-job.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,iBAAiB,EAAE,oBAAoB,EAAC,MAAM,aAAa,CAAC;AACzE,OAAO,YAAY,MAAM,iBAAiB,CAAC;AAG3C;;GAEG;AACH,MAAM,CAAC,OAAO,OAAO,SAAS;IAC5B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,YAAY,EAAE,YAAY,CAAC;IACpC,SAAS,EAAE,OAAO,CAAC;IACnB,6CAA6C;IAC7C,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC;IAE9B,OAAO,CAAC,QAAQ,CAAuB;IACvC,OAAO,CAAC,OAAO,CAAyB;gBAE5B,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,YAAY;IAYvD;;;OAGG;IACH,WAAW,CAAC,IAAI,EAAE,iBAAiB,EAAE,OAAO,EAAE,oBAAoB,GAAG,IAAI;IAQzE;;OAEG;IACH,IAAI,CAAC,KAAK,EAAE,GAAG,GAAG,IAAI;IAMtB;;OAEG;IACH,KAAK,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI;CAK1B"}
@@ -0,0 +1,47 @@
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.name = jobName;
10
+ this.workerThread = workerThread;
11
+ this.isRunning = true;
12
+ this._resolve = () => { };
13
+ this._reject = () => { };
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;
@@ -72,3 +72,4 @@ export default class WorkerPool {
72
72
  _getMaxConcurrency(): number;
73
73
  }
74
74
  export {};
75
+ //# sourceMappingURL=worker-pool.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker-pool.d.ts","sourceRoot":"","sources":["../../../src/lib/worker-farm/worker-pool.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,iBAAiB,EAAE,oBAAoB,EAAC,MAAM,aAAa,CAAC;AAEzE,OAAO,YAAY,MAAM,iBAAiB,CAAC;AAC3C,OAAO,SAAS,MAAM,cAAc,CAAC;AAErC,6CAA6C;AAC7C,aAAK,iBAAiB,GAAG;IACvB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,MAAM,CAAC;IAChB,YAAY,EAAE,YAAY,CAAC;CAC5B,CAAC;AAEF,4BAA4B;AAC5B,oBAAY,eAAe,GAAG;IAC5B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE,iBAAiB,KAAK,GAAG,CAAC;IAC9C,YAAY,CAAC,EAAE,OAAO,CAAC;CACxB,CAAC;AAEF,2BAA2B;AAC3B,aAAK,SAAS,GAAG,CAAC,GAAG,EAAE,SAAS,EAAE,IAAI,EAAE,iBAAiB,EAAE,OAAO,EAAE,oBAAoB,KAAK,IAAI,CAAC;AAClG,aAAK,OAAO,GAAG,CAAC,GAAG,EAAE,SAAS,EAAE,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;AAStD;;GAEG;AACH,MAAM,CAAC,OAAO,OAAO,UAAU;IAC7B,IAAI,EAAE,MAAM,CAAa;IACzB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,cAAc,EAAE,MAAM,CAAK;IAC3B,oBAAoB,EAAE,MAAM,CAAK;IACjC,OAAO,EAAE,CAAC,OAAO,EAAE,iBAAiB,KAAK,GAAG,CAAY;IACxD,YAAY,EAAE,OAAO,CAAQ;IAE7B,OAAO,CAAC,KAAK,CAAuB;IACpC,OAAO,CAAC,QAAQ,CAAmB;IACnC,OAAO,CAAC,SAAS,CAAsB;IACvC,OAAO,CAAC,KAAK,CAAK;IAClB,OAAO,CAAC,WAAW,CAAS;IAE5B;;;OAGG;gBACS,KAAK,EAAE,eAAe;IAMlC;;;OAGG;IACH,OAAO,IAAI,IAAI;IAMf,QAAQ,CAAC,KAAK,EAAE,eAAe;IAoBzB,QAAQ,CACZ,IAAI,EAAE,MAAM,EACZ,SAAS,GAAE,SAA+C,EAC1D,OAAO,GAAE,OAA0C,GAClD,OAAO,CAAC,SAAS,CAAC;IAarB;;;OAGG;IACG,eAAe,IAAI,OAAO,CAAC,IAAI,CAAC;IAyCtC;;;;;;;OAOG;IACH,mBAAmB,CAAC,MAAM,EAAE,YAAY;IAgBxC;;OAEG;IACH,mBAAmB,IAAI,YAAY,GAAG,IAAI;IAiB1C,kBAAkB;CAGnB"}
@@ -0,0 +1,151 @@
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 globals_1 = require("../env-utils/globals");
7
+ const worker_thread_1 = __importDefault(require("./worker-thread"));
8
+ const worker_job_1 = __importDefault(require("./worker-job"));
9
+ /**
10
+ * Process multiple data messages with small pool of identical workers
11
+ */
12
+ class WorkerPool {
13
+ /**
14
+ * @param processor - worker function
15
+ * @param maxConcurrency - max count of workers
16
+ */
17
+ constructor(props) {
18
+ this.name = 'unnamed';
19
+ this.maxConcurrency = 1;
20
+ this.maxMobileConcurrency = 1;
21
+ this.onDebug = () => { };
22
+ this.reuseWorkers = true;
23
+ this.props = {};
24
+ this.jobQueue = [];
25
+ this.idleQueue = [];
26
+ this.count = 0;
27
+ this.isDestroyed = false;
28
+ this.source = props.source;
29
+ this.url = props.url;
30
+ this.setProps(props);
31
+ }
32
+ /**
33
+ * Terminates all workers in the pool
34
+ * @note Can free up significant memory
35
+ */
36
+ destroy() {
37
+ // Destroy idle workers, active Workers will be destroyed on completion
38
+ this.idleQueue.forEach((worker) => worker.destroy());
39
+ this.isDestroyed = true;
40
+ }
41
+ setProps(props) {
42
+ this.props = { ...this.props, ...props };
43
+ if (props.name !== undefined) {
44
+ this.name = props.name;
45
+ }
46
+ if (props.maxConcurrency !== undefined) {
47
+ this.maxConcurrency = props.maxConcurrency;
48
+ }
49
+ if (props.maxMobileConcurrency !== undefined) {
50
+ this.maxMobileConcurrency = props.maxMobileConcurrency;
51
+ }
52
+ if (props.reuseWorkers !== undefined) {
53
+ this.reuseWorkers = props.reuseWorkers;
54
+ }
55
+ if (props.onDebug !== undefined) {
56
+ this.onDebug = props.onDebug;
57
+ }
58
+ }
59
+ async startJob(name, onMessage = (job, type, data) => job.done(data), onError = (job, error) => job.error(error)) {
60
+ // Promise resolves when thread starts working on this job
61
+ const startPromise = new Promise((onStart) => {
62
+ // Promise resolves when thread completes or fails working on this job
63
+ this.jobQueue.push({ name, onMessage, onError, onStart });
64
+ return this;
65
+ });
66
+ this._startQueuedJob(); // eslint-disable-line @typescript-eslint/no-floating-promises
67
+ return await startPromise;
68
+ }
69
+ // PRIVATE
70
+ /**
71
+ * Starts first queued job if worker is available or can be created
72
+ * Called when job is started and whenever a worker returns to the idleQueue
73
+ */
74
+ async _startQueuedJob() {
75
+ if (!this.jobQueue.length) {
76
+ return;
77
+ }
78
+ const workerThread = this._getAvailableWorker();
79
+ if (!workerThread) {
80
+ return;
81
+ }
82
+ // We have a worker, dequeue and start the job
83
+ const queuedJob = this.jobQueue.shift();
84
+ if (queuedJob) {
85
+ // Emit a debug event
86
+ // @ts-ignore
87
+ this.onDebug({
88
+ message: 'Starting job',
89
+ name: queuedJob.name,
90
+ workerThread,
91
+ backlog: this.jobQueue.length
92
+ });
93
+ // Create a worker job to let the app access thread and manage job completion
94
+ const job = new worker_job_1.default(queuedJob.name, workerThread);
95
+ // Set the worker thread's message handlers
96
+ workerThread.onMessage = (data) => queuedJob.onMessage(job, data.type, data.payload);
97
+ workerThread.onError = (error) => queuedJob.onError(job, error);
98
+ // Resolve the start promise so that the app can start sending messages to worker
99
+ queuedJob.onStart(job);
100
+ // Wait for the app to signal that the job is complete, then return worker to queue
101
+ try {
102
+ await job.result;
103
+ }
104
+ finally {
105
+ this.returnWorkerToQueue(workerThread);
106
+ }
107
+ }
108
+ }
109
+ /**
110
+ * Returns a worker to the idle queue
111
+ * Destroys the worker if
112
+ * - pool is destroyed
113
+ * - if this pool doesn't reuse workers
114
+ * - if maxConcurrency has been lowered
115
+ * @param worker
116
+ */
117
+ returnWorkerToQueue(worker) {
118
+ const shouldDestroyWorker = this.isDestroyed || !this.reuseWorkers || this.count > this._getMaxConcurrency();
119
+ if (shouldDestroyWorker) {
120
+ worker.destroy();
121
+ this.count--;
122
+ }
123
+ else {
124
+ this.idleQueue.push(worker);
125
+ }
126
+ if (!this.isDestroyed) {
127
+ this._startQueuedJob(); // eslint-disable-line @typescript-eslint/no-floating-promises
128
+ }
129
+ }
130
+ /**
131
+ * Returns idle worker or creates new worker if maxConcurrency has not been reached
132
+ */
133
+ _getAvailableWorker() {
134
+ // If a worker has completed and returned to the queue, it can be used
135
+ if (this.idleQueue.length > 0) {
136
+ return this.idleQueue.shift() || null;
137
+ }
138
+ // Create fresh worker if we haven't yet created the max amount of worker threads for this worker source
139
+ if (this.count < this._getMaxConcurrency()) {
140
+ this.count++;
141
+ const name = `${this.name.toLowerCase()} (#${this.count} of ${this.maxConcurrency})`;
142
+ return new worker_thread_1.default({ name, source: this.source, url: this.url });
143
+ }
144
+ // No worker available, have to wait
145
+ return null;
146
+ }
147
+ _getMaxConcurrency() {
148
+ return globals_1.isMobile ? this.maxMobileConcurrency : this.maxConcurrency;
149
+ }
150
+ }
151
+ exports.default = WorkerPool;
@@ -33,9 +33,10 @@ export default class WorkerThread {
33
33
  * Generate a standard Error from an ErrorEvent
34
34
  * @param {ErrorEvent} event
35
35
  */
36
- _getErrorFromErrorEvent(event: any): Error;
36
+ _getErrorFromErrorEvent(event: ErrorEvent): Error;
37
37
  /**
38
38
  * Creates a worker thread on the browser
39
39
  */
40
40
  _createBrowserWorker(): Worker;
41
41
  }
42
+ //# sourceMappingURL=worker-thread.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker-thread.d.ts","sourceRoot":"","sources":["../../../src/lib/worker-farm/worker-thread.ts"],"names":[],"mappings":"AAMA,oBAAY,iBAAiB,GAAG;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,GAAG,CAAC,EAAE,MAAM,CAAC;CACd,CAAC;AAEF;;GAEG;AACH,MAAM,CAAC,OAAO,OAAO,YAAY;IAC/B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;IACpC,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,CAAC;IACjC,UAAU,EAAE,OAAO,CAAS;IAC5B,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,CAAC,OAAO,EAAE,GAAG,KAAK,IAAI,CAAC;IAClC,OAAO,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IAEhC,OAAO,CAAC,YAAY,CAAc;IAElC,MAAM,CAAC,WAAW,IAAI,OAAO;gBAIjB,KAAK,EAAE,iBAAiB;IAYpC;;;OAGG;IACH,OAAO,IAAI,IAAI;IAQf,IAAI,SAAS,YAEZ;IAED;;;;OAIG;IACH,WAAW,CAAC,IAAI,EAAE,GAAG,EAAE,YAAY,CAAC,EAAE,GAAG,EAAE,GAAG,IAAI;IAQlD;;;OAGG;IACH,uBAAuB,CAAC,KAAK,EAAE,UAAU,GAAG,KAAK;IAiBjD;;OAEG;IACH,oBAAoB;CAqBrB"}
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const assert_1 = require("../env-utils/assert");
4
+ const get_loadable_worker_url_1 = require("../worker-utils/get-loadable-worker-url");
5
+ const get_transfer_list_1 = require("../worker-utils/get-transfer-list");
6
+ const NOOP = () => { };
7
+ /**
8
+ * Represents one worker thread
9
+ */
10
+ class WorkerThread {
11
+ constructor(props) {
12
+ this.terminated = false;
13
+ this._loadableURL = '';
14
+ const { name, source, url } = props;
15
+ (0, assert_1.assert)(source || url); // Either source or url must be defined
16
+ this.name = name;
17
+ this.source = source;
18
+ this.url = url;
19
+ this.onMessage = NOOP;
20
+ this.onError = (error) => console.log(error); // eslint-disable-line
21
+ this.worker = this._createBrowserWorker();
22
+ }
23
+ static isSupported() {
24
+ return typeof Worker !== 'undefined';
25
+ }
26
+ /**
27
+ * Terminate this worker thread
28
+ * @note Can free up significant memory
29
+ */
30
+ destroy() {
31
+ this.onMessage = NOOP;
32
+ this.onError = NOOP;
33
+ // @ts-ignore
34
+ this.worker.terminate();
35
+ this.terminated = true;
36
+ }
37
+ get isRunning() {
38
+ return Boolean(this.onMessage);
39
+ }
40
+ /**
41
+ * Send a message to this worker thread
42
+ * @param data any data structure, ideally consisting mostly of transferrable objects
43
+ * @param transferList If not supplied, calculated automatically by traversing data
44
+ */
45
+ postMessage(data, transferList) {
46
+ transferList = transferList || (0, get_transfer_list_1.getTransferList)(data);
47
+ // @ts-ignore
48
+ this.worker.postMessage(data, transferList);
49
+ }
50
+ // PRIVATE
51
+ /**
52
+ * Generate a standard Error from an ErrorEvent
53
+ * @param {ErrorEvent} event
54
+ */
55
+ _getErrorFromErrorEvent(event) {
56
+ // Note Error object does not have the expected fields if loading failed completely
57
+ // https://developer.mozilla.org/en-US/docs/Web/API/Worker#Event_handlers
58
+ // https://developer.mozilla.org/en-US/docs/Web/API/ErrorEvent
59
+ let message = 'Failed to load ';
60
+ message += `worker ${this.name} from ${this.url}. `;
61
+ if (event.message) {
62
+ message += `${event.message} in `;
63
+ }
64
+ // const hasFilename = event.filename && !event.filename.startsWith('blob:');
65
+ // message += hasFilename ? event.filename : this.source.slice(0, 100);
66
+ if (event.lineno) {
67
+ message += `:${event.lineno}:${event.colno}`;
68
+ }
69
+ return new Error(message);
70
+ }
71
+ /**
72
+ * Creates a worker thread on the browser
73
+ */
74
+ _createBrowserWorker() {
75
+ this._loadableURL = (0, get_loadable_worker_url_1.getLoadableWorkerURL)({ source: this.source, url: this.url });
76
+ const worker = new Worker(this._loadableURL, { name: this.name });
77
+ worker.onmessage = (event) => {
78
+ if (!event.data) {
79
+ this.onError(new Error('No data received'));
80
+ }
81
+ else {
82
+ this.onMessage(event.data);
83
+ }
84
+ };
85
+ // This callback represents an uncaught exception in the worker thread
86
+ worker.onerror = (error) => {
87
+ this.onError(this._getErrorFromErrorEvent(error));
88
+ this.terminated = true;
89
+ };
90
+ // TODO - not clear when this would be called, for now just log in case it happens
91
+ worker.onmessageerror = (event) => console.error(event); // eslint-disable-line
92
+ return worker;
93
+ }
94
+ }
95
+ exports.default = WorkerThread;
@@ -11,3 +11,4 @@ export declare function getLoadableWorkerURL(props: {
11
11
  source?: string;
12
12
  url?: string;
13
13
  }): any;
14
+ //# sourceMappingURL=get-loadable-worker-url.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"get-loadable-worker-url.d.ts","sourceRoot":"","sources":["../../../src/lib/worker-utils/get-loadable-worker-url.ts"],"names":[],"mappings":"AAIA;;;;;;;;GAQG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE;IAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,GAAG,CAAC,EAAE,MAAM,CAAA;CAAC,OAmB1E"}