How to use worker method in Jest

Best JavaScript code snippet using jest

Run Jest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

WorkerManager.js

Source: WorkerManager.js Github

copy
1/*
2 * Copyright (C) 2011 Google Inc. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
6 * met:
7 *
8 *     * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *     * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
13 * distribution.
14 *     * Neither the name of Google Inc. nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30
31/**
32 * @constructor
33 * @extends {WebInspector.Object}
34 */
35WebInspector.WorkerManager = function()
36{
37    this._workerIdToWindow = {};
38    InspectorBackend.registerWorkerDispatcher(new WebInspector.DedicatedWorkerMessageForwarder(this));
39}
40
41WebInspector.WorkerManager.isWorkerFrontend = function()
42{
43    return !!WebInspector.queryParamsObject["dedicatedWorkerId"] ||
44           !!WebInspector.queryParamsObject["isSharedWorker"];
45}
46
47WebInspector.WorkerManager.loaded = function()
48{
49    var workerId = WebInspector.queryParamsObject["dedicatedWorkerId"];
50    if (workerId)
51        WebInspector.WorkerManager._initializeDedicatedWorkerFrontend(workerId);
52    else
53        WebInspector.workerManager = new WebInspector.WorkerManager();
54
55    if (WebInspector.WorkerManager.isWorkerFrontend())
56        WebInspector.WorkerManager._calculateWorkerInspectorTitle();
57}
58
59WebInspector.WorkerManager._initializeDedicatedWorkerFrontend = function(workerId)
60{
61    function receiveMessage(event)
62    {
63        var message = event.data;
64        InspectorBackend.dispatch(message);
65    }
66    window.addEventListener("message", receiveMessage, true);
67
68
69    InspectorBackend.sendMessageObjectToBackend = function(message)
70    {
71        window.opener.postMessage({workerId: workerId, command: "sendMessageToBackend", message: message}, "*");
72    }
73
74    InspectorFrontendHost.loaded = function()
75    {
76        window.opener.postMessage({workerId: workerId, command: "loaded"}, "*");
77    }
78}
79
80WebInspector.WorkerManager._calculateWorkerInspectorTitle = function()
81{
82    var expression = "location.href";
83    if (WebInspector.queryParamsObject["isSharedWorker"])
84        expression += " + (this.name ? ' (' + this.name + ')' : '')";
85    RuntimeAgent.evaluate.invoke({expression:expression, doNotPauseOnExceptions:true, returnByValue: true}, evalCallback.bind(this));
86    function evalCallback(error, result, wasThrown)
87    {
88        if (error || wasThrown) {
89            console.error(error);
90            return;
91        }
92        InspectorFrontendHost.inspectedURLChanged(result.value);
93    }
94}
95
96WebInspector.WorkerManager.Events = {
97    WorkerAdded: "worker-added",
98    WorkerRemoved: "worker-removed",
99    WorkersCleared: "workers-cleared",
100    WorkerInspectorClosed: "worker-inspector-closed"
101}
102
103WebInspector.WorkerManager.prototype = {
104    _workerCreated: function(workerId, url, inspectorConnected)
105     {
106        if (inspectorConnected)
107            this._openInspectorWindow(workerId);
108        this.dispatchEventToListeners(WebInspector.WorkerManager.Events.WorkerAdded, {workerId: workerId, url: url, inspectorConnected: inspectorConnected});
109     },
110
111    _workerTerminated: function(workerId)
112     {
113        this.closeWorkerInspector(workerId);
114        this.dispatchEventToListeners(WebInspector.WorkerManager.Events.WorkerRemoved, workerId);
115     },
116
117    _sendMessageToWorkerInspector: function(workerId, message)
118    {
119        var workerInspectorWindow = this._workerIdToWindow[workerId];
120        if (workerInspectorWindow)
121            workerInspectorWindow.postMessage(message, "*");
122    },
123
124    openWorkerInspector: function(workerId)
125    {
126        this._openInspectorWindow(workerId);
127        WorkerAgent.connectToWorker(workerId);
128    },
129
130    _openInspectorWindow: function(workerId)
131    {
132        var url = window.location.href + "&dedicatedWorkerId=" + workerId;
133        url = url.replace("docked=true&", "");
134        // Set location=0 just to make sure the front-end will be opened in a separate window, not in new tab.
135        var workerInspectorWindow = window.open(url, undefined, "location=0");
136        this._workerIdToWindow[workerId] = workerInspectorWindow;
137        workerInspectorWindow.addEventListener("beforeunload", this._workerInspectorClosing.bind(this, workerId), true);
138
139        // Listen to beforeunload in detached state and to the InspectorClosing event in case of attached inspector.
140        window.addEventListener("beforeunload", this._pageInspectorClosing.bind(this), true);
141        WebInspector.notifications.addEventListener(WebInspector.Events.InspectorClosing, this._pageInspectorClosing, this);
142    },
143
144    closeWorkerInspector: function(workerId)
145    {
146        var workerInspectorWindow = this._workerIdToWindow[workerId];
147        if (workerInspectorWindow)
148            workerInspectorWindow.close();
149    },
150
151    reset: function()
152    {
153        for (var workerId in this._workerIdToWindow)
154            this.closeWorkerInspector(workerId);
155        this.dispatchEventToListeners(WebInspector.WorkerManager.Events.WorkersCleared);
156    },
157
158    _pageInspectorClosing: function()
159    {
160        this._ignoreWorkerInspectorClosing = true;
161        for (var workerId in this._workerIdToWindow) {
162            this._workerIdToWindow[workerId].close();
163            WorkerAgent.disconnectFromWorker(parseInt(workerId, 10));
164        }
165    },
166
167    _workerInspectorClosing: function(workerId, event)
168    {
169        if (this._ignoreWorkerInspectorClosing)
170            return;
171        delete this._workerIdToWindow[workerId];
172        WorkerAgent.disconnectFromWorker(workerId);
173        this.dispatchEventToListeners(WebInspector.WorkerManager.Events.WorkerInspectorClosed, workerId);
174    }
175}
176
177WebInspector.WorkerManager.prototype.__proto__ = WebInspector.Object.prototype;
178
179/**
180 * @constructor
181 * @implements {WorkerAgent.Dispatcher}
182 */
183WebInspector.DedicatedWorkerMessageForwarder = function(workerManager)
184{
185    this._workerManager = workerManager;
186    window.addEventListener("message", this._receiveMessage.bind(this), true);
187}
188
189WebInspector.DedicatedWorkerMessageForwarder.prototype = {
190    _receiveMessage: function(event)
191    {
192        var workerId = event.data["workerId"];
193        workerId = parseInt(workerId, 10);
194        var command = event.data.command;
195        var message = event.data.message;
196
197        if (command == "sendMessageToBackend")
198            WorkerAgent.sendMessageToWorker(workerId, message);
199    },
200
201    workerCreated: function(workerId, url, inspectorConnected)
202    {
203        this._workerManager._workerCreated(workerId, url, inspectorConnected);
204    },
205
206    workerTerminated: function(workerId)
207    {
208        this._workerManager._workerTerminated(workerId);
209    },
210
211    dispatchMessageFromWorker: function(workerId, message)
212    {
213        this._workerManager._sendMessageToWorkerInspector(workerId, message);
214    }
215}
216
Full Screen

