client.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. getSentryUserID: () => Promise<string>;
  12. convertToJPEG: (
  13. inputFileData: Uint8Array,
  14. filename: string,
  15. ) => Promise<Uint8Array>;
  16. logToDisk: (message: string) => void;
  17. }
  18. export interface ProxiedWorkerLimitedCache {
  19. match: (
  20. key: string,
  21. options?: { sizeInBytes?: number },
  22. ) => Promise<ArrayBuffer>;
  23. put: (key: string, data: ArrayBuffer) => Promise<void>;
  24. delete: (key: string) => Promise<boolean>;
  25. }
  26. export class WorkerSafeElectronClient implements ProxiedLimitedElectronAPIs {
  27. async openDiskCache(cacheName: string, cacheLimitInBytes?: number) {
  28. const cache = await ElectronAPIs.openDiskCache(
  29. cacheName,
  30. cacheLimitInBytes,
  31. );
  32. return Comlink.proxy({
  33. match: Comlink.proxy(transformMatch(cache.match.bind(cache))),
  34. put: Comlink.proxy(transformPut(cache.put.bind(cache))),
  35. delete: Comlink.proxy(cache.delete.bind(cache)),
  36. });
  37. }
  38. async deleteDiskCache(cacheName: string) {
  39. return await ElectronAPIs.deleteDiskCache(cacheName);
  40. }
  41. async getSentryUserID() {
  42. return await ElectronAPIs.getSentryUserID();
  43. }
  44. async convertToJPEG(
  45. inputFileData: Uint8Array,
  46. filename: string,
  47. ): Promise<Uint8Array> {
  48. return await ElectronAPIs.convertToJPEG(inputFileData, filename);
  49. }
  50. logToDisk(message: string) {
  51. return ElectronAPIs.logToDisk(message);
  52. }
  53. }
  54. function transformMatch(
  55. fn: LimitedCache["match"],
  56. ): ProxiedWorkerLimitedCache["match"] {
  57. return async (key: string, options: { sizeInBytes?: number }) => {
  58. return serializeResponse(await fn(key, options));
  59. };
  60. }
  61. function transformPut(
  62. fn: LimitedCache["put"],
  63. ): ProxiedWorkerLimitedCache["put"] {
  64. return async (key: string, data: ArrayBuffer) => {
  65. fn(key, deserializeToResponse(data));
  66. };
  67. }