FSPersistor.js 10 KB

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