workerpool.js

Source: workerpool.js Github

copy
1// Copyright 2007 The Closure Library Authors. All Rights Reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS-IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15/**
16 * @fileoverview This file implements a wrapper around the Gears WorkerPool
17 * with some extra features.
18 *
19 * @author arv@google.com (Erik Arvidsson)
20 */
21
22goog.provide('goog.gears.WorkerPool');
23goog.provide('goog.gears.WorkerPool.Event');
24goog.provide('goog.gears.WorkerPool.EventType');
25
26goog.require('goog.events.Event');
27goog.require('goog.events.EventTarget');
28goog.require('goog.gears');
29goog.require('goog.gears.Worker');
30
31
32
33/**
34 * This class implements a wrapper around the Gears Worker Pool.
35 *
36 * @constructor
37 * @extends {goog.events.EventTarget}
38 */
39goog.gears.WorkerPool = function() {
40  goog.events.EventTarget.call(this);
41
42  /**
43   * Map from thread id to worker object
44   * @type {Object}
45   * @private
46   */
47  this.workers_ = {};
48
49  // If we are in a worker thread we get the global google.gears.workerPool,
50  // otherwise we create a new Gears WorkerPool using the factory
51  var workerPool = /** @type {GearsWorkerPool} */
52      (goog.getObjectByName('google.gears.workerPool'));
53  if (workerPool) {
54    this.workerPool_ = workerPool;
55  } else {
56    // use a protected method to let the sub class override
57    this.workerPool_ = this.getGearsWorkerPool();
58  }
59
60  this.workerPool_.onmessage = goog.bind(this.handleMessage_, this);
61};
62goog.inherits(goog.gears.WorkerPool, goog.events.EventTarget);
63
64
65/**
66 * Enum for event types fired by the WorkerPool.
67 * @enum {string}
68 */
69goog.gears.WorkerPool.EventType = {
70  UNKNOWN_WORKER: 'uknown_worker'
71};
72
73
74/**
75 * The Gears WorkerPool object.
76 * @type {GearsWorkerPool}
77 * @private
78 */
79goog.gears.WorkerPool.prototype.workerPool_ = null;
80
81
82/**
83 * @return {GearsWorkerPool} A Gears WorkerPool object.
84 * @protected
85 */
86goog.gears.WorkerPool.prototype.getGearsWorkerPool = function() {
87  var factory = goog.gears.getFactory();
88  return factory.create('beta.workerpool');
89};
90
91
92/**
93 * Sets a last-chance error handler for a worker pool.
94 * WARNING: This will only succeed from inside a worker thread. In main thread,
95 * use window.onerror handler.
96 * @param {function(!GearsErrorObject):boolean} fn An error handler function
97 *     that gets passed an error object with message and line number attributes.
98 *     Returns whether the error was handled. If true stops propagation.
99 * @param {Object=} opt_handler This object for the function.
100 */
101goog.gears.WorkerPool.prototype.setErrorHandler = function(fn, opt_handler) {
102  this.workerPool_.onerror = goog.bind(fn, opt_handler);
103};
104
105
106/**
107 * Creates a new worker.
108 * @param {string} code  The code to execute inside the worker.
109 * @return {goog.gears.Worker} The worker that was just created.
110 */
111goog.gears.WorkerPool.prototype.createWorker = function(code) {
112  var workerId = this.workerPool_.createWorker(code);
113  var worker = new goog.gears.Worker(this, workerId);
114  this.registerWorker(worker);
115  return worker;
116};
117
118
119/**
120 * Creates a new worker from a URL.
121 * @param {string} url  URL from which to get the code to execute inside the
122 *     worker.
123 * @return {goog.gears.Worker} The worker that was just created.
124 */
125goog.gears.WorkerPool.prototype.createWorkerFromUrl = function(url) {
126  var workerId = this.workerPool_.createWorkerFromUrl(url);
127  var worker = new goog.gears.Worker(this, workerId);
128  this.registerWorker(worker);
129  return worker;
130};
131
132
133/**
134 * Allows the worker who calls this to be used cross origin.
135 */
136goog.gears.WorkerPool.prototype.allowCrossOrigin = function() {
137  this.workerPool_.allowCrossOrigin();
138};
139
140
141/**
142 * Sends a message to a given worker.
143 * @param {*} message The message to send to the worker.
144 * @param {goog.gears.Worker} worker The worker to send the message to.
145 */
146goog.gears.WorkerPool.prototype.sendMessage = function(message, worker) {
147  this.workerPool_.sendMessage(message, worker.getId());
148};
149
150
151/**
152 * Callback when this worker recieves a message.
153 * @param {string} message  The message that was sent.
154 * @param {number} senderId  The ID of the worker that sent the message.
155 * @param {GearsMessageObject} messageObject An object containing all
156 *     information about the message.
157 * @private
158 */
159goog.gears.WorkerPool.prototype.handleMessage_ = function(message,
160                                                          senderId,
161                                                          messageObject) {
162  if (!this.isDisposed()) {
163    var workers = this.workers_;
164    if (!workers[senderId]) {
165      // If the worker is unknown, dispatch an event giving users of the class
166      // the change to register the worker.
167      this.dispatchEvent(new goog.gears.WorkerPool.Event(
168          goog.gears.WorkerPool.EventType.UNKNOWN_WORKER,
169          senderId,
170          messageObject));
171    }
172
173    var worker = workers[senderId];
174    if (worker) {
175      worker.handleMessage(messageObject);
176    }
177  }
178};
179
180
181/**
182 * Registers a worker object.
183 * @param {goog.gears.Worker} worker  The worker to register.
184 */
185goog.gears.WorkerPool.prototype.registerWorker = function(worker) {
186  this.workers_[worker.getId()] = worker;
187};
188
189
190/**
191 * Unregisters a worker object.
192 * @param {goog.gears.Worker} worker  The worker to unregister.
193 */
194goog.gears.WorkerPool.prototype.unregisterWorker = function(worker) {
195  delete this.workers_[worker.getId()];
196};
197
198
199/** @override */
200goog.gears.WorkerPool.prototype.disposeInternal = function() {
201  goog.gears.WorkerPool.superClass_.disposeInternal.call(this);
202  this.workerPool_ = null;
203  delete this.workers_;
204};
205
206
207
208/**
209 * Event used when the workerpool recieves a message
210 * @param {string} type  The type of event.
211 * @param {number} senderId  The id of the sender of the message.
212 * @param {GearsMessageObject} messageObject  The message object.
213 *
214 * @constructor
215 * @extends {goog.events.Event}
216 */
217goog.gears.WorkerPool.Event = function(
218    type, senderId, messageObject) {
219  goog.events.Event.call(this, type);
220
221  /**
222   * The id of the sender of the message.
223   * @type {number}
224   */
225  this.senderId = senderId;
226
227  /**
228   * The message sent from the worker. This is the same as the
229   * messageObject.body field and is here for convenience.
230   * @type {*}
231   */
232  this.message = messageObject.body;
233
234  /**
235   * The object containing all information about the message.
236   * @type {GearsMessageObject}
237   */
238  this.messageObject = messageObject;
239};
240goog.inherits(goog.gears.WorkerPool.Event, goog.events.Event);
241
Full Screen

