FileWriter.js 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. /* eslint-disable
  2. n/handle-callback-err,
  3. max-len,
  4. */
  5. // TODO: This file was created by bulk-decaffeinate.
  6. // Fix any style issues and re-enable lint.
  7. /*
  8. * decaffeinate suggestions:
  9. * DS102: Remove unnecessary code created because of implicit returns
  10. * DS207: Consider shorter variations of null checks
  11. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  12. */
  13. const fs = require('fs')
  14. const OError = require('@overleaf/o-error')
  15. const logger = require('@overleaf/logger')
  16. const crypto = require('crypto')
  17. const _ = require('lodash')
  18. const Settings = require('@overleaf/settings')
  19. const request = require('request')
  20. const { Transform, pipeline } = require('stream')
  21. const { FileTooLargeError } = require('../Features/Errors/Errors')
  22. const { promisifyAll } = require('@overleaf/promise-utils')
  23. class SizeLimitedStream extends Transform {
  24. constructor(options) {
  25. options.autoDestroy = true
  26. super(options)
  27. this.bytes = 0
  28. this.maxSizeBytes = options.maxSizeBytes || Settings.maxUploadSize
  29. this.drain = false
  30. this.on('error', () => {
  31. this.drain = true
  32. this.resume()
  33. })
  34. }
  35. _transform(chunk, encoding, done) {
  36. if (this.drain) {
  37. // mechanism to drain the source stream on error, to avoid leaks
  38. // we consume the rest of the incoming stream and don't push it anywhere
  39. return done()
  40. }
  41. this.bytes += chunk.length
  42. if (this.maxSizeBytes && this.bytes > this.maxSizeBytes) {
  43. return done(
  44. new FileTooLargeError({
  45. message: 'stream size limit reached',
  46. info: { size: this.bytes },
  47. })
  48. )
  49. }
  50. this.push(chunk)
  51. done()
  52. }
  53. }
  54. const FileWriter = {
  55. ensureDumpFolderExists() {
  56. fs.mkdirSync(Settings.path.dumpFolder, { recursive: true })
  57. },
  58. writeLinesToDisk(identifier, lines, callback) {
  59. if (callback == null) {
  60. callback = function () {}
  61. }
  62. return FileWriter.writeContentToDisk(identifier, lines.join('\n'), callback)
  63. },
  64. writeContentToDisk(identifier, content, callback) {
  65. if (callback == null) {
  66. callback = function () {}
  67. }
  68. const fsPath = `${
  69. Settings.path.dumpFolder
  70. }/${identifier}_${crypto.randomUUID()}`
  71. return fs.writeFile(fsPath, content, function (error) {
  72. if (error != null) {
  73. return callback(error)
  74. }
  75. return callback(null, fsPath)
  76. })
  77. },
  78. writeStreamToDisk(identifier, stream, options, callback) {
  79. if (typeof options === 'function') {
  80. callback = options
  81. options = {}
  82. }
  83. if (callback == null) {
  84. callback = function () {}
  85. }
  86. options = options || {}
  87. const fsPath = `${
  88. Settings.path.dumpFolder
  89. }/${identifier}_${crypto.randomUUID()}`
  90. const writeStream = fs.createWriteStream(fsPath)
  91. const passThrough = new SizeLimitedStream({
  92. maxSizeBytes: options.maxSizeBytes,
  93. })
  94. // if writing fails, we want to consume the bytes from the source, to avoid leaks
  95. for (const evt of ['error', 'close']) {
  96. writeStream.on(evt, function () {
  97. passThrough.unpipe(writeStream)
  98. passThrough.resume()
  99. })
  100. }
  101. pipeline(stream, passThrough, writeStream, function (err) {
  102. if (
  103. options.maxSizeBytes &&
  104. passThrough.bytes >= options.maxSizeBytes &&
  105. !(err instanceof FileTooLargeError)
  106. ) {
  107. err = new FileTooLargeError({
  108. message: 'stream size limit reached',
  109. info: { size: passThrough.bytes },
  110. }).withCause(err || {})
  111. }
  112. if (err) {
  113. OError.tag(
  114. err,
  115. '[writeStreamToDisk] something went wrong writing the stream to disk',
  116. {
  117. identifier,
  118. fsPath,
  119. }
  120. )
  121. return callback(err)
  122. }
  123. logger.debug(
  124. { identifier, fsPath },
  125. '[writeStreamToDisk] write stream finished'
  126. )
  127. callback(null, fsPath)
  128. })
  129. },
  130. writeUrlToDisk(identifier, url, options, callback) {
  131. if (typeof options === 'function') {
  132. callback = options
  133. options = {}
  134. }
  135. if (callback == null) {
  136. callback = function () {}
  137. }
  138. options = options || {}
  139. callback = _.once(callback)
  140. const stream = request.get(url)
  141. stream.on('error', function (err) {
  142. logger.warn(
  143. { err, identifier, url },
  144. '[writeUrlToDisk] something went wrong with writing to disk'
  145. )
  146. callback(err)
  147. })
  148. stream.on('response', function (response) {
  149. if (response.statusCode >= 200 && response.statusCode < 300) {
  150. FileWriter.writeStreamToDisk(identifier, stream, options, callback)
  151. } else {
  152. const err = new Error(`bad response from url: ${response.statusCode}`)
  153. logger.warn({ err, identifier, url }, `[writeUrlToDisk] ${err.message}`)
  154. return callback(err)
  155. }
  156. })
  157. },
  158. }
  159. module.exports = FileWriter
  160. module.exports.promises = promisifyAll(FileWriter, {
  161. without: ['ensureDumpFolderExists'],
  162. })
  163. module.exports.SizeLimitedStream = SizeLimitedStream