Merge branch 'IDTEAM-1.26.0' into 'main'
[ProtonMail-WebClient.git] / packages / pass / lib / core / worker.service.ts
blob368c31f72d63f8fe1fa3c32b9838e8123ee9e619
1 import { throwError } from '@proton/pass/utils/fp/throw';
3 import { WASM_PROCEDURE_TIMEOUT } from './constants';
4 import type { PassCoreMethod, PassCoreRPC, PassCoreResult, PassCoreService } from './types';
6 /** Creates a `PassCoreService` instance which spawns the `PassRustCore`
7  * binary in a dedicated worker. Communication occurs via postMessaging
8  * through MessageChannels (see: `core.worker.ts`) This service should
9  * be used to ensure the WASM module will not block the main UI thread */
10 export const createPassCoreWorkerService = (): PassCoreService => {
11     const worker = new Worker(
12         /* webpackChunkName: "core.worker" */
13         new URL('@proton/pass/lib/core/core.worker', import.meta.url)
14     );
16     const send = <T extends PassCoreMethod>(message: PassCoreRPC<T>) => {
17         const channel = new MessageChannel();
19         return new Promise<PassCoreResult<T>>((resolve, reject) => {
20             const timer = setTimeout(
21                 () => reject(new Error(`[PassCoreWorker] Procedure timed out [${message.method}]`)),
22                 WASM_PROCEDURE_TIMEOUT
23             );
25             channel.port2.onmessage = (event: MessageEvent<PassCoreResult<T>>) => {
26                 resolve(event.data);
27                 clearTimeout(timer);
28             };
30             worker.postMessage(message, [channel.port1]);
31         })
32             .catch((err) => throwError({ name: 'PassCoreServiceError', message: err.message }))
33             .finally(() => {
34                 channel.port1.close();
35                 channel.port2.close();
36             });
37     };
39     return { exec: (method, ...args) => send({ method, args }) };