data-source.ts 9.5 KB

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