FSPersistor.js 9.0 KB

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