appverse-performance.js

Source: appverse-performance.js Github

copy
1(function() {
2    'use strict';
3
4    /**
5     * @ngdoc module
6     * @name appverse.performance
7     *
8     * @description
9     * The AppPerformance provides services to handle usage of several performance elements:
10     * 1. Webworkers. Multithreaded-parallelized execution of tasks separated of the main JavaScript thread.
11     * 2. High Performance UI directives support.
12     *
13     * @requires appverse.configuration
14     */
15    run.$inject = ["$log"];
16    angular.module('appverse.performance', ['appverse.configuration'])
17        .run(run);
18
19    function run ($log) {
20        $log.info('appverse.performance run');
21    }
22
23})();
24(function () {
25    'use strict';
26
27    angular.module('appverse.performance')
28
29
30    /**
31    * @ngdoc directive
32    * @name webworker
33    * @module appverse.performance
34    * @restrict E
35    *
36    * @description
37    * Establishes comm with messages to a selected web worker.
38    * Allows send messages to the worker and receive results from.
39    * Messages from the worker are displayed in a div.
40    *
41    * @example
42    <example module="appverse.performance">
43    <file name="index.html">
44    <p>Web Worker test</p>
45    <webworker  id="101" message="Hans Walter" template=""/>
46    </file>
47    </example>
48    *
49    * @param {string} id Id of the pre-configured worker or path to the worker's file
50    * @param {string} message Message to be passed to the worker.
51    *
52    * @requires  https://docs.angularjs.org/api/ngMock/service/$log $log
53    * @requires  WebWorkerFactory
54    * @requires  PERFORMANCE_CONFIG
55    */
56    .directive('webworker', ['$log', 'WebWorkerFactory', 'PERFORMANCE_CONFIG',
57        function ($log, WebWorkerFactory, PERFORMANCE_CONFIG) {
58
59            return {
60                restrict: 'E', //E = element, A = attribute, C = class, M = comment
61                scope: {
62                    //(required) set the worker id in configuration or the complete path
63                    //if it is not included in config.
64                    workerid: '@',
65                    //(required) set the message to be passed to the worker
66                    message: '@',
67                    //(optional) custom template to render the received message from the worker
68                    template: '@'
69                },
70                priority: 1000,
71                terminal: true,
72                compile: function () {},
73                link: function postLink(scope, element, attrs) {
74                    var workerid = attrs.id;
75                    var template = attrs.template;
76
77                    scope.$watch(function () {
78                        return WebWorkerFactory._resultMessage;
79                    }, function (newVal) {
80                        $log.debug('Cache watch {' + name + '}:', newVal);
81                        scope.messageFromWorker = WebWorkerFactory._resultMessage;
82                    });
83
84                    scope.$watch('message', function (value) {
85                        init(value); // set defaults
86                        compileTemplate(); // gets the template and compile the desired layout
87
88                    });
89
90                    /**
91                     * @function
92                     * @description
93                     * Set defaults into the scope object
94                     */
95                    function init(message) {
96                        scope.workerid = workerid;
97                        scope.template = template || PERFORMANCE_CONFIG.webworker_Message_template;
98                        initWorker(scope.workerid, message);
99                    }
100
101                    /**
102                     * @function
103                     * @description
104                     * Gets the message from the worker.
105                     */
106                    function initWorker(workerid, message) {
107                        WebWorkerFactory.runTask(workerid, message);
108                        var messageFromWorker = WebWorkerFactory._resultMessage;
109
110                        if (messageFromWorker) {
111                            scope.messageFromWorker = messageFromWorker;
112                        }
113                    }
114
115                    /**
116                     * @function
117                     * @description
118                     * Gets the template and compile the desired layout.
119                     * Based on $compile, it compiles a piece of HTML string or DOM into the retrieved
120                     * template and produces a template function, which can then be used to link scope and
121                     * the template together.
122                     */
123                    function compileTemplate($http, $templateCache, $compile) {
124                        $http.get(scope.template, {
125                                //This allows you can get the template again by consuming the
126                                //$templateCache service directly.
127                                cache: $templateCache
128                            })
129                            .success(function (html) {
130                                element.html(html);
131                                $compile(element.contents())(scope);
132                            });
133                    }
134                }
135            };
136        }]);
137
138})();
139
140(function() {
141    'use strict';
142
143    WebWorkerPoolFactory.$inject = ["$log", "$q", "PERFORMANCE_CONFIG"];
144    angular.module('appverse.performance')
145        .factory('WebWorkerPoolFactory', WebWorkerPoolFactory);
146
147
148    /**
149     * @ngdoc service
150     * @name WebWorkerFactory
151     * @module appverse.performance
152     *
153
154     * @description
155     * This factory starts a pooled multithreaded execution of a webworker:
156     * <pre></code>                _______
157     *                            |       |-> thread 1
158     * USER -> message -> task -> | pool  |-> thread 2
159     *                            |_______|-> thread N
160     * </code></pre>
161     *
162     * @requires https://docs.angularjs.org/api/ngMock/service/$q $q
163     * @requires https://docs.angularjs.org/api/ngMock/service/$log $log
164     * @requires PERFORMANCE_CONFIG
165     */
166    function WebWorkerPoolFactory ($log, $q, PERFORMANCE_CONFIG) {
167
168        var factory = {
169            _poolSize: PERFORMANCE_CONFIG.webworker_pooled_threads,
170            _authorizedWorkersOnly: PERFORMANCE_CONFIG.webworker_authorized_workers_only,
171            _workersDir: PERFORMANCE_CONFIG.webworker_directory,
172            _workersList: PERFORMANCE_CONFIG.webworker_authorized_workers,
173            _resultMessage: ''
174        };
175
176        $log.debug("Initializated webworkers factory preconfigured values." );
177        $log.debug("Default pool size: " + factory._poolSize);
178        $log.debug("Are only authorized preconfigured workers? " + factory._authorizedWorkersOnly);
179        $log.debug("The folder for webworkers in the app: " + factory._workersDir);
180        $log.debug("Number of members in the workers list: " + factory._workersList.length);
181
182        /**
183         * @ngdoc method
184         * @name WebWorkerFactory#runParallelTasksGroup
185         *
186         * @param {number} workerData WorkerData object with information of the task to be executed
187         * @param {object} workerTasks Array with a group of WorkerTask objects for the same WorkerData
188         *
189         * @description
190         * Runs a group of parallelized tasks
191         * Run a set of workers according to the pre-defined data in configuration
192         * (id, type, size in pool and worker file).
193         * Pe-definition in configuration is mandatory.
194         * The group of tasks are up to the caller.
195         */
196        factory.runParallelTasksGroup = function (workerData, workerTasks) {
197            this.workerData = workerData;
198
199
200            $log.debug("Started parallelized execution for worker: ");
201            $log.debug(workerData.toString());
202
203
204            //Initializes the pool with the indicated size for that worker group
205            var pool = new factory.WorkerPool(this.workerData.poolSize);
206            pool.init();
207
208            //Create a worker task for
209            if(workerTasks && workerTasks.length > 0){
210                // iterate through all the parts of the image
211                for (var x = 0; x < workerTasks.length; x++) {
212                    var workerTask = workerTasks[x];
213
214                    pool.addWorkerTask(workerTask);
215                }
216            }
217
218            return factory._resultMessage;
219        };
220
221
222        /**
223         * @ngdoc method
224         * @name WebWorkerFactory#passMessage
225         *
226         * @param {number} id of the called worker
227         * @param {object} function as callback
228         * @param {string} message to be passed to the worker
229         * @description
230         * Execute a task in a worker.
231         * The group of task is the same as the number indicated in the pool size for that pre-configured worker.
232         */
233        factory.runTask = function (workerId, message, callback) {
234
235            var pool = new factory.WorkerPool(factory._poolSize);
236            pool.init();
237
238            /*
239             If only workers in the configuration file are allowed.
240             No fallback needed.
241             */
242            var workerData;
243            var workerTask;
244            if(factory._authorizedWorkersOnly){
245                if(workerId){
246                    //Get data from configuration for the worker from the provided ID
247                    workerData = factory.getWorkerFromId(workerId);
248                }else{
249                    //NO VALID WORKER ID ERROR
250                    $log.error("NO VALID WORKER ID ERROR");
251                }
252            }else{
253                //If any provided worker is allowed the workerId arg is the complete path to the worker file
254                //The ID is not important here
255                if(workerId){
256                    workerData = new WorkerData(1001, 'dedicated', workerId);
257                }else{
258                    //NO VALID WORKER ID ERROR
259                    $log.error("NO VALID WORKER ID ERROR");
260                }
261            }
262
263            if(workerData) {
264                pool = new factory.WorkerPool(workerData.poolSize);
265                /*
266                 Create the worker task for the pool (only one task, passed N times):
267                 workerName: File of the worker
268                 callback: Register the supplied function as callback
269                 message: The last argument will be used to send a message to the worker
270                 */
271                workerTask = new factory.WorkerTask(workerData, callback, message);
272                // Pass the worker task object to the execution pool.
273                // The default behavior is create one task for each thread in the pool.
274                for(var i = 0; i < factory._poolSize; i++){
275                    pool.addWorkerTask(workerTask);
276                }
277            }else{
278                //NO WORKER DATA ERROR
279                $log.error("NO WORKER DATA ERROR");
280            }
281
282
283            //return _resultMessage;
284        };
285
286
287        factory.WorkerPool = function(poolSize) {
288            var _this = this;
289            if(!poolSize) {
290                this.size = factory._poolSize;
291            }else{
292                this.size = poolSize;
293            }
294
295            //Initialize some vars with default values
296            this.taskQueue = [];
297            this.workerQueue = [];
298
299            //Start the thread pool. To be used by the caller.
300            this.init = function() {
301                //Create the 'size' number of worker threads
302                for (var i = 0 ; i < _this.size ; i++) {
303                    _this.workerQueue.push(new WorkerThread(_this));
304                }
305            };
306
307
308            this.addWorkerTask = function(workerTask) {
309                if (_this.workerQueue.length > 0) {
310                    // get the worker from the front of the queue
311                    var workerThread = _this.workerQueue.shift();
312                    workerThread.run(workerTask);
313                } else {
314                    // If there are not free workers the task is put in queue
315                    _this.taskQueue.push(workerTask);
316                }
317            };
318
319
320            //Execute the queued task. If empty, put the task to the queue.
321            this.freeWorkerThread = function(workerThread) {
322                if (_this.taskQueue.length > 0) {
323                    // It is not put back in the queue, but it is executed on the next task
324                    var workerTask = _this.taskQueue.shift();
325                    workerThread.run(workerTask);
326                } else {
327                    _this.taskQueue.push(workerThread);
328                }
329            };
330
331        };
332
333        //Runner work tasks in the pool
334        function WorkerThread(parentPool) {
335
336            var _this = this;
337            this.parentPool = parentPool;
338            this.workerTask = {};
339
340            //Execute the task
341            this.run = function(workerTask) {
342                _this.workerTask = workerTask;
343
344                //Create a new web worker
345                if (_this.workerTask.script != null) {
346                    /*
347                     Creation of workers.
348                     For both dedicated and shared workers, you can also attach to the
349                     message event handler event type by using the addEventListener method.
350                     */
351                    var worker;
352                    if(workerTask.type == PERFORMANCE_CONFIG.webworker_dedicated_literal){
353                        worker = new Worker(_this.workerTask.script);
354                        worker.addEventListener('message', _this.OnWorkerMessageHandler, false);
355                        worker.postMessage(_this.workerTask.startMessage);
356                    }else if(workerTask.type == PERFORMANCE_CONFIG.webworker_shared_literal){
357                        worker = new SharedWorker(_this.workerTask.script);
358                        worker.port.addEventListener('message', _this.OnWorkerMessageHandler, false);
359                        worker.port.postMessage(_this.workerTask.startMessage);
360                    }else{
361                        //NO TYPE ERROR
362                        $log.error("NO VALID WORKER TYPE");
363                    }
364                }
365            };
366
367            //We assume we only get a single callback from a worker as a handler
368            //It also indicates the end of this worker.
369            _this.OnWorkerMessageHandler = function (evt) {
370                // pass to original callback
371                _this.workerTask.callback(evt);
372
373                // We should use a separate thread to add the worker
374                _this.parentPool.freeWorkerThread(_this);
375            };
376        }
377
378
379        //The task to run
380        factory.WorkerTask = function (workerData, callback, msg) {
381            this.script = workerData.file;
382            if(callback){
383                this.callback = callback;
384            }else{
385                this.callback = defaultEventHandler;
386            }
387            this.startMessage = msg;
388            this.type = workerData.type;
389        };
390
391        /*
392         Default event handler.
393         */
394        function defaultEventHandler(event){
395            factory._resultMessage = event.data;
396        }
397
398        //Data object for a worker
399        function WorkerData(workerId, type, poolSize, worker) {
400            this.id = workerId;
401            this.type = type;
402            this.poolSize = poolSize;
403            this.file = worker;
404        }
405
406        WorkerData.prototype.toString = function(){
407            return "ID: " + this.id + "|TYPE: " + this.type + "|POOL SIZE: " + this.poolSize + "|FILE: " + this.file;
408
409        };
410
411        //Extract worker information from configuration
412        factory.getWorkerFromId = function (workerId, poolSize){
413            this.id = workerId;
414            this.type = '';
415            this.poolSize = poolSize;
416            this.file = '';
417
418            for(var i = 0; i < factory._workersList.length; i++) {
419                if(factory._workersList[i].id === workerId){
420                    this.type = factory._workersList[i].type;
421                    if(!this.poolSize || this.poolSize == 0){
422                        this.poolSize = factory._workersList[i].poolSize;
423                    }else{
424                        this.poolSize = poolSize;
425                    }
426
427                    this.file = factory._workersDir + factory._workersList[i].file;
428                    break;
429                }
430            }
431
432            var workerData = new WorkerData(this.id, this.type, this.poolSize, this.file);
433
434            return workerData;
435        };
436
437        return factory;
438    }
439
440})();
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Jest on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)