FSPersistorManager.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. const fs = require('fs')
  2. const glob = require('glob')
  3. const logger = require('logger-sharelatex')
  4. const path = require('path')
  5. const rimraf = require('rimraf')
  6. const Stream = require('stream')
  7. const { promisify, callbackify } = require('util')
  8. const LocalFileWriter = require('./LocalFileWriter').promises
  9. const { NotFoundError, ReadError, WriteError } = require('./Errors')
  10. const pipeline = promisify(Stream.pipeline)
  11. const fsUnlink = promisify(fs.unlink)
  12. const fsOpen = promisify(fs.open)
  13. const fsStat = promisify(fs.stat)
  14. const fsGlob = promisify(glob)
  15. const rmrf = promisify(rimraf)
  16. const filterName = key => key.replace(/\//g, '_')
  17. async function sendFile(location, target, source) {
  18. const filteredTarget = filterName(target)
  19. logger.log({ location, target: filteredTarget, source }, 'sending file')
  20. // actually copy the file (instead of moving it) to maintain consistent behaviour
  21. // between the different implementations
  22. try {
  23. const sourceStream = fs.createReadStream(source)
  24. const targetStream = fs.createWriteStream(`${location}/${filteredTarget}`)
  25. await pipeline(sourceStream, targetStream)
  26. } catch (err) {
  27. throw _wrapError(
  28. err,
  29. 'failed to copy the specified file',
  30. { location, target, source },
  31. WriteError
  32. )
  33. }
  34. }
  35. async function sendStream(location, target, sourceStream) {
  36. logger.log({ location, target }, 'sending file stream')
  37. const fsPath = await LocalFileWriter.writeStream(sourceStream)
  38. try {
  39. await sendFile(location, target, fsPath)
  40. } finally {
  41. await LocalFileWriter.deleteFile(fsPath)
  42. }
  43. }
  44. // opts may be {start: Number, end: Number}
  45. async function getFileStream(location, name, opts) {
  46. const filteredName = filterName(name)
  47. logger.log({ location, filteredName }, 'getting file')
  48. try {
  49. opts.fd = await fsOpen(`${location}/${filteredName}`, 'r')
  50. } catch (err) {
  51. logger.err({ err, location, filteredName: name }, 'Error reading from file')
  52. throw _wrapError(
  53. err,
  54. 'failed to open file for streaming',
  55. { location, filteredName, opts },
  56. ReadError
  57. )
  58. }
  59. return fs.createReadStream(null, opts)
  60. }
  61. async function getFileSize(location, filename) {
  62. const fullPath = path.join(location, filterName(filename))
  63. try {
  64. const stat = await fsStat(fullPath)
  65. return stat.size
  66. } catch (err) {
  67. logger.err({ err, location, filename }, 'failed to stat file')
  68. throw _wrapError(
  69. err,
  70. 'failed to stat file',
  71. { location, filename },
  72. ReadError
  73. )
  74. }
  75. }
  76. async function copyFile(location, fromName, toName) {
  77. const filteredFromName = filterName(fromName)
  78. const filteredToName = filterName(toName)
  79. logger.log({ location, filteredFromName, filteredToName }, 'copying file')
  80. try {
  81. const sourceStream = fs.createReadStream(`${location}/${filteredFromName}`)
  82. const targetStream = fs.createWriteStream(`${location}/${filteredToName}`)
  83. await pipeline(sourceStream, targetStream)
  84. } catch (err) {
  85. throw _wrapError(
  86. err,
  87. 'failed to copy file',
  88. { location, filteredFromName, filteredToName },
  89. WriteError
  90. )
  91. }
  92. }
  93. async function deleteFile(location, name) {
  94. const filteredName = filterName(name)
  95. logger.log({ location, filteredName }, 'delete file')
  96. try {
  97. await fsUnlink(`${location}/${filteredName}`)
  98. } catch (err) {
  99. throw _wrapError(
  100. err,
  101. 'failed to delete file',
  102. { location, filteredName },
  103. WriteError
  104. )
  105. }
  106. }
  107. // this is only called internally for clean-up by `FileHandler` and isn't part of the external API
  108. async function deleteDirectory(location, name) {
  109. const filteredName = filterName(name.replace(/\/$/, ''))
  110. logger.log({ location, filteredName }, 'deleting directory')
  111. try {
  112. await rmrf(`${location}/${filteredName}`)
  113. } catch (err) {
  114. throw _wrapError(
  115. err,
  116. 'failed to delete directory',
  117. { location, filteredName },
  118. WriteError
  119. )
  120. }
  121. }
  122. async function checkIfFileExists(location, name) {
  123. const filteredName = filterName(name)
  124. try {
  125. const stat = await fsStat(`${location}/${filteredName}`)
  126. return !!stat
  127. } catch (err) {
  128. if (err.code === 'ENOENT') {
  129. return false
  130. }
  131. throw _wrapError(
  132. err,
  133. 'failed to stat file',
  134. { location, filteredName },
  135. ReadError
  136. )
  137. }
  138. }
  139. // note, does not recurse into subdirectories, as we use a flattened directory structure
  140. async function directorySize(location, name) {
  141. const filteredName = filterName(name.replace(/\/$/, ''))
  142. let size = 0
  143. try {
  144. const files = await fsGlob(`${location}/${filteredName}_*`)
  145. for (const file of files) {
  146. try {
  147. const stat = await fsStat(file)
  148. if (stat.isFile()) {
  149. size += stat.size
  150. }
  151. } catch (err) {
  152. // ignore files that may have just been deleted
  153. if (err.code !== 'ENOENT') {
  154. throw err
  155. }
  156. }
  157. }
  158. } catch (err) {
  159. throw _wrapError(
  160. err,
  161. 'failed to get directory size',
  162. { location, name },
  163. ReadError
  164. )
  165. }
  166. return size
  167. }
  168. function _wrapError(error, message, params, ErrorType) {
  169. if (error.code === 'ENOENT') {
  170. return new NotFoundError({
  171. message: 'no such file or directory',
  172. info: params
  173. }).withCause(error)
  174. } else {
  175. return new ErrorType({
  176. message: message,
  177. info: params
  178. }).withCause(error)
  179. }
  180. }
  181. module.exports = {
  182. sendFile: callbackify(sendFile),
  183. sendStream: callbackify(sendStream),
  184. getFileStream: callbackify(getFileStream),
  185. getFileSize: callbackify(getFileSize),
  186. copyFile: callbackify(copyFile),
  187. deleteFile: callbackify(deleteFile),
  188. deleteDirectory: callbackify(deleteDirectory),
  189. checkIfFileExists: callbackify(checkIfFileExists),
  190. directorySize: callbackify(directorySize),
  191. promises: {
  192. sendFile,
  193. sendStream,
  194. getFileStream,
  195. getFileSize,
  196. copyFile,
  197. deleteFile,
  198. deleteDirectory,
  199. checkIfFileExists,
  200. directorySize
  201. }
  202. }