ranges.js 12 KB

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