comlinkWorker.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import { WorkerSafeElectronClient } from "@ente/shared/electron/worker/client";
  2. import { addLocalLog } from "@ente/shared/logging";
  3. import { expose, Remote, wrap } from "comlink";
  4. import { logError } from "../sentry";
  5. export class ComlinkWorker<T extends new () => InstanceType<T>> {
  6. public remote: Promise<Remote<InstanceType<T>>>;
  7. private worker: Worker;
  8. private name: string;
  9. constructor(name: string, worker: Worker) {
  10. this.name = name;
  11. this.worker = worker;
  12. this.worker.onerror = (errorEvent) => {
  13. logError(Error(errorEvent.message), "Got error event from worker", {
  14. errorEvent: JSON.stringify(errorEvent),
  15. name: this.name,
  16. });
  17. };
  18. addLocalLog(() => `Initiated ${this.name}`);
  19. const comlink = wrap<T>(this.worker);
  20. this.remote = new comlink() as Promise<Remote<InstanceType<T>>>;
  21. expose(WorkerSafeElectronClient, this.worker);
  22. }
  23. public getName() {
  24. return this.name;
  25. }
  26. public terminate() {
  27. this.worker.terminate();
  28. addLocalLog(() => `Terminated ${this.name}`);
  29. }
  30. }