service.ts 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import { runningInWorker } from "@ente/shared/platform";
  2. import { LimitedCache } from "@ente/shared/storage/cacheStorage/types";
  3. import * as Comlink from "comlink";
  4. import { wrap } from "comlink";
  5. import { ElectronAPIsType } from "./types";
  6. import {
  7. ProxiedWorkerLimitedCache,
  8. WorkerSafeElectronClient,
  9. } from "./worker/client";
  10. import { deserializeToResponse, serializeResponse } from "./worker/utils/proxy";
  11. export interface LimitedElectronAPIs
  12. extends Pick<
  13. ElectronAPIsType,
  14. | "openDiskCache"
  15. | "deleteDiskCache"
  16. | "getSentryUserID"
  17. | "convertToJPEG"
  18. | "logToDisk"
  19. > {}
  20. class WorkerSafeElectronServiceImpl implements LimitedElectronAPIs {
  21. proxiedElectron:
  22. | Comlink.Remote<WorkerSafeElectronClient>
  23. | WorkerSafeElectronClient;
  24. ready: Promise<any>;
  25. constructor() {
  26. this.ready = this.init();
  27. }
  28. private async init() {
  29. if (runningInWorker()) {
  30. const workerSafeElectronClient =
  31. wrap<typeof WorkerSafeElectronClient>(self);
  32. this.proxiedElectron = await new workerSafeElectronClient();
  33. } else {
  34. this.proxiedElectron = new WorkerSafeElectronClient();
  35. }
  36. }
  37. async openDiskCache(cacheName: string, cacheLimitInBytes?: number) {
  38. await this.ready;
  39. const cache = await this.proxiedElectron.openDiskCache(
  40. cacheName,
  41. cacheLimitInBytes,
  42. );
  43. return {
  44. match: transformMatch(cache.match.bind(cache)),
  45. put: transformPut(cache.put.bind(cache)),
  46. delete: cache.delete.bind(cache),
  47. };
  48. }
  49. async deleteDiskCache(cacheName: string) {
  50. await this.ready;
  51. return await this.proxiedElectron.deleteDiskCache(cacheName);
  52. }
  53. async getSentryUserID() {
  54. await this.ready;
  55. return this.proxiedElectron.getSentryUserID();
  56. }
  57. async convertToJPEG(
  58. inputFileData: Uint8Array,
  59. filename: string,
  60. ): Promise<Uint8Array> {
  61. await this.ready;
  62. return this.proxiedElectron.convertToJPEG(inputFileData, filename);
  63. }
  64. async logToDisk(message: string) {
  65. await this.ready;
  66. return this.proxiedElectron.logToDisk(message);
  67. }
  68. }
  69. export const WorkerSafeElectronService = new WorkerSafeElectronServiceImpl();
  70. function transformMatch(
  71. fn: ProxiedWorkerLimitedCache["match"],
  72. ): LimitedCache["match"] {
  73. return async (key: string, options) => {
  74. return deserializeToResponse(await fn(key, options));
  75. };
  76. }
  77. function transformPut(
  78. fn: ProxiedWorkerLimitedCache["put"],
  79. ): LimitedCache["put"] {
  80. return async (key: string, data: Response) => {
  81. fn(key, await serializeResponse(data));
  82. };
  83. }