data-source.ts 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. /**
  2. * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. *
  6. * Adapted from LiteMol
  7. */
  8. import { Task, RuntimeContext } from 'mol-task';
  9. import { utf8Read } from 'mol-io/common/utf8';
  10. // export enum DataCompressionMethod {
  11. // None,
  12. // Gzip
  13. // }
  14. export interface AjaxGetParams<T extends 'string' | 'binary' | 'json' = 'string'> {
  15. url: string,
  16. type?: T,
  17. title?: string,
  18. // compression?: DataCompressionMethod
  19. body?: string
  20. }
  21. export function readStringFromFile(file: File) {
  22. return <Task<string>>readFromFileInternal(file, false);
  23. }
  24. export function readUint8ArrayFromFile(file: File) {
  25. return <Task<Uint8Array>>readFromFileInternal(file, true);
  26. }
  27. export function readFromFile(file: File, type: 'string' | 'binary') {
  28. return <Task<Uint8Array | string>>readFromFileInternal(file, type === 'binary');
  29. }
  30. // TODO: support for no-referrer
  31. export function ajaxGet(url: string): Task<string>
  32. export function ajaxGet(params: AjaxGetParams<'string'>): Task<string>
  33. export function ajaxGet(params: AjaxGetParams<'binary'>): Task<Uint8Array>
  34. export function ajaxGet<T = any>(params: AjaxGetParams<'json'>): Task<T>
  35. export function ajaxGet(params: AjaxGetParams<'string' | 'binary' | 'json'>): Task<string | Uint8Array | object>
  36. export function ajaxGet(params: AjaxGetParams<'string' | 'binary' | 'json'> | string) {
  37. if (typeof params === 'string') return ajaxGetInternal(params, params, 'string', false);
  38. return ajaxGetInternal(params.title, params.url, params.type || 'string', false /* params.compression === DataCompressionMethod.Gzip */, params.body);
  39. }
  40. export type AjaxTask = typeof ajaxGet
  41. function decompress(buffer: Uint8Array): Uint8Array {
  42. // TODO
  43. throw 'nyi';
  44. // const gzip = new LiteMolZlib.Gunzip(new Uint8Array(buffer));
  45. // return gzip.decompress();
  46. }
  47. async function processFile(ctx: RuntimeContext, asUint8Array: boolean, compressed: boolean, e: any) {
  48. const data = (e.target as FileReader).result;
  49. if (compressed) {
  50. await ctx.update('Decompressing...');
  51. const decompressed = decompress(new Uint8Array(data as ArrayBuffer));
  52. if (asUint8Array) {
  53. return decompressed;
  54. } else {
  55. return utf8Read(decompressed, 0, decompressed.length);
  56. }
  57. } else {
  58. return asUint8Array ? new Uint8Array(data as ArrayBuffer) : data as string;
  59. }
  60. }
  61. function readData(ctx: RuntimeContext, action: string, data: XMLHttpRequest | FileReader, asUint8Array: boolean): Promise<any> {
  62. return new Promise<any>((resolve, reject) => {
  63. data.onerror = (e: any) => {
  64. const error = (<FileReader>e.target).error;
  65. reject(error ? error : 'Failed.');
  66. };
  67. data.onabort = () => reject(Task.Aborted(''));
  68. data.onprogress = (e: ProgressEvent) => {
  69. if (e.lengthComputable) {
  70. ctx.update({ message: action, isIndeterminate: false, current: e.loaded, max: e.total });
  71. } else {
  72. ctx.update({ message: `${action} ${(e.loaded / 1024 / 1024).toFixed(2)} MB`, isIndeterminate: true });
  73. }
  74. }
  75. data.onload = (e: any) => resolve(e);
  76. });
  77. }
  78. function readFromFileInternal(file: File, asUint8Array: boolean): Task<string | Uint8Array> {
  79. let reader: FileReader | undefined = void 0;
  80. return Task.create('Read File', async ctx => {
  81. try {
  82. reader = new FileReader();
  83. const isCompressed = /\.gz$/i.test(file.name);
  84. if (isCompressed || asUint8Array) reader.readAsArrayBuffer(file);
  85. else reader.readAsBinaryString(file);
  86. ctx.update({ message: 'Opening file...', canAbort: true });
  87. const e = await readData(ctx, 'Reading...', reader, asUint8Array);
  88. const result = processFile(ctx, asUint8Array, isCompressed, e);
  89. return result;
  90. } finally {
  91. reader = void 0;
  92. }
  93. }, () => {
  94. if (reader) reader.abort();
  95. });
  96. }
  97. class RequestPool {
  98. private static pool: XMLHttpRequest[] = [];
  99. private static poolSize = 15;
  100. static get() {
  101. if (this.pool.length) {
  102. return this.pool.pop()!;
  103. }
  104. return new XMLHttpRequest();
  105. }
  106. static emptyFunc() { }
  107. static deposit(req: XMLHttpRequest) {
  108. if (this.pool.length < this.poolSize) {
  109. req.onabort = RequestPool.emptyFunc;
  110. req.onerror = RequestPool.emptyFunc;
  111. req.onload = RequestPool.emptyFunc;
  112. req.onprogress = RequestPool.emptyFunc;
  113. this.pool.push(req);
  114. }
  115. }
  116. }
  117. async function processAjax(ctx: RuntimeContext, asUint8Array: boolean, decompressGzip: boolean, e: any) {
  118. const req = (e.target as XMLHttpRequest);
  119. if (req.status >= 200 && req.status < 400) {
  120. if (asUint8Array) {
  121. const buff = new Uint8Array(e.target.response);
  122. RequestPool.deposit(e.target);
  123. if (decompressGzip) {
  124. return decompress(buff);
  125. } else {
  126. return buff;
  127. }
  128. }
  129. else {
  130. const text = e.target.responseText;
  131. RequestPool.deposit(e.target);
  132. return text;
  133. }
  134. } else {
  135. const status = req.statusText;
  136. RequestPool.deposit(e.target);
  137. throw status;
  138. }
  139. }
  140. function ajaxGetInternal(title: string | undefined, url: string, type: 'json' | 'string' | 'binary', decompressGzip: boolean, body?: string): Task<string | Uint8Array> {
  141. let xhttp: XMLHttpRequest | undefined = void 0;
  142. return Task.create(title ? title : 'Download', async ctx => {
  143. try {
  144. const asUint8Array = type === 'binary';
  145. if (!asUint8Array && decompressGzip) {
  146. throw 'Decompress is only available when downloading binary data.';
  147. }
  148. xhttp = RequestPool.get();
  149. xhttp.open(body ? 'post' : 'get', url, true);
  150. xhttp.responseType = asUint8Array ? 'arraybuffer' : 'text';
  151. xhttp.send(body);
  152. ctx.update({ message: 'Waiting for server...', canAbort: true });
  153. const e = await readData(ctx, 'Downloading...', xhttp, asUint8Array);
  154. const result = await processAjax(ctx, asUint8Array, decompressGzip, e)
  155. if (type === 'json') {
  156. ctx.update({ message: 'Parsing JSON...', canAbort: false });
  157. const data = JSON.parse(result);
  158. return data;
  159. }
  160. return result;
  161. } finally {
  162. xhttp = void 0;
  163. }
  164. }, () => {
  165. if (xhttp) xhttp.abort();
  166. });
  167. }
  168. export type AjaxGetManyEntry<T> = { kind: 'ok', id: string, result: T } | { kind: 'error', id: string, error: any }
  169. export async function ajaxGetMany(ctx: RuntimeContext, sources: { id: string, url: string, isBinary?: boolean, canFail?: boolean }[], maxConcurrency: number) {
  170. const len = sources.length;
  171. const slots: AjaxGetManyEntry<string | Uint8Array>[] = new Array(sources.length);
  172. await ctx.update({ message: 'Downloading...', current: 0, max: len });
  173. let promises: Promise<AjaxGetManyEntry<any> & { index: number }>[] = [], promiseKeys: number[] = [];
  174. let currentSrc = 0;
  175. for (let _i = Math.min(len, maxConcurrency); currentSrc < _i; currentSrc++) {
  176. const current = sources[currentSrc];
  177. promises.push(wrapPromise(currentSrc, current.id, ajaxGet({ url: current.url, type: current.isBinary ? 'binary' : 'string' }).runAsChild(ctx)));
  178. promiseKeys.push(currentSrc);
  179. }
  180. let done = 0;
  181. while (promises.length > 0) {
  182. const r = await Promise.race(promises);
  183. const src = sources[r.index];
  184. const idx = promiseKeys.indexOf(r.index);
  185. done++;
  186. if (r.kind === 'error' && !src.canFail) {
  187. // TODO: cancel other downloads
  188. throw new Error(`${src.url}: ${r.error}`);
  189. }
  190. if (ctx.shouldUpdate) {
  191. await ctx.update({ message: 'Downloading...', current: done, max: len });
  192. }
  193. slots[r.index] = r;
  194. promises = promises.filter(_filterRemoveIndex, idx);
  195. promiseKeys = promiseKeys.filter(_filterRemoveIndex, idx);
  196. if (currentSrc < len) {
  197. const current = sources[currentSrc];
  198. promises.push(wrapPromise(currentSrc, current.id, ajaxGet({ url: current.url, type: current.isBinary ? 'binary' : 'string' }).runAsChild(ctx)));
  199. promiseKeys.push(currentSrc);
  200. currentSrc++;
  201. }
  202. }
  203. return slots;
  204. }
  205. function _filterRemoveIndex(this: number, _: any, i: number) {
  206. return this !== i;
  207. }
  208. async function wrapPromise<T>(index: number, id: string, p: Promise<T>): Promise<AjaxGetManyEntry<T> & { index: number }> {
  209. try {
  210. const result = await p;
  211. return { kind: 'ok', result, index, id };
  212. } catch (error) {
  213. return { kind: 'error', error, index, id }
  214. }
  215. }