data-source.ts 9.3 KB

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