S3PersistorTests.js 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042
  1. const sinon = require('sinon')
  2. const chai = require('chai')
  3. const { expect } = chai
  4. const SandboxedModule = require('sandboxed-module')
  5. const Errors = require('../../src/Errors')
  6. const { EventEmitter } = require('node:events')
  7. const { Readable } = require('node:stream')
  8. const mockS3 = require('./S3ClientMock')
  9. const MODULE_PATH = '../../src/S3Persistor.js'
  10. describe('S3PersistorTests', function () {
  11. const defaultS3Key = 'frog'
  12. const defaultS3Secret = 'prince'
  13. const defaultS3Credentials = {
  14. credentials: {
  15. accessKeyId: defaultS3Key,
  16. secretAccessKey: defaultS3Secret,
  17. },
  18. }
  19. const filename = '/wombat/potato.tex'
  20. const bucket = 'womBucket'
  21. const key = 'monKey'
  22. const destKey = 'donKey'
  23. const objectSize = 5555
  24. const genericError = new Error('guru meditation error')
  25. const files = [
  26. { Key: 'llama', Size: 11 },
  27. { Key: 'hippo', Size: 22 },
  28. ]
  29. const filesSize = 33
  30. const md5 = 'ffffffff00000000ffffffff00000000'
  31. const redirectUrl = 'https://wombat.potato/giraffe'
  32. let Logger,
  33. Transform,
  34. PassThrough,
  35. S3,
  36. awsRequestPresigner,
  37. awsLibStorage,
  38. awsLibStorageUpload,
  39. abortSignal,
  40. Fs,
  41. ReadStream,
  42. Stream,
  43. StreamPromises,
  44. S3Persistor,
  45. S3NotFoundError,
  46. S3AccessDeniedError,
  47. FileNotFoundError,
  48. settings,
  49. Hash,
  50. crypto
  51. beforeEach(function () {
  52. settings = {
  53. secret: defaultS3Secret,
  54. key: defaultS3Key,
  55. partSize: 100 * 1024 * 1024,
  56. }
  57. Transform = class {
  58. once() {}
  59. }
  60. PassThrough = class {}
  61. Stream = {
  62. Transform,
  63. PassThrough,
  64. pipeline: sinon.stub().yields(),
  65. }
  66. StreamPromises = {
  67. pipeline: sinon.stub().resolves(),
  68. }
  69. ReadStream = new EventEmitter()
  70. FileNotFoundError = new Error('File not found')
  71. FileNotFoundError.code = 'ENOENT'
  72. Fs = {
  73. createReadStream: sinon.stub().returns(ReadStream),
  74. }
  75. S3NotFoundError = new Error('not found')
  76. S3NotFoundError.name = 'NoSuchKey'
  77. S3AccessDeniedError = new Error('access denied')
  78. S3AccessDeniedError.code = 'AccessDenied'
  79. S3 = mockS3()
  80. awsLibStorageUpload = sinon.stub().returns({
  81. done: sinon.stub().resolves(),
  82. })
  83. awsLibStorage = {
  84. Upload: awsLibStorageUpload,
  85. }
  86. awsRequestPresigner = {
  87. getSignedUrl: sinon.stub().resolves(redirectUrl),
  88. }
  89. Hash = {
  90. end: sinon.stub(),
  91. read: sinon.stub().returns(md5),
  92. setEncoding: sinon.stub(),
  93. }
  94. crypto = {
  95. createHash: sinon.stub().returns(Hash),
  96. }
  97. Logger = {
  98. warn: sinon.stub(),
  99. }
  100. abortSignal = sinon.stub()
  101. const AbortCtrl = sinon.stub().returns({
  102. signal: {},
  103. abort: abortSignal,
  104. })
  105. S3Persistor = new (SandboxedModule.require(MODULE_PATH, {
  106. requires: {
  107. '@aws-sdk/client-s3': S3,
  108. '@aws-sdk/lib-storage': awsLibStorage,
  109. '@aws-sdk/s3-request-presigner': awsRequestPresigner,
  110. '@overleaf/logger': Logger,
  111. '@aws-sdk/node-http-handler': {
  112. NodeHttpHandler: sinon.stub(),
  113. },
  114. './Errors': Errors,
  115. fs: Fs,
  116. stream: Stream,
  117. 'stream/promises': StreamPromises,
  118. crypto,
  119. },
  120. globals: { console, Buffer, AbortController: AbortCtrl },
  121. }).S3Persistor)(settings)
  122. })
  123. describe('getObjectStream', function () {
  124. describe('when called with valid parameters', function () {
  125. let stream
  126. beforeEach(async function () {
  127. S3.mockSend(S3.GetObjectCommand, {
  128. Body: Readable.from('content'),
  129. ContentEncoding: 'gzip',
  130. })
  131. stream = await S3Persistor.getObjectStream(bucket, key)
  132. })
  133. it('returns a PassThrough stream', function () {
  134. expect(stream).to.be.instanceOf(PassThrough)
  135. })
  136. it('fetches the right key from the right bucket', function () {
  137. S3.assertSendCalledWith(S3.GetObjectCommand, {
  138. Bucket: bucket,
  139. Key: key,
  140. })
  141. })
  142. it('pipes the stream through the meter', async function () {
  143. expect(Stream.pipeline).to.have.been.calledWith(
  144. sinon.match.instanceOf(Readable),
  145. sinon.match.instanceOf(Transform),
  146. sinon.match.instanceOf(PassThrough)
  147. )
  148. })
  149. it('does not abort the request', function () {
  150. expect(abortSignal).not.to.have.been.called
  151. })
  152. })
  153. describe('when called with a byte range', function () {
  154. let stream
  155. beforeEach(async function () {
  156. S3.mockSend(S3.GetObjectCommand, {
  157. Body: Readable.from('this is a longer content'),
  158. ContentEncoding: 'gzip',
  159. })
  160. stream = await S3Persistor.getObjectStream(bucket, key, {
  161. start: 5,
  162. end: 10,
  163. })
  164. })
  165. it('returns a PassThrough stream', function () {
  166. expect(stream).to.be.instanceOf(Stream.PassThrough)
  167. })
  168. it('passes the byte range on to S3', function () {
  169. S3.assertSendCalledWith(S3.GetObjectCommand, {
  170. Bucket: bucket,
  171. Key: key,
  172. Range: 'bytes=5-10',
  173. })
  174. })
  175. })
  176. describe('when streaming fails', function () {
  177. let stream
  178. beforeEach(async function () {
  179. S3.mockSend(S3.GetObjectCommand, {
  180. Body: Readable.from('content'),
  181. ContentEncoding: 'gzip',
  182. })
  183. Stream.pipeline.yields(new Error())
  184. stream = await S3Persistor.getObjectStream(bucket, key)
  185. })
  186. it('returns a PassThrough stream', function () {
  187. expect(stream).to.be.instanceOf(Stream.PassThrough)
  188. })
  189. it('aborts the request', function () {
  190. expect(abortSignal).to.have.been.calledOnce
  191. })
  192. })
  193. describe('when there are alternative credentials', function () {
  194. let stream
  195. const alternativeSecret = 'giraffe'
  196. const alternativeKey = 'hippo'
  197. const alternativeS3Credentials = {
  198. credentials: {
  199. accessKeyId: alternativeKey,
  200. secretAccessKey: alternativeSecret,
  201. },
  202. }
  203. beforeEach(async function () {
  204. S3.mockSend(S3.GetObjectCommand, {
  205. Body: Readable.from('content'),
  206. ContentEncoding: 'gzip',
  207. })
  208. settings.bucketCreds = {}
  209. settings.bucketCreds[bucket] = {
  210. auth_key: alternativeKey,
  211. auth_secret: alternativeSecret,
  212. }
  213. stream = await S3Persistor.getObjectStream(bucket, key)
  214. })
  215. it('returns a PassThrough stream', function () {
  216. expect(stream).to.be.instanceOf(Stream.PassThrough)
  217. })
  218. it('sets the AWS client up with the alternative credentials', function () {
  219. expect(S3.S3Client).to.have.been.calledWith(alternativeS3Credentials)
  220. })
  221. it('fetches the right key from the right bucket', function () {
  222. S3.assertSendCalledWith(S3.GetObjectCommand, {
  223. Bucket: bucket,
  224. Key: key,
  225. })
  226. })
  227. it('uses the default credentials for an unknown bucket', async function () {
  228. stream = await S3Persistor.getObjectStream('anotherBucket', key)
  229. expect(S3.S3Client).to.have.been.calledTwice
  230. expect(S3.S3Client.firstCall).to.have.been.calledWith(
  231. alternativeS3Credentials
  232. )
  233. expect(S3.S3Client.secondCall).to.have.been.calledWith(
  234. defaultS3Credentials
  235. )
  236. })
  237. })
  238. describe('without hard-coded credentials', function () {
  239. it('uses the default provider chain', async function () {
  240. delete settings.key
  241. delete settings.secret
  242. S3.mockSend(S3.GetObjectCommand, {
  243. Body: Readable.from('content'),
  244. ContentEncoding: 'gzip',
  245. })
  246. await S3Persistor.getObjectStream(bucket, key)
  247. expect(S3.S3Client).to.have.been.calledOnce
  248. expect(S3.S3Client.args[0].credentials).to.not.exist
  249. })
  250. })
  251. describe('when given S3 options', function () {
  252. const httpOptions = { timeout: 2000 }
  253. const maxRetries = 2
  254. beforeEach(async function () {
  255. settings.httpOptions = httpOptions
  256. settings.maxRetries = maxRetries
  257. S3.mockSend(S3.GetObjectCommand, {
  258. Body: Readable.from('content'),
  259. ContentEncoding: 'gzip',
  260. })
  261. await S3Persistor.getObjectStream(bucket, key)
  262. })
  263. it('configures the S3 client appropriately', function () {
  264. expect(S3.S3Client).to.have.been.calledWithMatch({
  265. httpOptions,
  266. maxAttempts: maxRetries + 1,
  267. })
  268. })
  269. })
  270. describe("when the file doesn't exist", function () {
  271. let error, stream
  272. beforeEach(async function () {
  273. S3.mockSend(S3.GetObjectCommand, S3NotFoundError, { rejects: true })
  274. try {
  275. stream = await S3Persistor.getObjectStream(bucket, key)
  276. } catch (err) {
  277. error = err
  278. }
  279. })
  280. it('does not return a stream', function () {
  281. expect(stream).not.to.exist
  282. })
  283. it('throws a NotFoundError', function () {
  284. expect(error).to.be.an.instanceOf(Errors.NotFoundError)
  285. })
  286. it('wraps the error', function () {
  287. expect(error.cause).to.exist
  288. })
  289. it('stores the bucket and key in the error', function () {
  290. expect(error.info).to.include({ bucketName: bucket, key })
  291. })
  292. })
  293. describe("when the file doesn't exist -- SSEC", function () {
  294. let error, stream
  295. beforeEach(async function () {
  296. S3.mockSend(S3.GetObjectCommand, S3NotFoundError, { rejects: true })
  297. try {
  298. stream = await S3Persistor.getObjectStream(bucket, key)
  299. } catch (err) {
  300. error = err
  301. }
  302. })
  303. it('does not return a stream', function () {
  304. expect(stream).not.to.exist
  305. })
  306. it('throws a NotFoundError', function () {
  307. expect(error).to.be.an.instanceOf(Errors.NotFoundError)
  308. })
  309. it('wraps the error', function () {
  310. expect(error.cause).to.exist
  311. })
  312. it('stores the bucket and key in the error', function () {
  313. expect(error.info).to.include({ bucketName: bucket, key })
  314. })
  315. })
  316. describe('when access to the file is denied', function () {
  317. let error, stream
  318. beforeEach(async function () {
  319. S3.mockSend(S3.GetObjectCommand, S3AccessDeniedError, { rejects: true })
  320. try {
  321. stream = await S3Persistor.getObjectStream(bucket, key)
  322. } catch (err) {
  323. error = err
  324. }
  325. })
  326. it('does not return a stream', function () {
  327. expect(stream).not.to.exist
  328. })
  329. it('throws a NotFoundError', function () {
  330. expect(error).to.be.an.instanceOf(Errors.NotFoundError)
  331. })
  332. it('wraps the error', function () {
  333. expect(error.cause).to.equal(S3AccessDeniedError)
  334. })
  335. it('stores the bucket and key in the error', function () {
  336. expect(error.info).to.include({ bucketName: bucket, key })
  337. })
  338. })
  339. describe('when S3 encounters an unknown error', function () {
  340. let error, stream
  341. beforeEach(async function () {
  342. S3.mockSend(S3.GetObjectCommand, genericError, { rejects: true })
  343. try {
  344. stream = await S3Persistor.getObjectStream(bucket, key)
  345. } catch (err) {
  346. error = err
  347. }
  348. })
  349. it('does not return a stream', function () {
  350. expect(stream).not.to.exist
  351. })
  352. it('throws a ReadError', function () {
  353. expect(error).to.be.an.instanceOf(Errors.ReadError)
  354. })
  355. it('wraps the error', function () {
  356. expect(error.cause).to.exist
  357. })
  358. it('stores the bucket and key in the error', function () {
  359. expect(error.info).to.include({ bucketName: bucket, key })
  360. })
  361. })
  362. })
  363. describe('getRedirectUrl', function () {
  364. let signedUrl
  365. beforeEach(async function () {
  366. signedUrl = await S3Persistor.getRedirectUrl(bucket, key)
  367. })
  368. it('should request a signed URL', function () {
  369. expect(awsRequestPresigner.getSignedUrl).to.have.been.called
  370. })
  371. it('should return the url', function () {
  372. expect(signedUrl).to.equal(redirectUrl)
  373. })
  374. })
  375. describe('getObjectSize', function () {
  376. describe('when called with valid parameters', function () {
  377. let size
  378. beforeEach(async function () {
  379. S3.mockSend(S3.HeadObjectCommand, { ContentLength: objectSize })
  380. size = await S3Persistor.getObjectSize(bucket, key)
  381. })
  382. it('should return the object size', function () {
  383. expect(size).to.equal(objectSize)
  384. })
  385. it('should pass the bucket and key to S3', function () {
  386. S3.assertSendCalledWith(S3.HeadObjectCommand, {
  387. Bucket: bucket,
  388. Key: key,
  389. })
  390. })
  391. })
  392. describe('when the object is not found', function () {
  393. let error
  394. beforeEach(async function () {
  395. S3.mockSend(S3.HeadObjectCommand, S3NotFoundError, { rejects: true })
  396. try {
  397. await S3Persistor.getObjectSize(bucket, key)
  398. } catch (err) {
  399. error = err
  400. }
  401. })
  402. it('should return a NotFoundError', function () {
  403. expect(error).to.be.an.instanceOf(Errors.NotFoundError)
  404. })
  405. it('should wrap the error', function () {
  406. expect(error.cause).to.equal(S3NotFoundError)
  407. })
  408. })
  409. describe('when S3 returns an error', function () {
  410. let error
  411. beforeEach(async function () {
  412. S3.mockSend(S3.HeadObjectCommand, genericError, { rejects: true })
  413. try {
  414. await S3Persistor.getObjectSize(bucket, key)
  415. } catch (err) {
  416. error = err
  417. }
  418. })
  419. it('should return a ReadError', function () {
  420. expect(error).to.be.an.instanceOf(Errors.ReadError)
  421. })
  422. it('should wrap the error', function () {
  423. expect(error.cause).to.equal(genericError)
  424. })
  425. })
  426. })
  427. describe('sendStream', function () {
  428. describe('with valid parameters', function () {
  429. beforeEach(async function () {
  430. await S3Persistor.sendStream(bucket, key, ReadStream)
  431. })
  432. it('should upload the stream in a single part', function () {
  433. expect(awsLibStorageUpload).to.have.been.calledWith({
  434. client: S3.s3ClientStub,
  435. params: {
  436. Bucket: bucket,
  437. Key: key,
  438. Body: sinon.match.instanceOf(Stream.Transform),
  439. },
  440. partSize: 100 * 1024 * 1024,
  441. })
  442. })
  443. it('should meter the stream', function () {
  444. expect(Stream.pipeline).to.have.been.calledWith(
  445. ReadStream,
  446. sinon.match.instanceOf(Stream.Transform)
  447. )
  448. })
  449. })
  450. describe('when a hash is supplied', function () {
  451. beforeEach(async function () {
  452. await S3Persistor.sendStream(bucket, key, ReadStream, {
  453. sourceMd5: 'aaaaaaaabbbbbbbbaaaaaaaabbbbbbbb',
  454. })
  455. })
  456. it('sends the hash in base64', function () {
  457. expect(awsLibStorageUpload).to.have.been.calledWith({
  458. client: S3.s3ClientStub,
  459. params: {
  460. Bucket: bucket,
  461. Key: key,
  462. Body: sinon.match.instanceOf(Transform),
  463. ContentMD5: 'qqqqqru7u7uqqqqqu7u7uw==',
  464. },
  465. partSize: 100 * 1024 * 1024,
  466. })
  467. })
  468. })
  469. describe('when metadata is supplied', function () {
  470. const contentType = 'text/csv'
  471. const contentEncoding = 'gzip'
  472. beforeEach(async function () {
  473. await S3Persistor.sendStream(bucket, key, ReadStream, {
  474. contentType,
  475. contentEncoding,
  476. })
  477. })
  478. it('sends the metadata to S3', function () {
  479. expect(awsLibStorageUpload).to.have.been.calledWith({
  480. client: S3.s3ClientStub,
  481. params: {
  482. Bucket: bucket,
  483. Key: key,
  484. Body: sinon.match.instanceOf(Transform),
  485. ContentType: contentType,
  486. ContentEncoding: contentEncoding,
  487. },
  488. partSize: 100 * 1024 * 1024,
  489. })
  490. })
  491. })
  492. describe('when the upload fails', function () {
  493. let error
  494. beforeEach(async function () {
  495. awsLibStorageUpload.rejects(genericError)
  496. try {
  497. await S3Persistor.sendStream(bucket, key, ReadStream)
  498. } catch (err) {
  499. error = err
  500. }
  501. })
  502. it('throws a WriteError', function () {
  503. expect(error).to.be.an.instanceOf(Errors.WriteError)
  504. })
  505. })
  506. })
  507. describe('sendFile', function () {
  508. describe('with valid parameters', function () {
  509. beforeEach(async function () {
  510. S3.s3ClientStub.send.resolves()
  511. await S3Persistor.sendFile(bucket, key, filename)
  512. })
  513. it('should create a read stream for the file', function () {
  514. expect(Fs.createReadStream).to.have.been.calledWith(filename)
  515. })
  516. it('should upload the stream', function () {
  517. expect(awsLibStorageUpload).to.have.been.calledWith({
  518. client: S3.s3ClientStub,
  519. params: {
  520. Bucket: bucket,
  521. Key: key,
  522. Body: sinon.match.instanceOf(Transform),
  523. },
  524. partSize: settings.partSize,
  525. })
  526. })
  527. })
  528. })
  529. describe('getObjectMd5Hash', function () {
  530. describe('when the etag is a valid md5 hash', function () {
  531. let hash
  532. beforeEach(async function () {
  533. S3.mockSend(S3.HeadObjectCommand, {
  534. ContentLength: objectSize,
  535. ETag: md5,
  536. })
  537. hash = await S3Persistor.getObjectMd5Hash(bucket, key)
  538. })
  539. it('should return the object hash', function () {
  540. expect(hash).to.equal(md5)
  541. })
  542. it('should get the hash from the object metadata', function () {
  543. S3.assertSendCalledWith(S3.HeadObjectCommand, {
  544. Bucket: bucket,
  545. Key: key,
  546. })
  547. })
  548. it('should not download the object', function () {
  549. S3.assertSendNotCalledWith(S3.GetObjectCommand)
  550. })
  551. })
  552. describe("when the etag isn't a valid md5 hash", function () {
  553. let hash
  554. beforeEach(async function () {
  555. S3.mockSend(S3.GetObjectCommand, {
  556. ContentLength: objectSize,
  557. ETag: md5,
  558. })
  559. S3.mockSend(S3.HeadObjectCommand, {
  560. ETag: 'somethingthatisntanmd5',
  561. Bucket: bucket,
  562. Key: key,
  563. })
  564. hash = await S3Persistor.getObjectMd5Hash(bucket, key)
  565. })
  566. it('should re-fetch the file to verify it', function () {
  567. S3.assertSendCalledWith(S3.GetObjectCommand, {
  568. Bucket: bucket,
  569. Key: key,
  570. })
  571. })
  572. it('should calculate the md5 hash from the file', function () {
  573. expect(Hash.read).to.have.been.called
  574. })
  575. it('should return the md5 hash', function () {
  576. expect(hash).to.equal(md5)
  577. })
  578. })
  579. })
  580. describe('copyObject', function () {
  581. describe('with valid parameters', function () {
  582. beforeEach(async function () {
  583. S3.mockSend(S3.CopyObjectCommand)
  584. await S3Persistor.copyObject(bucket, key, destKey)
  585. })
  586. it('should copy the object', function () {
  587. S3.assertSendCalledWith(S3.CopyObjectCommand, {
  588. Bucket: bucket,
  589. Key: destKey,
  590. CopySource: `/${bucket}/${key}`,
  591. })
  592. })
  593. })
  594. describe('when the file does not exist', function () {
  595. let error
  596. beforeEach(async function () {
  597. S3.mockSend(S3.CopyObjectCommand, S3NotFoundError, { rejects: true })
  598. try {
  599. await S3Persistor.copyObject(bucket, key, destKey)
  600. } catch (err) {
  601. error = err
  602. }
  603. })
  604. it('should throw a NotFoundError', function () {
  605. expect(error).to.be.an.instanceOf(Errors.NotFoundError)
  606. })
  607. })
  608. })
  609. describe('deleteObject', function () {
  610. describe('with valid parameters', function () {
  611. beforeEach(async function () {
  612. S3.mockSend(S3.DeleteObjectCommand)
  613. await S3Persistor.deleteObject(bucket, key)
  614. })
  615. it('should delete the object', function () {
  616. S3.assertSendCalledWith(S3.DeleteObjectCommand, {
  617. Bucket: bucket,
  618. Key: key,
  619. })
  620. })
  621. })
  622. })
  623. describe('deleteDirectory', function () {
  624. describe('with valid parameters', function () {
  625. beforeEach(async function () {
  626. S3.mockSend(S3.ListObjectsV2Command, { Contents: files })
  627. await S3Persistor.deleteDirectory(bucket, key)
  628. })
  629. it('should list the objects in the directory', function () {
  630. S3.assertSendCalledWith(S3.ListObjectsV2Command, {
  631. Bucket: bucket,
  632. Prefix: key,
  633. })
  634. })
  635. it('should delete the objects using their keys', function () {
  636. S3.s3ClientStub.send.withArgs(new S3.DeleteObjectsCommand()).resolves()
  637. S3.assertSendCalledWith(
  638. S3.DeleteObjectsCommand,
  639. {
  640. Bucket: bucket,
  641. Delete: {
  642. Objects: [{ Key: 'llama' }, { Key: 'hippo' }],
  643. Quiet: true,
  644. },
  645. },
  646. 1
  647. )
  648. })
  649. })
  650. describe('when there are no files', function () {
  651. beforeEach(async function () {
  652. S3.mockSend(S3.ListObjectsV2Command, { Contents: [] })
  653. await S3Persistor.deleteDirectory(bucket, key)
  654. })
  655. it('should list the objects in the directory', function () {
  656. S3.assertSendCalledWith(S3.ListObjectsV2Command, {
  657. Bucket: bucket,
  658. Prefix: key,
  659. })
  660. })
  661. it('should not try to delete any objects', function () {
  662. S3.assertSendNotCalledWith(S3.DeleteObjectsCommand)
  663. })
  664. })
  665. describe('when there are more files available', function () {
  666. const continuationToken = 'wombat'
  667. beforeEach(async function () {
  668. S3.mockSend(
  669. S3.ListObjectsV2Command,
  670. {
  671. Contents: files,
  672. IsTruncated: true,
  673. NextContinuationToken: continuationToken,
  674. },
  675. {
  676. nextResponses: [{ Contents: [{ Key: 'last-file', Size: 33 }] }],
  677. }
  678. )
  679. S3.mockSend(S3.DeleteObjectsCommand)
  680. return S3Persistor.deleteDirectory(bucket, key)
  681. })
  682. it('should list the objects a second time, with a continuation token', function () {
  683. S3.assertSendCallCount(S3.ListObjectsV2Command, 2)
  684. expect(S3.s3ClientStub.send.firstCall.args[0].payload).to.deep.equal({
  685. Bucket: bucket,
  686. Prefix: key,
  687. })
  688. expect(S3.s3ClientStub.send.thirdCall.args[0].payload).to.deep.equal({
  689. Bucket: bucket,
  690. Prefix: key,
  691. ContinuationToken: continuationToken,
  692. })
  693. })
  694. it('should delete both sets of files', function () {
  695. S3.assertSendCallCount(S3.DeleteObjectsCommand, 2)
  696. })
  697. })
  698. describe('when there is an error listing the objects', function () {
  699. let error
  700. beforeEach(async function () {
  701. S3.mockSend(S3.ListObjectsV2Command, genericError, { rejects: true })
  702. try {
  703. await S3Persistor.deleteDirectory(bucket, key)
  704. } catch (err) {
  705. error = err
  706. }
  707. })
  708. it('should generate a ReadError', function () {
  709. expect(error).to.be.an.instanceOf(Errors.ReadError)
  710. })
  711. it('should wrap the error', function () {
  712. expect(error.cause).to.equal(genericError)
  713. })
  714. it('should not try to delete any objects', function () {
  715. // call count should be 1, only the ListObjectsV2Command tested above
  716. expect(S3.s3ClientStub.send.callCount).to.equal(1)
  717. })
  718. })
  719. describe('when there is an error deleting the objects', function () {
  720. let error
  721. beforeEach(async function () {
  722. S3.mockSend(S3.ListObjectsV2Command, { Contents: files })
  723. S3.mockSend(S3.DeleteObjectsCommand, genericError, { rejects: true })
  724. try {
  725. await S3Persistor.deleteDirectory(bucket, key)
  726. } catch (err) {
  727. error = err
  728. }
  729. })
  730. it('should generate a WriteError', function () {
  731. expect(error).to.be.an.instanceOf(Errors.WriteError)
  732. })
  733. it('should wrap the error', function () {
  734. expect(error.cause).to.equal(genericError)
  735. })
  736. })
  737. })
  738. describe('directorySize', function () {
  739. describe('with valid parameters', function () {
  740. let size
  741. beforeEach(async function () {
  742. S3.mockSend(S3.ListObjectsV2Command, { Contents: files })
  743. size = await S3Persistor.directorySize(bucket, key)
  744. })
  745. it('should list the objects in the directory', function () {
  746. S3.assertSendCalledWith(S3.ListObjectsV2Command, {
  747. Bucket: bucket,
  748. Prefix: key,
  749. })
  750. })
  751. it('should return the directory size', function () {
  752. expect(size).to.equal(filesSize)
  753. })
  754. })
  755. describe('when there are no files', function () {
  756. let size
  757. beforeEach(async function () {
  758. S3.mockSend(S3.ListObjectsV2Command, { Contents: [] })
  759. size = await S3Persistor.directorySize(bucket, key)
  760. })
  761. it('should list the objects in the directory', function () {
  762. S3.assertSendCalledWith(S3.ListObjectsV2Command, {
  763. Bucket: bucket,
  764. Prefix: key,
  765. })
  766. })
  767. it('should return zero', function () {
  768. expect(size).to.equal(0)
  769. })
  770. })
  771. describe('when there are more files available', function () {
  772. const continuationToken = 'wombat'
  773. let size
  774. beforeEach(async function () {
  775. S3.mockSend(
  776. S3.ListObjectsV2Command,
  777. {
  778. Contents: files,
  779. IsTruncated: true,
  780. NextContinuationToken: continuationToken,
  781. },
  782. {
  783. nextResponses: [{ Contents: [{ Key: 'last-file', Size: 33 }] }],
  784. }
  785. )
  786. size = await S3Persistor.directorySize(bucket, key)
  787. })
  788. it('should list the objects a second time, with a continuation token', function () {
  789. S3.assertSendCallCount(S3.ListObjectsV2Command, 2)
  790. expect(S3.s3ClientStub.send.firstCall.args[0].payload).to.deep.equal({
  791. Bucket: bucket,
  792. Prefix: key,
  793. })
  794. expect(S3.s3ClientStub.send.secondCall.args[0].payload).to.deep.equal({
  795. Bucket: bucket,
  796. Prefix: key,
  797. ContinuationToken: continuationToken,
  798. })
  799. })
  800. it('should return the size of both sets of files', function () {
  801. expect(size).to.equal(filesSize * 2)
  802. })
  803. })
  804. describe('when there is an error listing the objects', function () {
  805. let error
  806. beforeEach(async function () {
  807. S3.mockSend(S3.ListObjectsV2Command, genericError, { rejects: true })
  808. try {
  809. await S3Persistor.directorySize(bucket, key)
  810. } catch (err) {
  811. error = err
  812. }
  813. })
  814. it('should generate a ReadError', function () {
  815. expect(error).to.be.an.instanceOf(Errors.ReadError)
  816. })
  817. it('should wrap the error', function () {
  818. expect(error.cause).to.equal(genericError)
  819. })
  820. })
  821. })
  822. describe('checkIfObjectExists', function () {
  823. describe('when the file exists', function () {
  824. let exists
  825. beforeEach(async function () {
  826. S3.mockSend(S3.HeadObjectCommand, { ContentLength: objectSize })
  827. exists = await S3Persistor.checkIfObjectExists(bucket, key)
  828. })
  829. it('should get the object header', function () {
  830. S3.assertSendCalledWith(S3.HeadObjectCommand, {
  831. Bucket: bucket,
  832. Key: key,
  833. })
  834. })
  835. it('should return that the file exists', function () {
  836. expect(exists).to.equal(true)
  837. })
  838. })
  839. describe('when the file does not exist', function () {
  840. let exists
  841. beforeEach(async function () {
  842. S3.mockSend(S3.HeadObjectCommand, S3NotFoundError, { rejects: true })
  843. S3.s3ClientStub.send.rejects(S3NotFoundError)
  844. exists = await S3Persistor.checkIfObjectExists(bucket, key)
  845. })
  846. it('should get the object header', function () {
  847. S3.assertSendCalledWith(S3.HeadObjectCommand, {
  848. Bucket: bucket,
  849. Key: key,
  850. })
  851. })
  852. it('should return that the file does not exist', function () {
  853. expect(exists).to.equal(false)
  854. })
  855. })
  856. describe('when there is an error', function () {
  857. let error
  858. beforeEach(async function () {
  859. S3.mockSend(S3.HeadObjectCommand, genericError, { rejects: true })
  860. try {
  861. await S3Persistor.checkIfObjectExists(bucket, key)
  862. } catch (err) {
  863. error = err
  864. }
  865. })
  866. it('should generate a ReadError', function () {
  867. expect(error).to.be.an.instanceOf(Errors.ReadError)
  868. })
  869. it('should wrap the upstream ReadError', function () {
  870. expect(error.cause).to.be.an.instanceOf(Errors.ReadError)
  871. })
  872. it('should eventually wrap the error', function () {
  873. expect(error.cause.cause).to.equal(genericError)
  874. })
  875. })
  876. })
  877. })