|
| 1 | +import { |
| 2 | + RenderRequest, |
| 3 | + RenderResponse, |
| 4 | + RenderResult, |
| 5 | + VizWorkerHash, |
| 6 | + VizWorkerSource, |
| 7 | + // eslint-disable-next-line import/no-unresolved |
| 8 | +} from '../../worker/voyager.worker'; |
| 9 | +import { computeHash } from '../utils/compute-hash'; |
| 10 | +import { LocalStorageLRUCache } from '../utils/local-storage-lru-cache'; |
| 11 | + |
| 12 | +export class VizWorker { |
| 13 | + private _cache = new LocalStorageLRUCache({ |
| 14 | + localStorageKey: 'VoyagerSVGCache', |
| 15 | + maxSize: 10, |
| 16 | + }); |
| 17 | + private _worker: Worker; |
| 18 | + private _listeners: Array<(result: RenderResult) => void> = []; |
| 19 | + |
| 20 | + constructor() { |
| 21 | + const blob = new Blob([VizWorkerSource], { |
| 22 | + type: 'application/javascript', |
| 23 | + }); |
| 24 | + const url = URL.createObjectURL(blob); |
| 25 | + |
| 26 | + this._worker = new Worker(url, { name: 'graphql-voyager-worker' }); |
| 27 | + this._worker.addEventListener('message', (event) => { |
| 28 | + const { id, result } = event.data as RenderResponse; |
| 29 | + |
| 30 | + this._listeners[id](result); |
| 31 | + delete this._listeners[id]; |
| 32 | + }); |
| 33 | + } |
| 34 | + |
| 35 | + async renderString(dot: string): Promise<string> { |
| 36 | + const dotHash = await computeHash(dot); |
| 37 | + const cacheKey = `worker:${VizWorkerHash}:dot:${dotHash}`; |
| 38 | + |
| 39 | + try { |
| 40 | + const cachedSVG = this._cache.get(cacheKey); |
| 41 | + if (cachedSVG != null) { |
| 42 | + console.log('SVG cached'); |
| 43 | + return decompressFromDataURL(cachedSVG); |
| 44 | + } |
| 45 | + } catch (err) { |
| 46 | + console.warn('Can not read graphql-voyager cache: ', err); |
| 47 | + } |
| 48 | + |
| 49 | + console.time('Rendering SVG'); |
| 50 | + const svg = await this._renderString(dot); |
| 51 | + console.timeEnd('Rendering SVG'); |
| 52 | + |
| 53 | + try { |
| 54 | + this._cache.set(cacheKey, await compressToDataURL(svg)); |
| 55 | + } catch (err) { |
| 56 | + console.warn('Can not write graphql-voyager cache: ', err); |
| 57 | + } |
| 58 | + return svg; |
| 59 | + } |
| 60 | + |
| 61 | + _renderString(src: string): Promise<string> { |
| 62 | + return new Promise((resolve, reject) => { |
| 63 | + const id = this._listeners.length; |
| 64 | + |
| 65 | + this._listeners.push(function (result): void { |
| 66 | + if ('error' in result) { |
| 67 | + const { error } = result; |
| 68 | + const e = new Error(error.message); |
| 69 | + if (error.fileName) (e as any).fileName = error.fileName; |
| 70 | + if (error.lineNumber) (e as any).lineNumber = error.lineNumber; |
| 71 | + if (error.stack) (e as any).stack = error.stack; |
| 72 | + return reject(e); |
| 73 | + } |
| 74 | + resolve(result.value); |
| 75 | + }); |
| 76 | + |
| 77 | + const renderRequest: RenderRequest = { id, src }; |
| 78 | + this._worker.postMessage(renderRequest); |
| 79 | + }); |
| 80 | + } |
| 81 | +} |
| 82 | + |
| 83 | +async function decompressFromDataURL(dataURL: string): Promise<string> { |
| 84 | + const response = await fetch(dataURL); |
| 85 | + const blob = await response.blob(); |
| 86 | + switch (blob.type) { |
| 87 | + case 'application/gzip': { |
| 88 | + // @ts-expect-error DecompressionStream is missing from DOM types |
| 89 | + const stream = blob.stream().pipeThrough(new DecompressionStream('gzip')); |
| 90 | + const decompressedBlob = await streamToBlob(stream, 'text/plain'); |
| 91 | + return decompressedBlob.text(); |
| 92 | + } |
| 93 | + case 'text/plain': |
| 94 | + return blob.text(); |
| 95 | + default: |
| 96 | + throw new Error('Can not convert data url with MIME type:' + blob.type); |
| 97 | + } |
| 98 | +} |
| 99 | + |
| 100 | +async function compressToDataURL(str: string): Promise<string> { |
| 101 | + try { |
| 102 | + const blob = new Blob([str], { type: 'text/plain' }); |
| 103 | + // @ts-expect-error CompressionStream is missing from DOM types |
| 104 | + const stream = blob.stream().pipeThrough(new CompressionStream('gzip')); |
| 105 | + const compressedBlob = await streamToBlob(stream, 'application/gzip'); |
| 106 | + return blobToDataURL(compressedBlob); |
| 107 | + } catch (err) { |
| 108 | + console.warn('Can not compress string: ', err); |
| 109 | + return `data:text/plain;charset=utf-8,${encodeURIComponent(str)}`; |
| 110 | + } |
| 111 | +} |
| 112 | + |
| 113 | +function blobToDataURL(blob: Blob): Promise<string> { |
| 114 | + const fileReader = new FileReader(); |
| 115 | + |
| 116 | + return new Promise((resolve, reject) => { |
| 117 | + try { |
| 118 | + fileReader.onload = function (event) { |
| 119 | + // eslint-disable-next-line @typescript-eslint/no-base-to-string |
| 120 | + const dataURL = event.target!.result!.toString(); |
| 121 | + resolve(dataURL); |
| 122 | + }; |
| 123 | + fileReader.readAsDataURL(blob); |
| 124 | + } catch (err) { |
| 125 | + reject(err); |
| 126 | + } |
| 127 | + }); |
| 128 | +} |
| 129 | + |
| 130 | +function streamToBlob(stream: ReadableStream, mimeType: string): Promise<Blob> { |
| 131 | + const response = new Response(stream, { |
| 132 | + headers: { 'Content-Type': mimeType }, |
| 133 | + }); |
| 134 | + return response.blob(); |
| 135 | +} |
0 commit comments