ente/packages/shared/worker/comlinkWorker.ts

32 lines
999 B
TypeScript
Raw Normal View History

2023-11-11 07:23:00 +00:00
import { expose, Remote, wrap } from 'comlink';
import { WorkerSafeElectronClient } from '@ente/shared/electron/worker/client';
2023-11-02 15:29:50 +00:00
import { addLocalLog } from '@ente/shared/logging';
2023-11-02 07:19:01 +00:00
export class ComlinkWorker<T extends new () => InstanceType<T>> {
public remote: Promise<Remote<InstanceType<T>>>;
private worker: Worker;
private name: string;
constructor(name: string, worker: Worker) {
this.name = name;
this.worker = worker;
this.worker.onerror = (errorEvent) => {
console.error('Got error event from worker', errorEvent);
};
2023-11-02 15:29:50 +00:00
addLocalLog(() => `Initiated ${this.name}`);
2023-11-02 07:19:01 +00:00
const comlink = wrap<T>(this.worker);
this.remote = new comlink() as Promise<Remote<InstanceType<T>>>;
expose(WorkerSafeElectronClient, this.worker);
2023-11-02 07:19:01 +00:00
}
public getName() {
return this.name;
}
public terminate() {
this.worker.terminate();
2023-11-02 15:29:50 +00:00
addLocalLog(() => `Terminated ${this.name}`);
2023-11-02 07:19:01 +00:00
}
}