GcsPersistorTests.js 20 KB

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