GcsPersistorTests.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  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. apiScheme: 'http',
  240. apiEndpoint: 'custom.endpoint',
  241. }
  242. signedUrl = await GcsPersistor.getRedirectUrl(bucket, key)
  243. })
  244. it('should return a plain URL', function () {
  245. expect(signedUrl).to.equal(
  246. `http://custom.endpoint/download/storage/v1/b/${bucket}/o/${key}?alt=media`
  247. )
  248. })
  249. })
  250. })
  251. describe('getObjectSize', function () {
  252. describe('when called with valid parameters', function () {
  253. let size
  254. beforeEach(async function () {
  255. size = await GcsPersistor.getObjectSize(bucket, key)
  256. })
  257. it('should return the object size', function () {
  258. expect(size).to.equal(files[0].metadata.size)
  259. })
  260. it('should pass the bucket and key to GCS', function () {
  261. expect(Storage.prototype.bucket).to.have.been.calledWith(bucket)
  262. expect(GcsBucket.file).to.have.been.calledWith(key)
  263. expect(GcsFile.getMetadata).to.have.been.called
  264. })
  265. })
  266. describe('when the object is not found', function () {
  267. let error
  268. beforeEach(async function () {
  269. GcsFile.getMetadata = sinon.stub().rejects(GcsNotFoundError)
  270. try {
  271. await GcsPersistor.getObjectSize(bucket, key)
  272. } catch (err) {
  273. error = err
  274. }
  275. })
  276. it('should return a NotFoundError', function () {
  277. expect(error).to.be.an.instanceOf(Errors.NotFoundError)
  278. })
  279. it('should wrap the error', function () {
  280. expect(error.cause).to.equal(GcsNotFoundError)
  281. })
  282. })
  283. describe('when GCS returns an error', function () {
  284. let error
  285. beforeEach(async function () {
  286. GcsFile.getMetadata = sinon.stub().rejects(genericError)
  287. try {
  288. await GcsPersistor.getObjectSize(bucket, key)
  289. } catch (err) {
  290. error = err
  291. }
  292. })
  293. it('should return a ReadError', function () {
  294. expect(error).to.be.an.instanceOf(Errors.ReadError)
  295. })
  296. it('should wrap the error', function () {
  297. expect(error.cause).to.equal(genericError)
  298. })
  299. })
  300. })
  301. describe('sendStream', function () {
  302. describe('with valid parameters', function () {
  303. beforeEach(async function () {
  304. return GcsPersistor.sendStream(bucket, key, ReadStream)
  305. })
  306. it('should upload the stream', function () {
  307. expect(Storage.prototype.bucket).to.have.been.calledWith(bucket)
  308. expect(GcsBucket.file).to.have.been.calledWith(key)
  309. expect(GcsFile.createWriteStream).to.have.been.called
  310. })
  311. it('should not try to create a resumable upload', function () {
  312. expect(GcsFile.createWriteStream).to.have.been.calledWith({
  313. resumable: false,
  314. })
  315. })
  316. it('should meter the stream and pass it to GCS', function () {
  317. expect(StreamPromises.pipeline).to.have.been.calledWith(
  318. ReadStream,
  319. sinon.match.instanceOf(Transform),
  320. WriteStream
  321. )
  322. })
  323. it('calculates the md5 hash of the file', function () {
  324. expect(Hash.digest).to.have.been.called
  325. })
  326. })
  327. describe('when a hash is supplied', function () {
  328. beforeEach(async function () {
  329. return GcsPersistor.sendStream(bucket, key, ReadStream, {
  330. sourceMd5: 'aaaaaaaabbbbbbbbaaaaaaaabbbbbbbb',
  331. })
  332. })
  333. it('should not calculate the md5 hash of the file', function () {
  334. expect(Hash.digest).not.to.have.been.called
  335. })
  336. it('sends the hash in base64', function () {
  337. expect(GcsFile.createWriteStream).to.have.been.calledWith({
  338. validation: 'md5',
  339. metadata: {
  340. md5Hash: 'qqqqqru7u7uqqqqqu7u7uw==',
  341. },
  342. resumable: false,
  343. })
  344. })
  345. it('does not fetch the md5 hash of the uploaded file', function () {
  346. expect(GcsFile.getMetadata).not.to.have.been.called
  347. })
  348. })
  349. describe('when metadata is supplied', function () {
  350. const contentType = 'text/csv'
  351. const contentEncoding = 'gzip'
  352. beforeEach(async function () {
  353. return GcsPersistor.sendStream(bucket, key, ReadStream, {
  354. contentType,
  355. contentEncoding,
  356. })
  357. })
  358. it('should send the metadata to GCS', function () {
  359. expect(GcsFile.createWriteStream).to.have.been.calledWith({
  360. metadata: { contentType, contentEncoding },
  361. resumable: false,
  362. })
  363. })
  364. })
  365. describe('when the upload fails', function () {
  366. let error
  367. beforeEach(async function () {
  368. StreamPromises.pipeline
  369. .withArgs(ReadStream, sinon.match.instanceOf(Transform), WriteStream)
  370. .rejects(genericError)
  371. try {
  372. await GcsPersistor.sendStream(bucket, key, ReadStream)
  373. } catch (err) {
  374. error = err
  375. }
  376. })
  377. it('throws a WriteError', function () {
  378. expect(error).to.be.an.instanceOf(Errors.WriteError)
  379. })
  380. it('wraps the error', function () {
  381. expect(error.cause).to.equal(genericError)
  382. })
  383. })
  384. })
  385. describe('sendFile', function () {
  386. describe('with valid parameters', function () {
  387. beforeEach(async function () {
  388. return GcsPersistor.sendFile(bucket, key, filename)
  389. })
  390. it('should create a read stream for the file', function () {
  391. expect(Fs.createReadStream).to.have.been.calledWith(filename)
  392. })
  393. it('should create a write stream', function () {
  394. expect(Storage.prototype.bucket).to.have.been.calledWith(bucket)
  395. expect(GcsBucket.file).to.have.been.calledWith(key)
  396. expect(GcsFile.createWriteStream).to.have.been.called
  397. })
  398. it('should upload the stream via the meter', function () {
  399. expect(StreamPromises.pipeline).to.have.been.calledWith(
  400. ReadStream,
  401. sinon.match.instanceOf(Transform),
  402. WriteStream
  403. )
  404. })
  405. })
  406. })
  407. describe('copyObject', function () {
  408. const destinationFile = 'destFile'
  409. beforeEach(function () {
  410. GcsBucket.file.withArgs(destKey).returns(destinationFile)
  411. })
  412. describe('with valid parameters', function () {
  413. beforeEach(async function () {
  414. return GcsPersistor.copyObject(bucket, key, destKey)
  415. })
  416. it('should copy the object', function () {
  417. expect(Storage.prototype.bucket).to.have.been.calledWith(bucket)
  418. expect(GcsBucket.file).to.have.been.calledWith(key)
  419. expect(GcsFile.copy).to.have.been.calledWith(destinationFile)
  420. })
  421. })
  422. describe('when the file does not exist', function () {
  423. let error
  424. beforeEach(async function () {
  425. GcsFile.copy = sinon.stub().rejects(GcsNotFoundError)
  426. try {
  427. await GcsPersistor.copyObject(bucket, key, destKey)
  428. } catch (err) {
  429. error = err
  430. }
  431. })
  432. it('should throw a NotFoundError', function () {
  433. expect(error).to.be.an.instanceOf(Errors.NotFoundError)
  434. })
  435. })
  436. })
  437. describe('deleteObject', function () {
  438. describe('with valid parameters', function () {
  439. beforeEach(async function () {
  440. return GcsPersistor.deleteObject(bucket, key)
  441. })
  442. it('should delete the object', function () {
  443. expect(Storage.prototype.bucket).to.have.been.calledWith(bucket)
  444. expect(GcsBucket.file).to.have.been.calledWith(key)
  445. expect(GcsFile.delete).to.have.been.called
  446. })
  447. })
  448. describe('when the file does not exist', function () {
  449. let error
  450. beforeEach(async function () {
  451. GcsFile.delete = sinon.stub().rejects(GcsNotFoundError)
  452. try {
  453. await GcsPersistor.deleteObject(bucket, key)
  454. } catch (err) {
  455. error = err
  456. }
  457. })
  458. it('should not throw an error', function () {
  459. expect(error).not.to.exist
  460. })
  461. })
  462. })
  463. describe('deleteDirectory', function () {
  464. const directoryName = `${ObjectId()}/${ObjectId()}`
  465. const directoryPrefix = `${directoryName}/`
  466. describe('with valid parameters', function () {
  467. beforeEach(async function () {
  468. GcsBucket.getFiles = sinon.stub()
  469. // set up multiple paginated calls to getFiles
  470. GcsBucket.getFiles
  471. .withArgs({ prefix: directoryPrefix, autoPaginate: false })
  472. .resolves([['aaa', 'bbb'], 'call-1'])
  473. GcsBucket.getFiles
  474. .withArgs('call-1')
  475. .resolves([['ccc', 'ddd', 'eee'], 'call-2'])
  476. GcsBucket.getFiles.withArgs('call-2').resolves([['fff', 'ggg']])
  477. return GcsPersistor.deleteDirectory(bucket, directoryName)
  478. })
  479. it('should list the objects in the directory', function () {
  480. expect(Storage.prototype.bucket).to.have.been.calledWith(bucket)
  481. expect(GcsBucket.getFiles).to.have.been.calledWith({
  482. prefix: directoryPrefix,
  483. autoPaginate: false,
  484. })
  485. expect(GcsBucket.getFiles).to.have.been.calledWith('call-1')
  486. expect(GcsBucket.getFiles).to.have.been.calledWith('call-2')
  487. })
  488. it('should delete the files', function () {
  489. expect(GcsFile.delete.callCount).to.equal(7)
  490. })
  491. })
  492. describe('when there is an error listing the objects', function () {
  493. let error
  494. beforeEach(async function () {
  495. GcsBucket.getFiles = sinon.stub().rejects(genericError)
  496. try {
  497. await GcsPersistor.deleteDirectory(bucket, directoryName)
  498. } catch (err) {
  499. error = err
  500. }
  501. })
  502. it('should generate a WriteError', function () {
  503. expect(error).to.be.an.instanceOf(Errors.WriteError)
  504. })
  505. it('should wrap the error', function () {
  506. expect(error.cause).to.equal(genericError)
  507. })
  508. })
  509. })
  510. describe('directorySize', function () {
  511. describe('with valid parameters', function () {
  512. let size
  513. beforeEach(async function () {
  514. size = await GcsPersistor.directorySize(bucket, key)
  515. })
  516. it('should list the objects in the directory', function () {
  517. expect(Storage.prototype.bucket).to.have.been.calledWith(bucket)
  518. expect(GcsBucket.getFiles).to.have.been.calledWith({
  519. prefix: `${key}/`,
  520. })
  521. })
  522. it('should return the directory size', function () {
  523. expect(size).to.equal(filesSize)
  524. })
  525. })
  526. describe('when there are no files', function () {
  527. let size
  528. beforeEach(async function () {
  529. GcsBucket.getFiles.resolves([[]])
  530. size = await GcsPersistor.directorySize(bucket, key)
  531. })
  532. it('should list the objects in the directory', function () {
  533. expect(Storage.prototype.bucket).to.have.been.calledWith(bucket)
  534. expect(GcsBucket.getFiles).to.have.been.calledWith({
  535. prefix: `${key}/`,
  536. })
  537. })
  538. it('should return zero', function () {
  539. expect(size).to.equal(0)
  540. })
  541. })
  542. describe('when there is an error listing the objects', function () {
  543. let error
  544. beforeEach(async function () {
  545. GcsBucket.getFiles.rejects(genericError)
  546. try {
  547. await GcsPersistor.directorySize(bucket, key)
  548. } catch (err) {
  549. error = err
  550. }
  551. })
  552. it('should generate a ReadError', function () {
  553. expect(error).to.be.an.instanceOf(Errors.ReadError)
  554. })
  555. it('should wrap the error', function () {
  556. expect(error.cause).to.equal(genericError)
  557. })
  558. })
  559. })
  560. describe('checkIfObjectExists', function () {
  561. describe('when the file exists', function () {
  562. let exists
  563. beforeEach(async function () {
  564. exists = await GcsPersistor.checkIfObjectExists(bucket, key)
  565. })
  566. it('should ask the file if it exists', function () {
  567. expect(Storage.prototype.bucket).to.have.been.calledWith(bucket)
  568. expect(GcsBucket.file).to.have.been.calledWith(key)
  569. expect(GcsFile.exists).to.have.been.called
  570. })
  571. it('should return that the file exists', function () {
  572. expect(exists).to.equal(true)
  573. })
  574. })
  575. describe('when the file does not exist', function () {
  576. let exists
  577. beforeEach(async function () {
  578. GcsFile.exists = sinon.stub().resolves([false])
  579. exists = await GcsPersistor.checkIfObjectExists(bucket, key)
  580. })
  581. it('should get the object header', function () {
  582. expect(Storage.prototype.bucket).to.have.been.calledWith(bucket)
  583. expect(GcsBucket.file).to.have.been.calledWith(key)
  584. expect(GcsFile.exists).to.have.been.called
  585. })
  586. it('should return that the file does not exist', function () {
  587. expect(exists).to.equal(false)
  588. })
  589. })
  590. describe('when there is an error', function () {
  591. let error
  592. beforeEach(async function () {
  593. GcsFile.exists = sinon.stub().rejects(genericError)
  594. try {
  595. await GcsPersistor.checkIfObjectExists(bucket, key)
  596. } catch (err) {
  597. error = err
  598. }
  599. })
  600. it('should generate a ReadError', function () {
  601. expect(error).to.be.an.instanceOf(Errors.ReadError)
  602. })
  603. it('should wrap the error', function () {
  604. expect(error.cause).to.equal(genericError)
  605. })
  606. })
  607. })
  608. })