All files / packages/core/src/webWorkerManager webWorkerManager.js

2.29% Statements 2/87
0% Branches 0/49
7.14% Functions 1/14
2.35% Lines 2/85

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255            1x 1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              
import * as Comlink from 'comlink';
import { RequestType } from '../enums/';
import { RequestPoolManager } from '../requestPool/requestPoolManager';
 
class CentralizedWorkerManager {
  constructor() {
    this.workerRegistry = {};
    this.workerPoolManager = new RequestPoolManager('webworker');
  }
 
  /**
   * Registers a new worker, it doesn't mean that the function will get executed.
   *
   * @param workerName - The name of the worker.
   * @param workerFn - The function that creates a new instance of the worker.
   * @param options - Optional parameters.
   * @param options.maxWorkerInstances - The maximum number of instances of this worker that can be created.
   * For instance if you create a worker with maxWorkerInstances = 2, then only 2 instances of this worker will be created
   * and in case there are 10 tasks that need to be executed, each will get assigned 5 tasks.
   * @param options.overwrite - Whether to overwrite the worker if it's already registered.
   * @param options.autoTerminateOnIdle - Whether to automatically terminate idle workers.
   */
  registerWorker(workerName, workerFn, options = {}) {
    const {
      maxWorkerInstances = 1,
      overwrite = false,
      autoTerminateOnIdle = {
        enabled: false,
        idleTimeThreshold: 3000, // 3 seconds
      },
    } = options;
 
    if (this.workerRegistry[workerName] && !overwrite) {
      console.warn(`Worker type '${workerName}' is already registered...`);
      return;
    }
 
    if (overwrite && this.workerRegistry[workerName]?.idleCheckIntervalId) {
      clearInterval(this.workerRegistry[workerName].idleCheckIntervalId);
    }
 
    const workerProperties = {
      workerFn: null,
      instances: [],
      loadCounters: [],
      lastActiveTime: [],
      // used for termination
      nativeWorkers: [],
      // auto termination
      autoTerminateOnIdle: autoTerminateOnIdle.enabled,
      idleCheckIntervalId: null,
      idleTimeThreshold: autoTerminateOnIdle.idleTimeThreshold,
    };
 
    workerProperties.loadCounters = Array(maxWorkerInstances).fill(0);
    workerProperties.lastActiveTime = Array(maxWorkerInstances).fill(null);
 
    for (let i = 0; i < maxWorkerInstances; i++) {
      const worker = workerFn();
      workerProperties.instances.push(Comlink.wrap(worker));
      workerProperties.nativeWorkers.push(worker);
      workerProperties.workerFn = workerFn;
    }
 
    this.workerRegistry[workerName] = workerProperties;
  }
 
  getNextWorkerAPI(workerName) {
    const workerProperties = this.workerRegistry[workerName];
 
    if (!workerProperties) {
      console.error(`Worker type '${workerName}' is not registered.`);
      return null;
    }
 
    // Find the worker with the minimum load.
    const workerInstances = workerProperties.instances.filter(
      (instance) => instance !== null
    );
 
    let minLoadIndex = 0;
    let minLoadValue = workerProperties.loadCounters[0] || 0;
    for (let i = 1; i < workerInstances.length; i++) {
      const currentLoadValue = workerProperties.loadCounters[i] || 0;
      if (currentLoadValue < minLoadValue) {
        minLoadIndex = i;
        minLoadValue = currentLoadValue;
      }
    }
 
    // Check and recreate the worker if it was terminated.
    if (workerProperties.instances[minLoadIndex] === null) {
      const worker = workerProperties.workerFn();
      workerProperties.instances[minLoadIndex] = Comlink.wrap(worker);
      workerProperties.nativeWorkers[minLoadIndex] = worker;
    }
 
    // Update the load counter.
    workerProperties.loadCounters[minLoadIndex] += 1;
 
    // return the worker that has the minimum load.
    return {
      api: workerProperties.instances[minLoadIndex],
      index: minLoadIndex,
    };
  }
 
