FileWriter.js 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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('underscore')
  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('../util/promises')
  23. class SizeLimitedStream extends Transform {
  24. constructor(options) {
  25. options.autoDestroy = true
  26. super(options)
  27. this.bytes = 0
  28. this.maxSizeBytes = options.maxSizeBytes
  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(callback) {
  56. if (callback == null) {
  57. callback = function () {}
  58. }
  59. return fs.mkdir(Settings.path.dumpFolder, function (error) {
  60. if (error != null && error.code !== 'EEXIST') {
  61. // Ignore error about already existing
  62. return callback(error)
  63. }
  64. return callback(null)
  65. })
  66. },
  67. writeLinesToDisk(identifier, lines, callback) {
  68. if (callback == null) {
  69. callback = function () {}
  70. }
  71. return FileWriter.writeContentToDisk(identifier, lines.join('\n'), callback)
  72. },
  73. writeContentToDisk(identifier, content, callback) {
  74. if (callback == null) {
  75. callback = function () {}
  76. }
  77. callback = _.once(callback)
  78. const fsPath = `${
  79. Settings.path.dumpFolder
  80. }/${identifier}_${crypto.randomUUID()}`
  81. return FileWriter.ensureDumpFolderExists(function (error) {
  82. if (error != null) {
  83. return callback(error)
  84. }
  85. return fs.writeFile(fsPath, content, function (error) {
  86. if (error != null) {
  87. return callback(error)
  88. }
  89. return callback(null, fsPath)
  90. })
  91. })
  92. },
  93. writeStreamToDisk(identifier, stream, options, callback) {
  94. if (typeof options === 'function') {
  95. callback = options
  96. options = {}
  97. }
  98. if (callback == null) {
  99. callback = function () {}
  100. }
  101. options = options || {}
  102. const fsPath = `${
  103. Settings.path.dumpFolder
  104. }/${identifier}_${crypto.randomUUID()}`
  105. stream.pause()
  106. FileWriter.ensureDumpFolderExists(function (error) {
  107. const writeStream = fs.createWriteStream(fsPath)
  108. if (error != null) {
  109. return callback(error)
  110. }
  111. stream.resume()
  112. const passThrough = new SizeLimitedStream({
  113. maxSizeBytes: options.maxSizeBytes,
  114. })
  115. // if writing fails, we want to consume the bytes from the source, to avoid leaks
  116. for (const evt of ['error', 'close']) {
  117. writeStream.on(evt, function () {
  118. passThrough.unpipe(writeStream)
  119. passThrough.resume()
  120. })
  121. }
  122. pipeline(stream, passThrough, writeStream, function (err) {
  123. if (
  124. options.maxSizeBytes &&
  125. passThrough.bytes >= options.maxSizeBytes &&
  126. !(err instanceof FileTooLargeError)
  127. ) {
  128. err = new FileTooLargeError({
  129. message: 'stream size limit reached',
  130. info: { size: passThrough.bytes },
  131. }).withCause(err || {})
  132. }
  133. if (err) {
  134. OError.tag(
  135. err,
  136. '[writeStreamToDisk] something went wrong writing the stream to disk',
  137. {
  138. identifier,
  139. fsPath,
  140. }
  141. )
  142. return callback(err)
  143. }
  144. logger.debug(
  145. { identifier, fsPath },
  146. '[writeStreamToDisk] write stream finished'
  147. )
  148. callback(null, fsPath)
  149. })
  150. })
  151. },
  152. writeUrlToDisk(identifier, url, options, callback) {
  153. if (typeof options === 'function') {
  154. callback = options
  155. options = {}
  156. }
  157. if (callback == null) {
  158. callback = function () {}
  159. }
  160. options = options || {}
  161. callback = _.once(callback)
  162. const stream = request.get(url)
  163. stream.on('error', function (err) {
  164. logger.warn(
  165. { err, identifier, url },
  166. '[writeUrlToDisk] something went wrong with writing to disk'
  167. )
  168. callback(err)
  169. })
  170. stream.on('response', function (response) {
  171. if (response.statusCode >= 200 && response.statusCode < 300) {
  172. FileWriter.writeStreamToDisk(identifier, stream, options, callback)
  173. } else {
  174. const err = new Error(`bad response from url: ${response.statusCode}`)
  175. logger.warn({ err, identifier, url }, `[writeUrlToDisk] ${err.message}`)
  176. return callback(err)
  177. }
  178. })
  179. },
  180. }
  181. module.exports = FileWriter
  182. module.exports.promises = promisifyAll(FileWriter)
  183. module.exports.SizeLimitedStream = SizeLimitedStream