FSPersistorTests.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. const crypto = require('node:crypto')
  2. const { expect } = require('chai')
  3. const mockFs = require('mock-fs')
  4. const fs = require('node:fs')
  5. const fsPromises = require('node:fs/promises')
  6. const Path = require('node:path')
  7. const StreamPromises = require('node:stream/promises')
  8. const SandboxedModule = require('sandboxed-module')
  9. const Errors = require('../../src/Errors')
  10. const MODULE_PATH = '../../src/FSPersistor.js'
  11. describe('FSPersistorTests', function () {
  12. const localFiles = {
  13. '/uploads/info.txt': Buffer.from('This information is critical', {
  14. encoding: 'utf-8',
  15. }),
  16. '/uploads/other.txt': Buffer.from('Some other content', {
  17. encoding: 'utf-8',
  18. }),
  19. }
  20. const location = '/bucket'
  21. const files = {
  22. wombat: 'animals/wombat.tex',
  23. giraffe: 'animals/giraffe.tex',
  24. potato: 'vegetables/potato.tex',
  25. }
  26. const scenarios = [
  27. {
  28. description: 'default settings',
  29. settings: {},
  30. fsPath: key => Path.join(location, key.replaceAll('/', '_')),
  31. },
  32. {
  33. description: 'with useSubdirectories = true',
  34. settings: { useSubdirectories: true },
  35. fsPath: key => Path.join(location, key),
  36. },
  37. ]
  38. for (const scenario of scenarios) {
  39. describe(scenario.description, function () {
  40. let persistor
  41. beforeEach(function () {
  42. const FSPersistor = SandboxedModule.require(MODULE_PATH, {
  43. requires: {
  44. 'fs/promises': fsPromises,
  45. 'stream/promises': StreamPromises,
  46. './Errors': Errors,
  47. },
  48. })
  49. persistor = new FSPersistor(scenario.settings)
  50. })
  51. beforeEach(function () {
  52. mockFs({
  53. ...localFiles,
  54. '/not-a-dir':
  55. 'This regular file is meant to prevent using this path as a directory',
  56. '/directory/subdirectory': {},
  57. })
  58. })
  59. afterEach(function () {
  60. mockFs.restore()
  61. })
  62. describe('sendFile', function () {
  63. it('should copy the file', async function () {
  64. await persistor.sendFile(location, files.wombat, '/uploads/info.txt')
  65. const contents = await fsPromises.readFile(
  66. scenario.fsPath(files.wombat)
  67. )
  68. expect(contents.equals(localFiles['/uploads/info.txt'])).to.be.true
  69. })
  70. it('should return an error if the file cannot be stored', async function () {
  71. await expect(
  72. persistor.sendFile('/not-a-dir', files.wombat, '/uploads/info.txt')
  73. ).to.be.rejectedWith(Errors.WriteError)
  74. })
  75. })
  76. describe('sendStream', function () {
  77. let stream
  78. describe("when the file doesn't exist", function () {
  79. beforeEach(function () {
  80. stream = fs.createReadStream('/uploads/info.txt')
  81. })
  82. it('should write the stream to disk', async function () {
  83. await persistor.sendStream(location, files.wombat, stream)
  84. const contents = await fsPromises.readFile(
  85. scenario.fsPath(files.wombat)
  86. )
  87. expect(contents.equals(localFiles['/uploads/info.txt'])).to.be.true
  88. })
  89. it('should delete the temporary file', async function () {
  90. await persistor.sendStream(location, files.wombat, stream)
  91. const entries = await fsPromises.readdir(location)
  92. const tempDirs = entries.filter(dir => dir.startsWith('tmp-'))
  93. expect(tempDirs).to.be.empty
  94. })
  95. describe('on error', function () {
  96. beforeEach(async function () {
  97. await expect(
  98. persistor.sendStream('/not-a-dir', files.wombat, stream)
  99. ).to.be.rejectedWith(Errors.WriteError)
  100. })
  101. it('should not write the target file', async function () {
  102. await expect(fsPromises.access(scenario.fsPath(files.wombat))).to
  103. .be.rejected
  104. })
  105. it('should delete the temporary file', async function () {
  106. await persistor.sendStream(location, files.wombat, stream)
  107. const entries = await fsPromises.readdir(location)
  108. const tempDirs = entries.filter(dir => dir.startsWith('tmp-'))
  109. expect(tempDirs).to.be.empty
  110. })
  111. })
  112. describe('when the md5 hash matches', function () {
  113. it('should write the stream to disk', async function () {
  114. await persistor.sendStream(location, files.wombat, stream, {
  115. sourceMd5: md5(localFiles['/uploads/info.txt']),
  116. })
  117. const contents = await fsPromises.readFile(
  118. scenario.fsPath(files.wombat)
  119. )
  120. expect(contents.equals(localFiles['/uploads/info.txt'])).to.be
  121. .true
  122. })
  123. })
  124. describe('when the md5 hash does not match', function () {
  125. beforeEach(async function () {
  126. await expect(
  127. persistor.sendStream(location, files.wombat, stream, {
  128. sourceMd5: md5('wrong content'),
  129. })
  130. ).to.be.rejectedWith(Errors.WriteError)
  131. })
  132. it('should not write the target file', async function () {
  133. await expect(fsPromises.access(scenario.fsPath(files.wombat))).to
  134. .be.rejected
  135. })
  136. it('should delete the temporary file', async function () {
  137. await persistor.sendStream(location, files.wombat, stream)
  138. const entries = await fsPromises.readdir(location)
  139. const tempDirs = entries.filter(dir => dir.startsWith('tmp-'))
  140. expect(tempDirs).to.be.empty
  141. })
  142. })
  143. })
  144. describe('when the file already exists', function () {
  145. let stream
  146. beforeEach(async function () {
  147. await persistor.sendFile(
  148. location,
  149. files.wombat,
  150. '/uploads/info.txt'
  151. )
  152. stream = fs.createReadStream('/uploads/other.txt')
  153. })
  154. it('should write the stream to disk', async function () {
  155. await persistor.sendStream(location, files.wombat, stream)
  156. const contents = await fsPromises.readFile(
  157. scenario.fsPath(files.wombat)
  158. )
  159. expect(contents.equals(localFiles['/uploads/other.txt'])).to.be.true
  160. })
  161. it('should delete the temporary file', async function () {
  162. await persistor.sendStream(location, files.wombat, stream)
  163. const entries = await fsPromises.readdir(location)
  164. const tempDirs = entries.filter(dir => dir.startsWith('tmp-'))
  165. expect(tempDirs).to.be.empty
  166. })
  167. describe('on error', function () {
  168. beforeEach(async function () {
  169. await expect(
  170. persistor.sendStream('/not-a-dir', files.wombat, stream)
  171. ).to.be.rejectedWith(Errors.WriteError)
  172. })
  173. it('should not update the target file', async function () {
  174. const contents = await fsPromises.readFile(
  175. scenario.fsPath(files.wombat)
  176. )
  177. expect(contents.equals(localFiles['/uploads/info.txt'])).to.be
  178. .true
  179. })
  180. it('should delete the temporary file', async function () {
  181. await persistor.sendStream(location, files.wombat, stream)
  182. const entries = await fsPromises.readdir(location)
  183. const tempDirs = entries.filter(dir => dir.startsWith('tmp-'))
  184. expect(tempDirs).to.be.empty
  185. })
  186. })
  187. describe('when the md5 hash matches', function () {
  188. it('should write the stream to disk', async function () {
  189. await persistor.sendStream(location, files.wombat, stream, {
  190. sourceMd5: md5(localFiles['/uploads/other.txt']),
  191. })
  192. const contents = await fsPromises.readFile(
  193. scenario.fsPath(files.wombat)
  194. )
  195. expect(contents.equals(localFiles['/uploads/other.txt'])).to.be
  196. .true
  197. })
  198. })
  199. describe('when the md5 hash does not match', function () {
  200. beforeEach(async function () {
  201. await expect(
  202. persistor.sendStream(location, files.wombat, stream, {
  203. sourceMd5: md5('wrong content'),
  204. })
  205. ).to.be.rejectedWith(Errors.WriteError)
  206. })
  207. it('should not update the target file', async function () {
  208. const contents = await fsPromises.readFile(
  209. scenario.fsPath(files.wombat)
  210. )
  211. expect(contents.equals(localFiles['/uploads/info.txt'])).to.be
  212. .true
  213. })
  214. it('should delete the temporary file', async function () {
  215. await persistor.sendStream(location, files.wombat, stream)
  216. const entries = await fsPromises.readdir(location)
  217. const tempDirs = entries.filter(dir => dir.startsWith('tmp-'))
  218. expect(tempDirs).to.be.empty
  219. })
  220. })
  221. })
  222. })
  223. describe('getObjectStream', function () {
  224. beforeEach(async function () {
  225. await persistor.sendFile(location, files.wombat, '/uploads/info.txt')
  226. })
  227. it('should return a string with the object contents', async function () {
  228. const stream = await persistor.getObjectStream(location, files.wombat)
  229. const contents = await streamToBuffer(stream)
  230. expect(contents.equals(localFiles['/uploads/info.txt'])).to.be.true
  231. })
  232. it('should support ranges', async function () {
  233. const stream = await persistor.getObjectStream(
  234. location,
  235. files.wombat,
  236. {
  237. start: 5,
  238. end: 16,
  239. }
  240. )
  241. const contents = await streamToBuffer(stream)
  242. // end is inclusive in ranges, but exclusive in slice()
  243. expect(contents.equals(localFiles['/uploads/info.txt'].slice(5, 17)))
  244. .to.be.true
  245. })
  246. it('should give a NotFoundError if the file does not exist', async function () {
  247. await expect(
  248. persistor.getObjectStream(location, 'does-not-exist')
  249. ).to.be.rejectedWith(Errors.NotFoundError)
  250. })
  251. })
  252. describe('getObjectSize', function () {
  253. beforeEach(async function () {
  254. await persistor.sendFile(location, files.wombat, '/uploads/info.txt')
  255. })
  256. it('should return the file size', async function () {
  257. expect(
  258. await persistor.getObjectSize(location, files.wombat)
  259. ).to.equal(localFiles['/uploads/info.txt'].length)
  260. })
  261. it('should throw a NotFoundError if the file does not exist', async function () {
  262. await expect(
  263. persistor.getObjectSize(location, 'does-not-exist')
  264. ).to.be.rejectedWith(Errors.NotFoundError)
  265. })
  266. })
  267. describe('copyObject', function () {
  268. beforeEach(async function () {
  269. await persistor.sendFile(location, files.wombat, '/uploads/info.txt')
  270. })
  271. it('Should copy the file to the new location', async function () {
  272. await persistor.copyObject(location, files.wombat, files.potato)
  273. const contents = await fsPromises.readFile(
  274. scenario.fsPath(files.potato)
  275. )
  276. expect(contents.equals(localFiles['/uploads/info.txt'])).to.be.true
  277. })
  278. })
  279. describe('deleteObject', function () {
  280. beforeEach(async function () {
  281. await persistor.sendFile(location, files.wombat, '/uploads/info.txt')
  282. await fsPromises.access(scenario.fsPath(files.wombat))
  283. })
  284. it('should delete the file', async function () {
  285. await persistor.deleteObject(location, files.wombat)
  286. await expect(fsPromises.access(scenario.fsPath(files.wombat))).to.be
  287. .rejected
  288. })
  289. it("should ignore files that don't exist", async function () {
  290. await persistor.deleteObject(location, 'does-not-exist')
  291. })
  292. })
  293. describe('deleteDirectory', function () {
  294. beforeEach(async function () {
  295. for (const file of Object.values(files)) {
  296. await persistor.sendFile(location, file, '/uploads/info.txt')
  297. await fsPromises.access(scenario.fsPath(file))
  298. }
  299. })
  300. it('should delete all files under the directory', async function () {
  301. await persistor.deleteDirectory(location, 'animals')
  302. for (const file of [files.wombat, files.giraffe]) {
  303. await expect(fsPromises.access(scenario.fsPath(file))).to.be
  304. .rejected
  305. }
  306. })
  307. it('should not delete files under other directoris', async function () {
  308. await persistor.deleteDirectory(location, 'animals')
  309. await fsPromises.access(scenario.fsPath(files.potato))
  310. })
  311. it("should ignore directories that don't exist", async function () {
  312. await persistor.deleteDirectory(location, 'does-not-exist')
  313. for (const file of Object.values(files)) {
  314. await fsPromises.access(scenario.fsPath(file))
  315. }
  316. })
  317. })
  318. describe('checkIfObjectExists', function () {
  319. beforeEach(async function () {
  320. await persistor.sendFile(location, files.wombat, '/uploads/info.txt')
  321. })
  322. it('should return true for existing files', async function () {
  323. expect(
  324. await persistor.checkIfObjectExists(location, files.wombat)
  325. ).to.equal(true)
  326. })
  327. it('should return false for non-existing files', async function () {
  328. expect(
  329. await persistor.checkIfObjectExists(location, 'does-not-exist')
  330. ).to.equal(false)
  331. })
  332. })
  333. describe('directorySize', function () {
  334. beforeEach(async function () {
  335. for (const file of Object.values(files)) {
  336. await persistor.sendFile(location, file, '/uploads/info.txt')
  337. }
  338. })
  339. it('should sum directory files size', async function () {
  340. expect(await persistor.directorySize(location, 'animals')).to.equal(
  341. 2 * localFiles['/uploads/info.txt'].length
  342. )
  343. })
  344. it('should return 0 on non-existing directories', async function () {
  345. expect(
  346. await persistor.directorySize(location, 'does-not-exist')
  347. ).to.equal(0)
  348. })
  349. })
  350. })
  351. }
  352. })
  353. function md5(str) {
  354. return crypto.createHash('md5').update(str).digest('hex')
  355. }
  356. async function streamToBuffer(stream) {
  357. const chunks = []
  358. for await (const chunk of stream) {
  359. chunks.push(chunk)
  360. }
  361. return Buffer.concat(chunks)
  362. }