  /**
   * Executes a task on a worker.
   *
   * @param workerName - The name of the worker to execute the task on.
   * @param methodName - The name of the method to execute on the worker.
   * @param args - The arguments to pass to the method. Default is an array
   * You should put your transferable objects in the first argument as object
   * and from the second argument you can put your non-transferable objects such
   * as functions, classes, etc.
   * @param options - An object containing options for the request. Default is an empty object.
   * @param options.requestType - The type of the request. Default is RequestType.Compute.
   * @param options.priority - The priority of the request. Default is 0.
   * @param options.options - Additional options for the request. Default is an empty object.
   *
   * @returns A promise that resolves with the result of the task.
   */
  executeTask(
    workerName,
    methodName,
    args = {},
    {
      requestType = RequestType.Compute,
      priority = 0,
      options = {},
      callbacks = [],
    } = {}
  ) {
    return new Promise((resolve, reject) => {
      const requestFn = async () => {
        const { api, index } = this.getNextWorkerAPI(workerName);
        if (!api) {
          const error = new Error(
            `No available worker instance for '${workerName}'`
          );
          console.error(error);
          reject(error);
          return;
        }
 
        try {
          // fix if any of the args keys are a function then we need to proxy it
          // for the worker to be able to call it
          let finalCallbacks = [];
          if (callbacks.length) {
            finalCallbacks = callbacks.map((cb) => {
              return Comlink.proxy(cb);
            });
          }
          const workerProperties = this.workerRegistry[workerName];
 
          workerProperties.processing = true;
 
          const results = await api[methodName](args, ...finalCallbacks);
 
          workerProperties.processing = false;
          workerProperties.lastActiveTime[index] = Date.now();
 
          // If auto termination is enabled and the interval is not set, set it.
          if (
            workerProperties.autoTerminateOnIdle &&
            !workerProperties.idleCheckIntervalId &&
            workerProperties.idleTimeThreshold
          ) {
            workerProperties.idleCheckIntervalId = setInterval(() => {
              this.terminateIdleWorkers(
                workerName,
                workerProperties.idleTimeThreshold
              );
            }, workerProperties.idleTimeThreshold);
          }
 
          resolve(results);
        } catch (err) {
          console.error(
            `Error executing method '${methodName}' on worker '${workerName}':`,
            err
          );
          reject(err);
        } finally {
          this.workerRegistry[workerName].loadCounters[index]--;
        }
      };
 
      // I believe there is a bug right now, where if there are two workers
      // and one wants to run a compute job 6 times and the limit is just 5, then
      // the other worker will never get a chance to run its compute job.
      // we should probably have a separate limit for compute jobs per worker
      // context as there is another layer of parallelism there.
      this.workerPoolManager.addRequest(
        requestFn,
        requestType,
        options,
        priority
      );
    });
  }
 
  terminateIdleWorkers(workerName, idleTimeThreshold) {
    const workerProperties = this.workerRegistry[workerName];
 
    if (workerProperties.processing) {
      return;
    }
 
    const now = Date.now();
 
    workerProperties.instances.forEach((_, index) => {
      const lastActiveTime = workerProperties.lastActiveTime[index];
      const isWorkerActive =
        lastActiveTime !== null && workerProperties.loadCounters[index] > 0;
      const idleTime = now - lastActiveTime;
 
      if (!isWorkerActive && idleTime > idleTimeThreshold) {
        this.terminateWorkerInstance(workerName, index);
      }
    });
  }
 
  terminate(workerName) {
    const workerProperties = this.workerRegistry[workerName];
    if (!workerProperties) {
      console.error(`Worker type '${workerName}' is not registered.`);
      return;
    }
 
    workerProperties.instances.forEach((_, index) => {
      this.terminateWorkerInstance(workerName, index);
    });
  }
 
  // New method to handle individual worker termination
  terminateWorkerInstance(workerName, index) {
    const workerProperties = this.workerRegistry[workerName];
    const workerInstance = workerProperties.instances[index];
 
    if (workerInstance !== null) {
      workerInstance[Comlink.releaseProxy]();
      workerProperties.nativeWorkers[index].terminate();
 
      // Set the worker instance to null after termination
      workerProperties.instances[index] = null;
      workerProperties.lastActiveTime[index] = null;
    }
  }
}
 
export default CentralizedWorkerManager;