GcsPersistorTests.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  1. const sinon = require('sinon')
  2. const chai = require('chai')
  3. const { expect } = chai
  4. const modulePath = '../../src/GcsPersistor.js'
  5. const SandboxedModule = require('sandboxed-module')
  6. const { ObjectId } = require('mongodb')
  7. const asyncPool = require('tiny-async-pool')
  8. const Errors = require('../../src/Errors')
  9. describe('GcsPersistorTests', function () {
  10. const filename = '/wombat/potato.tex'
  11. const bucket = 'womBucket'
  12. const key = 'monKey'
  13. const destKey = 'donKey'
  14. const genericError = new Error('guru meditation error')
  15. const filesSize = 33
  16. const md5 = 'ffffffff00000000ffffffff00000000'
  17. const WriteStream = 'writeStream'
  18. const redirectUrl = 'https://wombat.potato/giraffe'
  19. let Logger,
  20. Transform,
  21. Storage,
  22. Fs,
  23. GcsNotFoundError,
  24. ReadStream,
  25. Stream,
  26. GcsBucket,
  27. GcsFile,
  28. GcsPersistor,
  29. FileNotFoundError,
  30. Hash,
  31. Settings,
  32. crypto,
  33. files
  34. beforeEach(function () {
  35. Settings = {
  36. directoryKeyRegex: /^[0-9a-fA-F]{24}\/[0-9a-fA-F]{24}/,
  37. Metrics: {
  38. count: sinon.stub(),
  39. },
  40. }
  41. files = [
  42. {
  43. metadata: { size: 11, md5Hash: '/////wAAAAD/////AAAAAA==' },
  44. delete: sinon.stub(),
  45. },
  46. {
  47. metadata: { size: 22, md5Hash: '/////wAAAAD/////AAAAAA==' },
  48. delete: sinon.stub(),
  49. },
  50. ]
  51. ReadStream = {
  52. pipe: sinon.stub().returns('readStream'),
  53. on: sinon.stub(),
  54. removeListener: sinon.stub(),
  55. }
  56. ReadStream.on.withArgs('end').yields()
  57. ReadStream.on.withArgs('pipe').yields({
  58. unpipe: sinon.stub(),
  59. resume: sinon.stub(),
  60. on: sinon.stub(),
  61. })
  62. Transform = class {
  63. on(event, callback) {
  64. if (event === 'readable') {
  65. callback()
  66. }
  67. }
  68. once() {}
  69. removeListener() {}
  70. }
  71. Stream = {
  72. pipeline: sinon.stub().yields(),
  73. Transform: Transform,
  74. }
  75. GcsFile = {
  76. delete: sinon.stub().resolves(),
  77. createReadStream: sinon.stub().returns(ReadStream),
  78. getMetadata: sinon.stub().resolves([files[0].metadata]),
  79. createWriteStream: sinon.stub().returns(WriteStream),
  80. copy: sinon.stub().resolves(),
  81. exists: sinon.stub().resolves([true]),
  82. getSignedUrl: sinon.stub().resolves([redirectUrl]),
  83. }
  84. GcsBucket = {
  85. file: sinon.stub().returns(GcsFile),
  86. getFiles: sinon.stub().resolves([files]),
  87. }
  88. Storage = class {
  89. constructor() {
  90. this.interceptors = []
  91. }
  92. }
  93. Storage.prototype.bucket = sinon.stub().returns(GcsBucket)
  94. GcsNotFoundError = new Error('File not found')
  95. GcsNotFoundError.code = 404
  96. Fs = {
  97. createReadStream: sinon.stub().returns(ReadStream),
  98. }
  99. FileNotFoundError = new Error('File not found')
  100. FileNotFoundError.code = 'ENOENT'
  101. Hash = {
  102. end: sinon.stub(),
  103. read: sinon.stub().returns(md5),
  104. digest: sinon.stub().returns(md5),
  105. setEncoding: sinon.stub(),
  106. }
  107. crypto = {
  108. createHash: sinon.stub().returns(Hash),
  109. }
  110. Logger = {
  111. warn: sinon.stub(),
  112. }
  113. GcsPersistor = new (SandboxedModule.require(modulePath, {
  114. requires: {
  115. '@google-cloud/storage': { Storage },
  116. 'logger-sharelatex': Logger,
  117. 'tiny-async-pool': asyncPool,
  118. './Errors': Errors,
  119. fs: Fs,
  120. stream: Stream,
  121. crypto,
  122. },
  123. globals: { console, Buffer },
  124. }))(Settings)
  125. })
  126. describe('getObjectStream', function () {
  127. describe('when called with valid parameters', function () {
  128. let stream
  129. beforeEach(async function () {
  130. stream = await GcsPersistor.getObjectStream(bucket, key)
  131. })
  132. it('returns a metered stream', function () {
  133. expect(stream).to.be.instanceOf(Transform)
  134. })
  135. it('fetches the right key from the right bucket', function () {
  136. expect(Storage.prototype.bucket).to.have.been.calledWith(bucket)
  137. expect(GcsBucket.file).to.have.been.calledWith(key)
  138. expect(GcsFile.createReadStream).to.have.been.called
  139. })
  140. it('disables automatic decompression', function () {
  141. expect(GcsFile.createReadStream).to.have.been.calledWith({
  142. decompress: false,
  143. })
  144. })
  145. it('pipes the stream through the meter', function () {
  146. expect(ReadStream.pipe).to.have.been.calledWith(
  147. sinon.match.instanceOf(Transform)
  148. )
  149. })
  150. })
  151. describe('when called with a byte range', function () {
  152. let stream
  153. beforeEach(async function () {
  154. stream = await GcsPersistor.getObjectStream(bucket, key, {
  155. start: 5,
  156. end: 10,
  157. })
  158. })
  159. it('returns a metered stream', function () {
  160. expect(stream).to.be.instanceOf(Transform)
  161. })
  162. it('passes the byte range on to GCS', function () {
  163. expect(GcsFile.createReadStream).to.have.been.calledWith({
  164. decompress: false,
  165. start: 5,
  166. end: 10,
  167. })
  168. })
  169. })
  170. describe("when the file doesn't exist", function () {
  171. let error, stream
  172. beforeEach(async function () {
  173. Transform.prototype.on = sinon.stub()
  174. ReadStream.on.withArgs('error').yields(GcsNotFoundError)
  175. try {
  176. stream = await GcsPersistor.getObjectStream(bucket, key)
  177. } catch (e) {
  178. error = e
  179. }
  180. })
  181. it('does not return a stream', function () {
  182. expect(stream).not.to.exist
  183. })
  184. it('throws a NotFoundError', function () {
  185. expect(error).to.be.an.instanceOf(Errors.NotFoundError)
  186. })
  187. it('wraps the error', function () {
  188. expect(error.cause).to.exist
  189. })
  190. it('stores the bucket and key in the error', function () {
  191. expect(error.info).to.include({ bucketName: bucket, key: key })
  192. })
  193. })
  194. describe('when Gcs encounters an unkown error', function () {
  195. let error, stream
  196. beforeEach(async function () {
  197. Transform.prototype.on = sinon.stub()
  198. ReadStream.on.withArgs('error').yields(genericError)
  199. try {
  200. stream = await GcsPersistor.getObjectStream(bucket, key)
  201. } catch (err) {
  202. error = err
  203. }
  204. })
  205. it('does not return a stream', function () {
  206. expect(stream).not.to.exist
  207. })
  208. it('throws a ReadError', function () {
  209. expect(error).to.be.an.instanceOf(Errors.ReadError)
  210. })
  211. it('wraps the error', function () {
  212. expect(error.cause).to.exist
  213. })
  214. it('stores the bucket and key in the error', function () {
  215. expect(error.info).to.include({ bucketName: bucket, key: key })
  216. })
  217. })
  218. })
  219. describe('getRedirectUrl', function () {
  220. let signedUrl
  221. describe('with signed URLs', function () {
  222. beforeEach(async function () {
  223. signedUrl = await GcsPersistor.getRedirectUrl(bucket, key)
  224. })
  225. it('should request a signed URL', function () {
  226. expect(GcsFile.getSignedUrl).to.have.been.called
  227. })
  228. it('should return the url', function () {
  229. expect(signedUrl).to.equal(redirectUrl)
  230. })
  231. })
  232. describe('with unsigned URLs', function () {
  233. beforeEach(async function () {
  234. GcsPersistor.settings.unsignedUrls = true
  235. GcsPersistor.settings.endpoint = {
  236. apiScheme: 'http',
  237. apiEndpoint: 'custom.endpoint',
  238. }
  239. signedUrl = await GcsPersistor.getRedirectUrl(bucket, key)
  240. })
  241. it('should return a plain URL', function () {
  242. expect(signedUrl).to.equal(
  243. `http://custom.endpoint/download/storage/v1/b/${bucket}/o/${key}?alt=media`
  244. )
  245. })
  246. })
  247. })
  248. describe('getObjectSize', function () {
  249. describe('when called with valid parameters', function () {
  250. let size
  251. beforeEach(async function () {
  252. size = await GcsPersistor.getObjectSize(bucket, key)
  253. })
  254. it('should return the object size', function () {
  255. expect(size).to.equal(files[0].metadata.size)
  256. })
  257. it('should pass the bucket and key to GCS', function () {
  258. expect(Storage.prototype.bucket).to.have.been.calledWith(bucket)
  259. expect(GcsBucket.file).to.have.been.calledWith(key)
  260. expect(GcsFile.getMetadata).to.have.been.called
  261. })
  262. })
  263. describe('when the object is not found', function () {
  264. let error
  265. beforeEach(async function () {
  266. GcsFile.getMetadata = sinon.stub().rejects(GcsNotFoundError)
  267. try {
  268. await GcsPersistor.getObjectSize(bucket, key)
  269. } catch (err) {
  270. error = err
  271. }
  272. })
  273. it('should return a NotFoundError', function () {
  274. expect(error).to.be.an.instanceOf(Errors.NotFoundError)
  275. })
  276. it('should wrap the error', function () {
  277. expect(error.cause).to.equal(GcsNotFoundError)
  278. })
  279. })
  280. describe('when GCS returns an error', function () {
  281. let error
  282. beforeEach(async function () {
  283. GcsFile.getMetadata = sinon.stub().rejects(genericError)
  284. try {
  285. await GcsPersistor.getObjectSize(bucket, key)
  286. } catch (err) {
  287. error = err
  288. }
  289. })
  290. it('should return a ReadError', function () {
  291. expect(error).to.be.an.instanceOf(Errors.ReadError)
  292. })
  293. it('should wrap the error', function () {
  294. expect(error.cause).to.equal(genericError)
  295. })
  296. })
  297. })
  298. describe('sendStream', function () {
  299. describe('with valid parameters', function () {
  300. beforeEach(async function () {
  301. return GcsPersistor.sendStream(bucket, key, ReadStream)
  302. })
  303. it('should upload the stream', function () {
  304. expect(Storage.prototype.bucket).to.have.been.calledWith(bucket)
  305. expect(GcsBucket.file).to.have.been.calledWith(key)
  306. expect(GcsFile.createWriteStream).to.have.been.called
  307. })
  308. it('should not try to create a resumable upload', function () {
  309. expect(GcsFile.createWriteStream).to.have.been.calledWith({
  310. resumable: false,
  311. })
  312. })
  313. it('should meter the stream and pass it to GCS', function () {
  314. expect(Stream.pipeline).to.have.been.calledWith(
  315. ReadStream,
  316. sinon.match.instanceOf(Transform),
  317. WriteStream
  318. )
  319. })
  320. it('calculates the md5 hash of the file', function () {
  321. expect(Hash.digest).to.have.been.called
  322. })
  323. })
  324. describe('when a hash is supplied', function () {
  325. beforeEach(async function () {
  326. return GcsPersistor.sendStream(bucket, key, ReadStream, {
  327. sourceMd5: 'aaaaaaaabbbbbbbbaaaaaaaabbbbbbbb',
  328. })
  329. })
  330. it('should not calculate the md5 hash of the file', function () {
  331. expect(Hash.digest).not.to.have.been.called
  332. })
  333. it('sends the hash in base64', function () {
  334. expect(GcsFile.createWriteStream).to.have.been.calledWith({
  335. validation: 'md5',
  336. metadata: {
  337. md5Hash: 'qqqqqru7u7uqqqqqu7u7uw==',
  338. },
  339. resumable: false,
  340. })
  341. })
  342. it('does not fetch the md5 hash of the uploaded file', function () {
  343. expect(GcsFile.getMetadata).not.to.have.been.called
  344. })
  345. })
  346. describe('when metadata is supplied', function () {
  347. const contentType = 'text/csv'
  348. const contentEncoding = 'gzip'
  349. beforeEach(async function () {
  350. return GcsPersistor.sendStream(bucket, key, ReadStream, {
  351. contentType,
  352. contentEncoding,
  353. })
  354. })
  355. it('should send the metadata to GCS', function () {
  356. expect(GcsFile.createWriteStream).to.have.been.calledWith({
  357. metadata: { contentType, contentEncoding },
  358. resumable: false,
  359. })
  360. })
  361. })
  362. describe('when the upload fails', function () {
  363. let error
  364. beforeEach(async function () {
  365. Stream.pipeline
  366. .withArgs(
  367. ReadStream,
  368. sinon.match.instanceOf(Transform),
  369. WriteStream,
  370. sinon.match.any
  371. )
  372. .yields(genericError)
  373. try {
  374. await GcsPersistor.sendStream(bucket, key, ReadStream)
  375. } catch (err) {
  376. error = err
  377. }
  378. })
  379. it('throws a WriteError', function () {
  380. expect(error).to.be.an.instanceOf(Errors.WriteError)
  381. })
  382. it('wraps the error', function () {
  383. expect(error.cause).to.equal(genericError)
  384. })
  385. })
  386. })
  387. describe('sendFile', function () {
  388. describe('with valid parameters', function () {
  389. beforeEach(async function () {
  390. return GcsPersistor.sendFile(bucket, key, filename)
  391. })
  392. it('should create a read stream for the file', function () {
  393. expect(Fs.createReadStream).to.have.been.calledWith(filename)
  394. })
  395. it('should create a write stream', function () {
  396. expect(Storage.prototype.bucket).to.have.been.calledWith(bucket)
  397. expect(GcsBucket.file).to.have.been.calledWith(key)
  398. expect(GcsFile.createWriteStream).to.have.been.called
  399. })
  400. it('should upload the stream via the meter', function () {
  401. expect(Stream.pipeline).to.have.been.calledWith(
  402. ReadStream,
  403. sinon.match.instanceOf(Transform),
  404. WriteStream
  405. )
  406. })
  407. })
  408. })
  409. describe('copyObject', function () {
  410. const destinationFile = 'destFile'
  411. beforeEach(function () {
  412. GcsBucket.file.withArgs(destKey).returns(destinationFile)
  413. })
  414. describe('with valid parameters', function () {
  415. beforeEach(async function () {
  416. return GcsPersistor.copyObject(bucket, key, destKey)
  417. })
  418. it('should copy the object', function () {
  419. expect(Storage.prototype.bucket).to.have.been.calledWith(bucket)
  420. expect(GcsBucket.file).to.have.been.calledWith(key)
  421. expect(GcsFile.copy).to.have.been.calledWith(destinationFile)
  422. })
  423. })
  424. describe('when the file does not exist', function () {
  425. let error
  426. beforeEach(async function () {
  427. GcsFile.copy = sinon.stub().rejects(GcsNotFoundError)
  428. try {
  429. await GcsPersistor.copyObject(bucket, key, destKey)
  430. } catch (err) {
  431. error = err
  432. }
  433. })
  434. it('should throw a NotFoundError', function () {
  435. expect(error).to.be.an.instanceOf(Errors.NotFoundError)
  436. })
  437. })
  438. })
  439. describe('deleteObject', function () {
  440. describe('with valid parameters', function () {
  441. beforeEach(async function () {
  442. return GcsPersistor.deleteObject(bucket, key)
  443. })
  444. it('should delete the object', function () {
  445. expect(Storage.prototype.bucket).to.have.been.calledWith(bucket)
  446. expect(GcsBucket.file).to.have.been.calledWith(key)
  447. expect(GcsFile.delete).to.have.been.called
  448. })
  449. })
  450. describe('when the file does not exist', function () {
  451. let error
  452. beforeEach(async function () {
  453. GcsFile.delete = sinon.stub().rejects(GcsNotFoundError)
  454. try {
  455. await GcsPersistor.deleteObject(bucket, key)
  456. } catch (err) {
  457. error = err
  458. }
  459. })
  460. it('should not throw an error', function () {
  461. expect(error).not.to.exist
  462. })
  463. })
  464. })
  465. describe('deleteDirectory', function () {
  466. const directoryName = `${ObjectId()}/${ObjectId()}`
  467. describe('with valid parameters', function () {
  468. beforeEach(async function () {
  469. GcsBucket.getFiles = sinon.stub()
  470. // set up multiple paginated calls to getFiles
  471. GcsBucket.getFiles
  472. .withArgs({ directory: directoryName, autoPaginate: false })
  473. .resolves([['aaa', 'bbb'], 'call-1'])
  474. GcsBucket.getFiles
  475. .withArgs('call-1')
  476. .resolves([['ccc', 'ddd', 'eee'], 'call-2'])
  477. GcsBucket.getFiles.withArgs('call-2').resolves([['fff', 'ggg']])
  478. return GcsPersistor.deleteDirectory(bucket, directoryName)
  479. })
  480. it('should list the objects in the directory', function () {
  481. expect(Storage.prototype.bucket).to.have.been.calledWith(bucket)
  482. expect(GcsBucket.getFiles).to.have.been.calledWith({
  483. directory: directoryName,
  484. autoPaginate: false,
  485. })
  486. expect(GcsBucket.getFiles).to.have.been.calledWith('call-1')
  487. expect(GcsBucket.getFiles).to.have.been.calledWith('call-2')
  488. })
  489. it('should delete the files', function () {
  490. expect(GcsFile.delete.callCount).to.equal(7)
  491. })
  492. })
  493. describe('when there is an error listing the objects', function () {
  494. let error
  495. beforeEach(async function () {
  496. GcsBucket.getFiles = sinon.stub().rejects(genericError)
  497. try {
  498. await GcsPersistor.deleteDirectory(bucket, directoryName)
  499. } catch (err) {
  500. error = err
  501. }
  502. })
  503. it('should generate a WriteError', function () {
  504. expect(error).to.be.an.instanceOf(Errors.WriteError)
  505. })
  506. it('should wrap the error', function () {
  507. expect(error.cause).to.equal(genericError)
  508. })
  509. })
  510. })
  511. describe('directorySize', function () {
  512. describe('with valid parameters', function () {
  513. let size
  514. beforeEach(async function () {
  515. size = await GcsPersistor.directorySize(bucket, key)
  516. })
  517. it('should list the objects in the directory', function () {
  518. expect(Storage.prototype.bucket).to.have.been.calledWith(bucket)
  519. expect(GcsBucket.getFiles).to.have.been.calledWith({ directory: key })
  520. })
  521. it('should return the directory size', function () {
  522. expect(size).to.equal(filesSize)
  523. })
  524. })
  525. describe('when there are no files', function () {
  526. let size
  527. beforeEach(async function () {
  528. GcsBucket.getFiles.resolves([[]])
  529. size = await GcsPersistor.directorySize(bucket, key)
  530. })
  531. it('should list the objects in the directory', function () {
  532. expect(Storage.prototype.bucket).to.have.been.calledWith(bucket)
  533. expect(GcsBucket.getFiles).to.have.been.calledWith({ directory: key })
  534. })
  535. it('should return zero', function () {
  536. expect(size).to.equal(0)
  537. })
  538. })
  539. describe('when there is an error listing the objects', function () {
  540. let error
  541. beforeEach(async function () {
  542. GcsBucket.getFiles.rejects(genericError)
  543. try {
  544. await GcsPersistor.directorySize(bucket, key)
  545. } catch (err) {
  546. error = err
  547. }
  548. })
  549. it('should generate a ReadError', function () {
  550. expect(error).to.be.an.instanceOf(Errors.ReadError)
  551. })
  552. it('should wrap the error', function () {
  553. expect(error.cause).to.equal(genericError)
  554. })
  555. })
  556. })
  557. describe('checkIfObjectExists', function () {
  558. describe('when the file exists', function () {
  559. let exists
  560. beforeEach(async function () {
  561. exists = await GcsPersistor.checkIfObjectExists(bucket, key)
  562. })
  563. it('should ask the file if it exists', function () {
  564. expect(Storage.prototype.bucket).to.have.been.calledWith(bucket)
  565. expect(GcsBucket.file).to.have.been.calledWith(key)
  566. expect(GcsFile.exists).to.have.been.called
  567. })
  568. it('should return that the file exists', function () {
  569. expect(exists).to.equal(true)
  570. })
  571. })
  572. describe('when the file does not exist', function () {
  573. let exists
  574. beforeEach(async function () {
  575. GcsFile.exists = sinon.stub().resolves([false])
  576. exists = await GcsPersistor.checkIfObjectExists(bucket, key)
  577. })
  578. it('should get the object header', function () {
  579. expect(Storage.prototype.bucket).to.have.been.calledWith(bucket)
  580. expect(GcsBucket.file).to.have.been.calledWith(key)
  581. expect(GcsFile.exists).to.have.been.called
  582. })
  583. it('should return that the file does not exist', function () {
  584. expect(exists).to.equal(false)
  585. })
  586. })
  587. describe('when there is an error', function () {
  588. let error
  589. beforeEach(async function () {
  590. GcsFile.exists = sinon.stub().rejects(genericError)
  591. try {
  592. await GcsPersistor.checkIfObjectExists(bucket, key)
  593. } catch (err) {
  594. error = err
  595. }
  596. })
  597. it('should generate a ReadError', function () {
  598. expect(error).to.be.an.instanceOf(Errors.ReadError)
  599. })
  600. it('should wrap the error', function () {
  601. expect(error.cause).to.equal(genericError)
  602. })
  603. })
  604. })
  605. })