ranges.js 13 KB

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