FSPersistor.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. const crypto = require('crypto')
  2. const fs = require('fs')
  3. const fsPromises = require('fs/promises')
  4. const globCallbacks = require('glob')
  5. const Path = require('path')
  6. const { PassThrough } = require('stream')
  7. const { pipeline } = require('stream/promises')
  8. const { promisify } = require('util')
  9. const AbstractPersistor = require('./AbstractPersistor')
  10. const { ReadError, WriteError, NotImplementedError } = require('./Errors')
  11. const PersistorHelper = require('./PersistorHelper')
  12. const glob = promisify(globCallbacks)
  13. module.exports = class FSPersistor extends AbstractPersistor {
  14. constructor(settings = {}) {
  15. super()
  16. this.useSubdirectories = Boolean(settings.useSubdirectories)
  17. }
  18. async sendFile(location, target, source) {
  19. // actually copy the file (instead of moving it) to maintain consistent behaviour
  20. // between the different implementations
  21. try {
  22. const sourceStream = fs.createReadStream(source)
  23. await this.sendStream(location, target, sourceStream)
  24. } catch (err) {
  25. throw PersistorHelper.wrapError(
  26. err,
  27. 'failed to copy the specified file',
  28. { location, target, source },
  29. WriteError
  30. )
  31. }
  32. }
  33. async sendStream(location, target, sourceStream, opts = {}) {
  34. if (opts.ifNoneMatch === '*') {
  35. // The standard library only has fs.rename(), which does not support exclusive flags.
  36. // Refuse to act on this write operation.
  37. throw new NotImplementedError(
  38. 'Overwrite protection required by caller, but it is not available is FS backend. Configure GCS or S3 backend instead, get in touch with support for further information.'
  39. )
  40. }
  41. const targetPath = this._getFsPath(location, target)
  42. try {
  43. await this._ensureDirectoryExists(targetPath)
  44. const tempFilePath = await this._writeStreamToTempFile(
  45. location,
  46. sourceStream,
  47. opts
  48. )
  49. try {
  50. await fsPromises.rename(tempFilePath, targetPath)
  51. } finally {
  52. await this._cleanupTempFile(tempFilePath)
  53. }
  54. } catch (err) {
  55. throw PersistorHelper.wrapError(
  56. err,
  57. 'failed to write stream',
  58. { location, target, ifNoneMatch: opts.ifNoneMatch },
  59. WriteError
  60. )
  61. }
  62. }
  63. // opts may be {start: Number, end: Number}
  64. async getObjectStream(location, name, opts = {}) {
  65. const observer = new PersistorHelper.ObserverStream({
  66. metric: 'fs.ingress', // ingress to us from disk
  67. bucket: location,
  68. })
  69. const fsPath = this._getFsPath(location, name)
  70. try {
  71. opts.fd = await fsPromises.open(fsPath, 'r')
  72. } catch (err) {
  73. throw PersistorHelper.wrapError(
  74. err,
  75. 'failed to open file for streaming',
  76. { location, name, fsPath, opts },
  77. ReadError
  78. )
  79. }
  80. const stream = fs.createReadStream(null, opts)
  81. // Return a PassThrough stream with a minimal interface. It will buffer until the caller starts reading. It will emit errors from the source stream (Stream.pipeline passes errors along).
  82. const pass = new PassThrough()
  83. pipeline(stream, observer, pass).catch(() => {})
  84. return pass
  85. }
  86. async getRedirectUrl() {
  87. // not implemented
  88. return null
  89. }
  90. async getObjectSize(location, filename) {
  91. const fsPath = this._getFsPath(location, filename)
  92. try {
  93. const stat = await fsPromises.stat(fsPath)
  94. return stat.size
  95. } catch (err) {
  96. throw PersistorHelper.wrapError(
  97. err,
  98. 'failed to stat file',
  99. { location, filename },
  100. ReadError
  101. )
  102. }
  103. }
  104. async getObjectMd5Hash(location, filename) {
  105. const fsPath = this._getFsPath(location, filename)
  106. try {
  107. const stream = fs.createReadStream(fsPath)
  108. const hash = await PersistorHelper.calculateStreamMd5(stream)
  109. return hash
  110. } catch (err) {
  111. throw new ReadError(
  112. 'unable to get md5 hash from file',
  113. { location, filename },
  114. err
  115. )
  116. }
  117. }
  118. async copyObject(location, source, target) {
  119. const sourceFsPath = this._getFsPath(location, source)
  120. const targetFsPath = this._getFsPath(location, target)
  121. try {
  122. await this._ensureDirectoryExists(targetFsPath)
  123. await fsPromises.copyFile(sourceFsPath, targetFsPath)
  124. } catch (err) {
  125. throw PersistorHelper.wrapError(
  126. err,
  127. 'failed to copy file',
  128. { location, source, target, sourceFsPath, targetFsPath },
  129. WriteError
  130. )
  131. }
  132. }
  133. async deleteObject(location, name) {
  134. const fsPath = this._getFsPath(location, name)
  135. try {
  136. // S3 doesn't give us a 404 when a file wasn't there to be deleted, so we
  137. // should be consistent here as well
  138. await fsPromises.rm(fsPath, { force: true })
  139. } catch (err) {
  140. throw PersistorHelper.wrapError(
  141. err,
  142. 'failed to delete file',
  143. { location, name, fsPath },
  144. WriteError
  145. )
  146. }
  147. }
  148. async deleteDirectory(location, name) {
  149. const fsPath = this._getFsPath(location, name)
  150. try {
  151. if (this.useSubdirectories) {
  152. await fsPromises.rm(fsPath, { recursive: true, force: true })
  153. } else {
  154. const files = await this._listDirectory(fsPath)
  155. for (const file of files) {
  156. await fsPromises.rm(file, { force: true })
  157. }
  158. }
  159. } catch (err) {
  160. throw PersistorHelper.wrapError(
  161. err,
  162. 'failed to delete directory',
  163. { location, name, fsPath },
  164. WriteError
  165. )
  166. }
  167. }
  168. async checkIfObjectExists(location, name) {
  169. const fsPath = this._getFsPath(location, name)
  170. try {
  171. const stat = await fsPromises.stat(fsPath)
  172. return !!stat
  173. } catch (err) {
  174. if (err.code === 'ENOENT') {
  175. return false
  176. }
  177. throw PersistorHelper.wrapError(
  178. err,
  179. 'failed to stat file',
  180. { location, name, fsPath },
  181. ReadError
  182. )
  183. }
  184. }
  185. // note, does not recurse into subdirectories, as we use a flattened directory structure
  186. async directorySize(location, name) {
  187. const fsPath = this._getFsPath(location, name)
  188. let size = 0
  189. try {
  190. const files = await this._listDirectory(fsPath)
  191. for (const file of files) {
  192. try {
  193. const stat = await fsPromises.stat(file)
  194. if (stat.isFile()) {
  195. size += stat.size
  196. }
  197. } catch (err) {
  198. // ignore files that may have just been deleted
  199. if (err.code !== 'ENOENT') {
  200. throw err
  201. }
  202. }
  203. }
  204. } catch (err) {
  205. throw PersistorHelper.wrapError(
  206. err,
  207. 'failed to get directory size',
  208. { location, name },
  209. ReadError
  210. )
  211. }
  212. return size
  213. }
  214. async _writeStreamToTempFile(location, stream, opts = {}) {
  215. const observerOptions = {
  216. metric: 'fs.egress', // egress from us to disk
  217. bucket: location,
  218. }
  219. const observer = new PersistorHelper.ObserverStream(observerOptions)
  220. const tempDirPath = await fsPromises.mkdtemp(Path.join(location, 'tmp-'))
  221. const tempFilePath = Path.join(tempDirPath, 'uploaded-file')
  222. const transforms = [observer]
  223. let md5Observer
  224. if (opts.sourceMd5) {
  225. md5Observer = createMd5Observer()
  226. transforms.push(md5Observer.transform)
  227. }
  228. try {
  229. const writeStream = fs.createWriteStream(tempFilePath)
  230. await pipeline(stream, ...transforms, writeStream)
  231. } catch (err) {
  232. await this._cleanupTempFile(tempFilePath)
  233. throw new WriteError(
  234. 'problem writing temp file locally',
  235. { tempFilePath },
  236. err
  237. )
  238. }
  239. if (opts.sourceMd5) {
  240. const actualMd5 = md5Observer.hash.digest('hex')
  241. if (actualMd5 !== opts.sourceMd5) {
  242. await this._cleanupTempFile(tempFilePath)
  243. throw new WriteError('md5 hash mismatch', {
  244. expectedMd5: opts.sourceMd5,
  245. actualMd5,
  246. })
  247. }
  248. }
  249. return tempFilePath
  250. }
  251. async _cleanupTempFile(tempFilePath) {
  252. const dirPath = Path.dirname(tempFilePath)
  253. await fsPromises.rm(dirPath, { force: true, recursive: true })
  254. }
  255. _getFsPath(location, key) {
  256. key = key.replace(/\/$/, '')
  257. if (!this.useSubdirectories) {
  258. key = key.replace(/\//g, '_')
  259. }
  260. return Path.join(location, key)
  261. }
  262. async _listDirectory(path) {
  263. if (this.useSubdirectories) {
  264. return await glob(Path.join(path, '**'))
  265. } else {
  266. return await glob(`${path}_*`)
  267. }
  268. }
  269. async _ensureDirectoryExists(path) {
  270. await fsPromises.mkdir(Path.dirname(path), { recursive: true })
  271. }
  272. }
  273. function createMd5Observer() {
  274. const hash = crypto.createHash('md5')
  275. async function* transform(chunks) {
  276. for await (const chunk of chunks) {
  277. hash.update(chunk)
  278. yield chunk
  279. }
  280. }
  281. return { hash, transform }
  282. }