blockedsource.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. "use strict";
  2. var __importDefault = (this && this.__importDefault) || function (mod) {
  3. return (mod && mod.__esModule) ? mod : { "default": mod };
  4. };
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. exports.BlockedSource = void 0;
  7. const quick_lru_1 = __importDefault(require("quick-lru"));
  8. const basesource_js_1 = require("./basesource.js");
  9. const utils_js_1 = require("../utils.js");
  10. class Block {
  11. /**
  12. *
  13. * @param {number} offset
  14. * @param {number} length
  15. * @param {ArrayBuffer} [data]
  16. */
  17. constructor(offset, length, data = null) {
  18. this.offset = offset;
  19. this.length = length;
  20. this.data = data;
  21. }
  22. /**
  23. * @returns {number} the top byte border
  24. */
  25. get top() {
  26. return this.offset + this.length;
  27. }
  28. }
  29. class BlockGroup {
  30. /**
  31. *
  32. * @param {number} offset
  33. * @param {number} length
  34. * @param {number[]} blockIds
  35. */
  36. constructor(offset, length, blockIds) {
  37. this.offset = offset;
  38. this.length = length;
  39. this.blockIds = blockIds;
  40. }
  41. }
  42. class BlockedSource extends basesource_js_1.BaseSource {
  43. /**
  44. *
  45. * @param {BaseSource} source The underlying source that shall be blocked and cached
  46. * @param {object} options
  47. * @param {number} [options.blockSize]
  48. * @param {number} [options.cacheSize]
  49. */
  50. constructor(source, { blockSize = 65536, cacheSize = 100 } = {}) {
  51. super();
  52. this.source = source;
  53. this.blockSize = blockSize;
  54. this.blockCache = new quick_lru_1.default({
  55. maxSize: cacheSize,
  56. onEviction: (blockId, block) => {
  57. this.evictedBlocks.set(blockId, block);
  58. },
  59. });
  60. /** @type {Map<number, Block>} */
  61. this.evictedBlocks = new Map();
  62. // mapping blockId -> Block instance
  63. this.blockRequests = new Map();
  64. // set of blockIds missing for the current requests
  65. this.blockIdsToFetch = new Set();
  66. this.abortedBlockIds = new Set();
  67. }
  68. get fileSize() {
  69. return this.source.fileSize;
  70. }
  71. /**
  72. *
  73. * @param {import("./basesource").Slice[]} slices
  74. */
  75. async fetch(slices, signal) {
  76. const blockRequests = [];
  77. const missingBlockIds = [];
  78. const allBlockIds = [];
  79. this.evictedBlocks.clear();
  80. for (const { offset, length } of slices) {
  81. let top = offset + length;
  82. const { fileSize } = this;
  83. if (fileSize !== null) {
  84. top = Math.min(top, fileSize);
  85. }
  86. const firstBlockOffset = Math.floor(offset / this.blockSize) * this.blockSize;
  87. for (let current = firstBlockOffset; current < top; current += this.blockSize) {
  88. const blockId = Math.floor(current / this.blockSize);
  89. if (!this.blockCache.has(blockId) && !this.blockRequests.has(blockId)) {
  90. this.blockIdsToFetch.add(blockId);
  91. missingBlockIds.push(blockId);
  92. }
  93. if (this.blockRequests.has(blockId)) {
  94. blockRequests.push(this.blockRequests.get(blockId));
  95. }
  96. allBlockIds.push(blockId);
  97. }
  98. }
  99. // allow additional block requests to accumulate
  100. await (0, utils_js_1.wait)();
  101. this.fetchBlocks(signal);
  102. // Gather all of the new requests that this fetch call is contributing to `fetch`.
  103. const missingRequests = [];
  104. for (const blockId of missingBlockIds) {
  105. // The requested missing block could already be in the cache
  106. // instead of having its request still be outstanding.
  107. if (this.blockRequests.has(blockId)) {
  108. missingRequests.push(this.blockRequests.get(blockId));
  109. }
  110. }
  111. // Actually await all pending requests that are needed for this `fetch`.
  112. await Promise.allSettled(blockRequests);
  113. await Promise.allSettled(missingRequests);
  114. // Perform retries if a block was interrupted by a previous signal
  115. const abortedBlockRequests = [];
  116. const abortedBlockIds = allBlockIds
  117. .filter((id) => this.abortedBlockIds.has(id) || !this.blockCache.has(id));
  118. abortedBlockIds.forEach((id) => this.blockIdsToFetch.add(id));
  119. // start the retry of some blocks if required
  120. if (abortedBlockIds.length > 0 && signal && !signal.aborted) {
  121. this.fetchBlocks(null);
  122. for (const blockId of abortedBlockIds) {
  123. const block = this.blockRequests.get(blockId);
  124. if (!block) {
  125. throw new Error(`Block ${blockId} is not in the block requests`);
  126. }
  127. abortedBlockRequests.push(block);
  128. }
  129. await Promise.allSettled(abortedBlockRequests);
  130. }
  131. // throw an abort error
  132. if (signal && signal.aborted) {
  133. throw new utils_js_1.AbortError('Request was aborted');
  134. }
  135. const blocks = allBlockIds.map((id) => this.blockCache.get(id) || this.evictedBlocks.get(id));
  136. const failedBlocks = blocks.filter((i) => !i);
  137. if (failedBlocks.length) {
  138. throw new utils_js_1.AggregateError(failedBlocks, 'Request failed');
  139. }
  140. // create a final Map, with all required blocks for this request to satisfy
  141. const requiredBlocks = new Map((0, utils_js_1.zip)(allBlockIds, blocks));
  142. // TODO: satisfy each slice
  143. return this.readSliceData(slices, requiredBlocks);
  144. }
  145. /**
  146. *
  147. * @param {AbortSignal} signal
  148. */
  149. fetchBlocks(signal) {
  150. // check if we still need to
  151. if (this.blockIdsToFetch.size > 0) {
  152. const groups = this.groupBlocks(this.blockIdsToFetch);
  153. // start requesting slices of data
  154. const groupRequests = this.source.fetch(groups, signal);
  155. for (let groupIndex = 0; groupIndex < groups.length; ++groupIndex) {
  156. const group = groups[groupIndex];
  157. for (const blockId of group.blockIds) {
  158. // make an async IIFE for each block
  159. this.blockRequests.set(blockId, (async () => {
  160. try {
  161. const response = (await groupRequests)[groupIndex];
  162. const blockOffset = blockId * this.blockSize;
  163. const o = blockOffset - response.offset;
  164. const t = Math.min(o + this.blockSize, response.data.byteLength);
  165. const data = response.data.slice(o, t);
  166. const block = new Block(blockOffset, data.byteLength, data, blockId);
  167. this.blockCache.set(blockId, block);
  168. this.abortedBlockIds.delete(blockId);
  169. }
  170. catch (err) {
  171. if (err.name === 'AbortError') {
  172. // store the signal here, we need it to determine later if an
  173. // error was caused by this signal
  174. err.signal = signal;
  175. this.blockCache.delete(blockId);
  176. this.abortedBlockIds.add(blockId);
  177. }
  178. else {
  179. throw err;
  180. }
  181. }
  182. finally {
  183. this.blockRequests.delete(blockId);
  184. }
  185. })());
  186. }
  187. }
  188. this.blockIdsToFetch.clear();
  189. }
  190. }
  191. /**
  192. *
  193. * @param {Set} blockIds
  194. * @returns {BlockGroup[]}
  195. */
  196. groupBlocks(blockIds) {
  197. const sortedBlockIds = Array.from(blockIds).sort((a, b) => a - b);
  198. if (sortedBlockIds.length === 0) {
  199. return [];
  200. }
  201. let current = [];
  202. let lastBlockId = null;
  203. const groups = [];
  204. for (const blockId of sortedBlockIds) {
  205. if (lastBlockId === null || lastBlockId + 1 === blockId) {
  206. current.push(blockId);
  207. lastBlockId = blockId;
  208. }
  209. else {
  210. groups.push(new BlockGroup(current[0] * this.blockSize, current.length * this.blockSize, current));
  211. current = [blockId];
  212. lastBlockId = blockId;
  213. }
  214. }
  215. groups.push(new BlockGroup(current[0] * this.blockSize, current.length * this.blockSize, current));
  216. return groups;
  217. }
  218. /**
  219. *
  220. * @param {import("./basesource").Slice[]} slices
  221. * @param {Map} blocks
  222. */
  223. readSliceData(slices, blocks) {
  224. return slices.map((slice) => {
  225. let top = slice.offset + slice.length;
  226. if (this.fileSize !== null) {
  227. top = Math.min(this.fileSize, top);
  228. }
  229. const blockIdLow = Math.floor(slice.offset / this.blockSize);
  230. const blockIdHigh = Math.floor(top / this.blockSize);
  231. const sliceData = new ArrayBuffer(slice.length);
  232. const sliceView = new Uint8Array(sliceData);
  233. for (let blockId = blockIdLow; blockId <= blockIdHigh; ++blockId) {
  234. const block = blocks.get(blockId);
  235. const delta = block.offset - slice.offset;
  236. const topDelta = block.top - top;
  237. let blockInnerOffset = 0;
  238. let rangeInnerOffset = 0;
  239. let usedBlockLength;
  240. if (delta < 0) {
  241. blockInnerOffset = -delta;
  242. }
  243. else if (delta > 0) {
  244. rangeInnerOffset = delta;
  245. }
  246. if (topDelta < 0) {
  247. usedBlockLength = block.length - blockInnerOffset;
  248. }
  249. else {
  250. usedBlockLength = top - block.offset - blockInnerOffset;
  251. }
  252. const blockView = new Uint8Array(block.data, blockInnerOffset, usedBlockLength);
  253. sliceView.set(blockView, rangeInnerOffset);
  254. }
  255. return sliceData;
  256. });
  257. }
  258. }
  259. exports.BlockedSource = BlockedSource;
  260. //# sourceMappingURL=blockedsource.js.map