client.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import ElectronAPIs from "@ente/shared/electron";
  2. import { LimitedCache } from "@ente/shared/storage/cacheStorage/types";
  3. import * as Comlink from "comlink";
  4. import { deserializeToResponse, serializeResponse } from "./utils/proxy";
  5. export interface ProxiedLimitedElectronAPIs {
  6. openDiskCache: (
  7. cacheName: string,
  8. cacheLimitInBytes?: number,
  9. ) => Promise<ProxiedWorkerLimitedCache>;
  10. deleteDiskCache: (cacheName: string) => Promise<boolean>;
  11. convertToJPEG: (
  12. inputFileData: Uint8Array,
  13. filename: string,
  14. ) => Promise<Uint8Array>;
  15. logToDisk: (message: string) => void;
  16. }
  17. export interface ProxiedWorkerLimitedCache {
  18. match: (
  19. key: string,
  20. options?: { sizeInBytes?: number },
  21. ) => Promise<ArrayBuffer>;
  22. put: (key: string, data: ArrayBuffer) => Promise<void>;
  23. delete: (key: string) => Promise<boolean>;
  24. }
  25. export class WorkerSafeElectronClient implements ProxiedLimitedElectronAPIs {
  26. async openDiskCache(cacheName: string, cacheLimitInBytes?: number) {
  27. const cache = await ElectronAPIs.openDiskCache(
  28. cacheName,
  29. cacheLimitInBytes,
  30. );
  31. return Comlink.proxy({
  32. match: Comlink.proxy(transformMatch(cache.match.bind(cache))),
  33. put: Comlink.proxy(transformPut(cache.put.bind(cache))),
  34. delete: Comlink.proxy(cache.delete.bind(cache)),
  35. });
  36. }
  37. async deleteDiskCache(cacheName: string) {
  38. return await ElectronAPIs.deleteDiskCache(cacheName);
  39. }
  40. async convertToJPEG(
  41. inputFileData: Uint8Array,
  42. filename: string,
  43. ): Promise<Uint8Array> {
  44. return await ElectronAPIs.convertToJPEG(inputFileData, filename);
  45. }
  46. logToDisk(message: string) {
  47. return ElectronAPIs.logToDisk(message);
  48. }
  49. }
  50. function transformMatch(
  51. fn: LimitedCache["match"],
  52. ): ProxiedWorkerLimitedCache["match"] {
  53. return async (key: string, options: { sizeInBytes?: number }) => {
  54. return serializeResponse(await fn(key, options));
  55. };
  56. }
  57. function transformPut(
  58. fn: LimitedCache["put"],
  59. ): ProxiedWorkerLimitedCache["put"] {
  60. return async (key: string, data: ArrayBuffer) => {
  61. fn(key, deserializeToResponse(data));
  62. };
  63. }