ranges.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. /*
  2. * This file is part of the storage node for the Joystream project.
  3. * Copyright (C) 2019 Joystream Contributors
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. 'use strict';
  19. const uuid = require('uuid');
  20. const stream_buf = require('stream-buffers');
  21. const debug = require('debug')('joystream:util:ranges');
  22. /*
  23. * Range parsing
  24. */
  25. /*
  26. * Parse a range string, e.g. '0-100' or '-100' or '0-'. Return the values
  27. * in an array of int or undefined (if not provided).
  28. */
  29. function _parse_range(range)
  30. {
  31. var matches = range.match(/^(\d+-\d+|\d+-|-\d+|\*)$/u);
  32. if (!matches) {
  33. throw new Error(`Not a valid range: ${range}`);
  34. }
  35. var vals = matches[1].split('-').map((v) => {
  36. return v === '*' || v === '' ? undefined : parseInt(v, 10);
  37. });
  38. if (vals[1] <= vals[0]) {
  39. throw new Error(`Invalid range: start "${vals[0]}" must be before end "${vals[1]}".`);
  40. }
  41. return [vals[0], vals[1]];
  42. }
  43. /*
  44. * Parse a range header value, e.g. unit=ranges, where ranges
  45. * are a comman separated list of individual ranges, and unit is any
  46. * custom unit string. If the unit (and equal sign) are not given, assume
  47. * 'bytes'.
  48. */
  49. function parse(range_str)
  50. {
  51. var res = {};
  52. debug('Parse range header value:', range_str);
  53. var matches = range_str.match(/^(([^\s]+)=)?((?:(?:\d+-\d+|-\d+|\d+-),?)+)$/u)
  54. if (!matches) {
  55. throw new Error(`Not a valid range header: ${range_str}`);
  56. }
  57. res.unit = matches[2] || 'bytes';
  58. res.range_str = matches[3];
  59. res.ranges = [];
  60. // Parse individual ranges
  61. var ranges = []
  62. res.range_str.split(',').forEach((range) => {
  63. ranges.push(_parse_range(range));
  64. });
  65. // Merge ranges into result.
  66. ranges.forEach((new_range) => {
  67. debug('Found range:', new_range);
  68. var is_merged = false;
  69. for (var i in res.ranges) {
  70. var old_range = res.ranges[i];
  71. // Skip if the new range is fully separate from the old range.
  72. if (old_range[1] + 1 < new_range[0] || new_range[1] + 1 < old_range[0]) {
  73. debug('Range does not overlap with', old_range);
  74. continue;
  75. }
  76. // If we know they're adjacent or overlapping, we construct the
  77. // merged range from the lower start and the higher end of both
  78. // ranges.
  79. var merged = [
  80. Math.min(old_range[0], new_range[0]),
  81. Math.max(old_range[1], new_range[1])
  82. ];
  83. res.ranges[i] = merged;
  84. is_merged = true;
  85. debug('Merged', new_range, 'into', old_range, 'as', merged);
  86. }
  87. if (!is_merged) {
  88. debug('Non-overlapping range!');
  89. res.ranges.push(new_range);
  90. }
  91. });
  92. // Finally, sort ranges
  93. res.ranges.sort((first, second) => {
  94. if (first[0] === second[0]) {
  95. // Should not happen due to merging.
  96. return 0;
  97. }
  98. return (first[0] < second[0]) ? -1 : 1;
  99. });
  100. debug('Result of parse is', res);
  101. return res;
  102. }
  103. /*
  104. * Async version of parse().
  105. */
  106. function parseAsync(range_str, cb)
  107. {
  108. try {
  109. return cb(parse(range_str));
  110. } catch (err) {
  111. return cb(null, err);
  112. }
  113. }
  114. /*
  115. * Range streaming
  116. */
  117. /*
  118. * The class writes parts specified in the options to the response. If no ranges
  119. * are specified, the entire stream is written. At the end, the given callback
  120. * is invoked - if an error occurred, it is invoked with an error parameter.
  121. *
  122. * Note that the range implementation can be optimized for streams that support
  123. * seeking.
  124. *
  125. * There's another optimization here for when sizes are given, which is possible
  126. * with file system based streams. We'll see how likely that's going to be in
  127. * future.
  128. */
  129. class RangeSender
  130. {
  131. constructor(response, stream, opts, end_callback)
  132. {
  133. // Options
  134. this.name = opts.name || 'content.bin';
  135. this.type = opts.type || 'application/octet-stream';
  136. this.size = opts.size;
  137. this.ranges = opts.ranges;
  138. this.download = opts.download || false;
  139. // Range handling related state.
  140. this.read_offset = 0; // Nothing read so far
  141. this.range_index = -1; // No range index yet.
  142. this.range_boundary = undefined; // Generate boundary when needed.
  143. // Event handlers & state
  144. this.handlers = {};
  145. this.opened = false;
  146. debug('RangeSender:', this);
  147. if (opts.ranges) {
  148. debug('Parsed ranges:', opts.ranges.ranges);
  149. }
  150. // Parameters
  151. this.response = response;
  152. this.stream = stream;
  153. this.opts = opts;
  154. this.end_callback = end_callback;
  155. }
  156. on_error(err)
  157. {
  158. // Assume hiding the actual error is best, and default to 404.
  159. debug('Error:', err);
  160. if (!this.response.headersSent) {
  161. this.response.status(err.code || 404).send({
  162. message: err.message || `File not found: ${this.name}`
  163. });
  164. }
  165. if (this.end_callback) {
  166. this.end_callback(err);
  167. }
  168. }
  169. on_end()
  170. {
  171. debug('End of stream.');
  172. this.response.end();
  173. if (this.end_callback) {
  174. this.end_callback();
  175. }
  176. }
  177. // **** No ranges
  178. on_open_no_range()
  179. {
  180. // File got opened, so we can set headers/status
  181. debug('Open succeeded:', this.name, this.type);
  182. this.opened = true;
  183. this.response.status(200);
  184. this.response.contentType(this.type);
  185. this.response.header('Accept-Ranges', 'bytes');
  186. this.response.header('Content-Transfer-Encoding', 'binary');
  187. if (this.download) {
  188. this.response.header('Content-Disposition', `attachment; filename="${this.name}"`);
  189. }
  190. else {
  191. this.response.header('Content-Disposition', 'inline');
  192. }
  193. if (this.size) {
  194. this.response.header('Content-Length', this.size);
  195. }
  196. }
  197. on_data_no_range(chunk)
  198. {
  199. if (!this.opened) {
  200. this.handlers['open']();
  201. }
  202. // As simple as it can be.
  203. this.response.write(Buffer.from(chunk, 'binary'));
  204. }
  205. // *** With ranges
  206. next_range_headers()
  207. {
  208. // Next range
  209. this.range_index += 1;
  210. if (this.range_index >= this.ranges.ranges.length) {
  211. debug('Cannot advance range index; we are done.');
  212. return undefined;
  213. }
  214. // Calculate this range's size.
  215. var range = this.ranges.ranges[this.range_index];
  216. var total_size;
  217. if (this.size) {
  218. total_size = this.size;
  219. }
  220. if (typeof range[0] === 'undefined') {
  221. range[0] = 0;
  222. }
  223. if (typeof range[1] === 'undefined') {
  224. if (this.size) {
  225. range[1] = total_size - 1;
  226. }
  227. }
  228. var send_size;
  229. if (typeof range[0] !== 'undefined' && typeof range[1] !== 'undefined') {
  230. send_size = range[1] - range[0] + 1;
  231. }
  232. // Write headers, but since we may be in a multipart situation, write them
  233. // explicitly to the stream.
  234. var start = (typeof range[0] === 'undefined') ? '' : `${range[0]}`;
  235. var end = (typeof range[1] === 'undefined') ? '' : `${range[1]}`;
  236. var size_str;
  237. if (total_size) {
  238. size_str = `${total_size}`;
  239. }
  240. else {
  241. size_str = '*';
  242. }
  243. var ret = {
  244. 'Content-Range': `bytes ${start}-${end}/${size_str}`,
  245. 'Content-Type': `${this.type}`,
  246. };
  247. if (send_size) {
  248. ret['Content-Length'] = `${send_size}`;
  249. }
  250. return ret;
  251. }
  252. next_range()
  253. {
  254. if (this.ranges.ranges.length == 1) {
  255. debug('Cannot start new range; only one requested.');
  256. this.stream.off('data', this.handlers['data']);
  257. return false;
  258. }
  259. var headers = this.next_range_headers();
  260. if (headers) {
  261. var header_buf = new stream_buf.WritableStreamBuffer();
  262. // We start a range with a boundary.
  263. header_buf.write(`\r\n--${this.range_boundary}\r\n`);
  264. // The we write the range headers.
  265. for (var header in headers) {
  266. header_buf.write(`${header}: ${headers[header]}\r\n`);
  267. }
  268. header_buf.write('\r\n');
  269. this.response.write(header_buf.getContents());
  270. debug('New range started.');
  271. return true;
  272. }
  273. // No headers means we're finishing the last range.
  274. this.response.write(`\r\n--${this.range_boundary}--\r\n`);
  275. debug('End of ranges sent.');
  276. this.stream.off('data', this.handlers['data']);
  277. return false;
  278. }
  279. on_open_ranges()
  280. {
  281. // File got opened, so we can set headers/status
  282. debug('Open succeeded:', this.name, this.type);
  283. this.opened = true;
  284. this.response.header('Accept-Ranges', 'bytes');
  285. this.response.header('Content-Transfer-Encoding', 'binary');
  286. this.response.header('Content-Disposition', 'inline');
  287. // For single ranges, the content length should be the size of the
  288. // range. For multiple ranges, we don't send a content length
  289. // header.
  290. //
  291. // Similarly, the type is different whether or not there is more than
  292. // one range.
  293. if (this.ranges.ranges.length == 1) {
  294. this.response.writeHead(206, 'Partial Content', this.next_range_headers());
  295. }
  296. else {
  297. this.range_boundary = uuid.v4();
  298. var headers = {
  299. 'Content-Type': `multipart/byteranges; boundary=${this.range_boundary}`,
  300. };
  301. this.response.writeHead(206, 'Partial Content', headers);
  302. this.next_range();
  303. }
  304. }
  305. on_data_ranges(chunk)
  306. {
  307. if (!this.opened) {
  308. this.handlers['open']();
  309. }
  310. // Crap, node.js streams are stupid. No guarantee for seek support. Sure,
  311. // that makes node.js easier to implement, but offloads everything onto the
  312. // application developer.
  313. //
  314. // So, we skip chunks until our read position is within the range we want to
  315. // send at the moment. We're relying on ranges being in-order, which this
  316. // file's parser luckily (?) provides.
  317. //
  318. // The simplest optimization would be at ever range start to seek() to the
  319. // start.
  320. var chunk_range = [this.read_offset, this.read_offset + chunk.length - 1];
  321. debug('= Got chunk with byte range', chunk_range);
  322. while (true) {
  323. var req_range = this.ranges.ranges[this.range_index];
  324. if (!req_range) {
  325. break;
  326. }
  327. debug('Current requested range is', req_range);
  328. if (!req_range[1]) {
  329. req_range = [req_range[0], Number.MAX_SAFE_INTEGER];
  330. debug('Treating as', req_range);
  331. }
  332. // No overlap in the chunk and requested range; don't write.
  333. if (chunk_range[1] < req_range[0] || chunk_range[0] > req_range[1]) {
  334. debug('Ignoring chunk; it is out of range.');
  335. break;
  336. }
  337. // Since there is overlap, find the segment that's entirely within the
  338. // chunk.
  339. var segment = [
  340. Math.max(chunk_range[0], req_range[0]),
  341. Math.min(chunk_range[1], req_range[1]),
  342. ];
  343. debug('Segment to send within chunk is', segment);
  344. // Normalize the segment to a chunk offset
  345. var start = segment[0] - this.read_offset;
  346. var end = segment[1] - this.read_offset;
  347. var len = end - start + 1;
  348. debug('Offsets into buffer are', [start, end], 'with length', len);
  349. // Write the slice that we want to write. We first create a buffer from the
  350. // chunk. Then we slice a new buffer from the same underlying ArrayBuffer,
  351. // starting at the original buffer's offset, further offset by the segment
  352. // start. The segment length bounds the end of our slice.
  353. var buf = Buffer.from(chunk, 'binary');
  354. this.response.write(Buffer.from(buf.buffer, buf.byteOffset + start, len));
  355. // If the requested range is finished, we should start the next one.
  356. if (req_range[1] > chunk_range[1]) {
  357. debug('Chunk is finished, but the requested range is missing bytes.');
  358. break;
  359. }
  360. if (req_range[1] <= chunk_range[1]) {
  361. debug('Range is finished.');
  362. if (!this.next_range(segment)) {
  363. break;
  364. }
  365. }
  366. }
  367. // Update read offset when chunk is finished.
  368. this.read_offset += chunk.length;
  369. }
  370. start()
  371. {
  372. // Before we start streaming, let's ensure our ranges don't contain any
  373. // without start - if they do, we nuke them all and treat this as a full
  374. // request.
  375. var nuke = false;
  376. if (this.ranges) {
  377. for (var i in this.ranges.ranges) {
  378. if (typeof this.ranges.ranges[i][0] === 'undefined') {
  379. nuke = true;
  380. break;
  381. }
  382. }
  383. }
  384. if (nuke) {
  385. this.ranges = undefined;
  386. }
  387. // Register callbacks. Store them in a handlers object so we can
  388. // keep the bound version around for stopping to listen to events.
  389. this.handlers['error'] = this.on_error.bind(this);
  390. this.handlers['end'] = this.on_end.bind(this);
  391. if (this.ranges) {
  392. debug('Preparing to handle ranges.');
  393. this.handlers['open'] = this.on_open_ranges.bind(this);
  394. this.handlers['data'] = this.on_data_ranges.bind(this);
  395. }
  396. else {
  397. debug('No ranges, just send the whole file.');
  398. this.handlers['open'] = this.on_open_no_range.bind(this);
  399. this.handlers['data'] = this.on_data_no_range.bind(this);
  400. }
  401. for (var handler in this.handlers) {
  402. this.stream.on(handler, this.handlers[handler]);
  403. }
  404. }
  405. }
  406. function send(response, stream, opts, end_callback)
  407. {
  408. var sender = new RangeSender(response, stream, opts, end_callback);
  409. sender.start();
  410. }
  411. /*
  412. * Exports
  413. */
  414. module.exports =
  415. {
  416. parse: parse,
  417. parseAsync: parseAsync,
  418. RangeSender: RangeSender,
  419. send: send,
  420. };