FilestoreTests.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963
  1. const chai = require('chai')
  2. const { expect } = chai
  3. const fs = require('fs')
  4. const Settings = require('@overleaf/settings')
  5. const Path = require('path')
  6. const FilestoreApp = require('./FilestoreApp')
  7. const TestHelper = require('./TestHelper')
  8. const rp = require('request-promise-native').defaults({
  9. resolveWithFullResponse: true,
  10. })
  11. const S3 = require('aws-sdk/clients/s3')
  12. const Stream = require('stream')
  13. const request = require('request')
  14. const { promisify } = require('util')
  15. const { Storage } = require('@google-cloud/storage')
  16. const streamifier = require('streamifier')
  17. chai.use(require('chai-as-promised'))
  18. const { ObjectId } = require('mongodb')
  19. const tk = require('timekeeper')
  20. const ChildProcess = require('child_process')
  21. const fsWriteFile = promisify(fs.writeFile)
  22. const fsStat = promisify(fs.stat)
  23. const pipeline = promisify(Stream.pipeline)
  24. const exec = promisify(ChildProcess.exec)
  25. const msleep = promisify(setTimeout)
  26. if (!process.env.AWS_ACCESS_KEY_ID) {
  27. throw new Error('please provide credentials for the AWS S3 test server')
  28. }
  29. process.on('unhandledRejection', e => {
  30. // eslint-disable-next-line no-console
  31. console.log('** Unhandled Promise Rejection **\n', e)
  32. throw e
  33. })
  34. // store settings for multiple backends, so that we can test each one.
  35. // fs will always be available - add others if they are configured
  36. const BackendSettings = require('./TestConfig')
  37. describe('Filestore', function () {
  38. this.timeout(1000 * 10)
  39. const filestoreUrl = `http://localhost:${Settings.internal.filestore.port}`
  40. const seenSockets = []
  41. async function expectNoSockets() {
  42. try {
  43. await msleep(1000)
  44. const { stdout } = await exec('ss -tnH')
  45. const badSockets = []
  46. for (const socket of stdout.split('\n')) {
  47. const fields = socket.split(' ').filter(part => part !== '')
  48. if (
  49. fields.length > 2 &&
  50. parseInt(fields[1]) &&
  51. !seenSockets.includes(socket)
  52. ) {
  53. badSockets.push(socket)
  54. seenSockets.push(socket)
  55. }
  56. }
  57. if (badSockets.length) {
  58. // eslint-disable-next-line no-console
  59. console.error(
  60. 'ERR: Sockets still have receive buffer after connection closed'
  61. )
  62. for (const socket of badSockets) {
  63. // eslint-disable-next-line no-console
  64. console.error(socket)
  65. }
  66. throw new Error('Sockets still open after connection closed')
  67. }
  68. } catch (err) {
  69. expect(err).not.to.exist
  70. }
  71. }
  72. // redefine the test suite for every available backend
  73. Object.keys(BackendSettings).forEach(backend => {
  74. describe(backend, function () {
  75. let app,
  76. previousEgress,
  77. previousIngress,
  78. metricPrefix,
  79. projectId,
  80. otherProjectId
  81. before(async function () {
  82. // create the app with the relevant filestore settings
  83. Settings.filestore = BackendSettings[backend]
  84. app = new FilestoreApp()
  85. await app.runServer()
  86. })
  87. if (BackendSettings[backend].gcs) {
  88. before(async function () {
  89. const storage = new Storage(Settings.filestore.gcs.endpoint)
  90. await storage.createBucket(process.env.GCS_USER_FILES_BUCKET_NAME)
  91. await storage.createBucket(process.env.GCS_PUBLIC_FILES_BUCKET_NAME)
  92. await storage.createBucket(process.env.GCS_TEMPLATE_FILES_BUCKET_NAME)
  93. await storage.createBucket(
  94. `${process.env.GCS_USER_FILES_BUCKET_NAME}-deleted`
  95. )
  96. await storage.createBucket(
  97. `${process.env.GCS_PUBLIC_FILES_BUCKET_NAME}-deleted`
  98. )
  99. await storage.createBucket(
  100. `${process.env.GCS_TEMPLATE_FILES_BUCKET_NAME}-deleted`
  101. )
  102. })
  103. }
  104. after(async function () {
  105. await msleep(3000)
  106. await app.stop()
  107. })
  108. beforeEach(async function () {
  109. // retrieve previous metrics from the app
  110. if (['s3', 'gcs'].includes(Settings.filestore.backend)) {
  111. metricPrefix = Settings.filestore.backend
  112. previousEgress = await TestHelper.getMetric(
  113. filestoreUrl,
  114. `${metricPrefix}_egress`
  115. )
  116. }
  117. projectId = ObjectId().toString()
  118. otherProjectId = ObjectId().toString()
  119. })
  120. it('should send a 200 for the status endpoint', async function () {
  121. const response = await rp(`${filestoreUrl}/status`)
  122. expect(response.statusCode).to.equal(200)
  123. expect(response.body).to.contain('filestore')
  124. expect(response.body).to.contain('up')
  125. })
  126. it('should send a 200 for the health-check endpoint', async function () {
  127. const response = await rp(`${filestoreUrl}/health_check`)
  128. expect(response.statusCode).to.equal(200)
  129. expect(response.body).to.equal('OK')
  130. })
  131. describe('with a file on the server', function () {
  132. let fileId, fileUrl, constantFileContent
  133. const localFileReadPath =
  134. '/tmp/filestore_acceptance_tests_file_read.txt'
  135. beforeEach(async function () {
  136. fileId = ObjectId().toString()
  137. fileUrl = `${filestoreUrl}/project/${projectId}/file/${fileId}`
  138. constantFileContent = [
  139. 'hello world',
  140. `line 2 goes here ${Math.random()}`,
  141. 'there are 3 lines in all',
  142. ].join('\n')
  143. await fsWriteFile(localFileReadPath, constantFileContent)
  144. const writeStream = request.post(fileUrl)
  145. const readStream = fs.createReadStream(localFileReadPath)
  146. // hack to consume the result to ensure the http request has been fully processed
  147. const resultStream = fs.createWriteStream('/dev/null')
  148. await pipeline(readStream, writeStream, resultStream)
  149. })
  150. beforeEach(async function retrievePreviousIngressMetrics() {
  151. // The upload request can bump the ingress metric.
  152. // The content hash validation might require a full download
  153. // in case the ETag field of the upload response is not a md5 sum.
  154. if (['s3', 'gcs'].includes(Settings.filestore.backend)) {
  155. previousIngress = await TestHelper.getMetric(
  156. filestoreUrl,
  157. `${metricPrefix}_ingress`
  158. )
  159. }
  160. })
  161. it('should return 404 for a non-existant id', async function () {
  162. const options = { uri: fileUrl + '___this_is_clearly_wrong___' }
  163. await expect(
  164. rp.get(options)
  165. ).to.eventually.be.rejected.and.have.property('statusCode', 404)
  166. })
  167. it('should return the file size on a HEAD request', async function () {
  168. const expectedLength = Buffer.byteLength(constantFileContent)
  169. const res = await rp.head(fileUrl)
  170. expect(res.statusCode).to.equal(200)
  171. expect(res.headers['content-length']).to.equal(
  172. expectedLength.toString()
  173. )
  174. })
  175. it('should be able get the file back', async function () {
  176. const res = await rp.get(fileUrl)
  177. expect(res.body).to.equal(constantFileContent)
  178. })
  179. it('should not leak a socket', async function () {
  180. await rp.get(fileUrl)
  181. await expectNoSockets()
  182. })
  183. it('should be able to get back the first 9 bytes of the file', async function () {
  184. const options = {
  185. uri: fileUrl,
  186. headers: {
  187. Range: 'bytes=0-8',
  188. },
  189. }
  190. const res = await rp.get(options)
  191. expect(res.body).to.equal('hello wor')
  192. })
  193. it('should be able to get back bytes 4 through 10 of the file', async function () {
  194. const options = {
  195. uri: fileUrl,
  196. headers: {
  197. Range: 'bytes=4-10',
  198. },
  199. }
  200. const res = await rp.get(options)
  201. expect(res.body).to.equal('o world')
  202. })
  203. it('should be able to delete the file', async function () {
  204. const response = await rp.del(fileUrl)
  205. expect(response.statusCode).to.equal(204)
  206. await expect(
  207. rp.get(fileUrl)
  208. ).to.eventually.be.rejected.and.have.property('statusCode', 404)
  209. })
  210. it('should be able to copy files', async function () {
  211. const newProjectID = ObjectId().toString()
  212. const newFileId = ObjectId().toString()
  213. const newFileUrl = `${filestoreUrl}/project/${newProjectID}/file/${newFileId}`
  214. const opts = {
  215. method: 'put',
  216. uri: newFileUrl,
  217. json: {
  218. source: {
  219. project_id: projectId,
  220. file_id: fileId,
  221. },
  222. },
  223. }
  224. let response = await rp(opts)
  225. expect(response.statusCode).to.equal(200)
  226. response = await rp.del(fileUrl)
  227. expect(response.statusCode).to.equal(204)
  228. response = await rp.get(newFileUrl)
  229. expect(response.body).to.equal(constantFileContent)
  230. })
  231. it('should be able to overwrite the file', async function () {
  232. const newContent = `here is some different content, ${Math.random()}`
  233. const writeStream = request.post(fileUrl)
  234. const readStream = streamifier.createReadStream(newContent)
  235. // hack to consume the result to ensure the http request has been fully processed
  236. const resultStream = fs.createWriteStream('/dev/null')
  237. await pipeline(readStream, writeStream, resultStream)
  238. const response = await rp.get(fileUrl)
  239. expect(response.body).to.equal(newContent)
  240. })
  241. if (['S3Persistor', 'GcsPersistor'].includes(backend)) {
  242. it('should record an egress metric for the upload', async function () {
  243. const metric = await TestHelper.getMetric(
  244. filestoreUrl,
  245. `${metricPrefix}_egress`
  246. )
  247. expect(metric - previousEgress).to.equal(constantFileContent.length)
  248. })
  249. it('should record an ingress metric when downloading the file', async function () {
  250. await rp.get(fileUrl)
  251. const metric = await TestHelper.getMetric(
  252. filestoreUrl,
  253. `${metricPrefix}_ingress`
  254. )
  255. expect(metric - previousIngress).to.equal(
  256. constantFileContent.length
  257. )
  258. })
  259. it('should record an ingress metric for a partial download', async function () {
  260. const options = {
  261. uri: fileUrl,
  262. headers: {
  263. Range: 'bytes=0-8',
  264. },
  265. }
  266. await rp.get(options)
  267. const metric = await TestHelper.getMetric(
  268. filestoreUrl,
  269. `${metricPrefix}_ingress`
  270. )
  271. expect(metric - previousIngress).to.equal(9)
  272. })
  273. }
  274. })
  275. describe('with multiple files', function () {
  276. let fileIds, fileUrls, otherFileUrls, projectUrl, otherProjectUrl
  277. const localFileReadPaths = [
  278. '/tmp/filestore_acceptance_tests_file_read_1.txt',
  279. '/tmp/filestore_acceptance_tests_file_read_2.txt',
  280. '/tmp/filestore_acceptance_tests_file_read_3.txt',
  281. ]
  282. const constantFileContents = [
  283. [
  284. 'hello world',
  285. `line 2 goes here ${Math.random()}`,
  286. 'there are 3 lines in all',
  287. ].join('\n'),
  288. [
  289. `for reference: ${Math.random()}`,
  290. 'cats are the best animals',
  291. 'wombats are a close second',
  292. ].join('\n'),
  293. [
  294. `another file: ${Math.random()}`,
  295. 'with multiple lines',
  296. 'the end',
  297. ].join('\n'),
  298. ]
  299. before(async function () {
  300. return Promise.all([
  301. fsWriteFile(localFileReadPaths[0], constantFileContents[0]),
  302. fsWriteFile(localFileReadPaths[1], constantFileContents[1]),
  303. fsWriteFile(localFileReadPaths[2], constantFileContents[2]),
  304. ])
  305. })
  306. beforeEach(async function () {
  307. projectUrl = `${filestoreUrl}/project/${projectId}`
  308. otherProjectUrl = `${filestoreUrl}/project/${otherProjectId}`
  309. fileIds = [
  310. ObjectId().toString(),
  311. ObjectId().toString(),
  312. ObjectId().toString(),
  313. ]
  314. fileUrls = [
  315. `${projectUrl}/file/${fileIds[0]}`,
  316. `${projectUrl}/file/${fileIds[1]}`,
  317. ]
  318. otherFileUrls = [`${otherProjectUrl}/file/${fileIds[2]}`]
  319. const writeStreams = [
  320. request.post(fileUrls[0]),
  321. request.post(fileUrls[1]),
  322. request.post(otherFileUrls[0]),
  323. ]
  324. const readStreams = [
  325. fs.createReadStream(localFileReadPaths[0]),
  326. fs.createReadStream(localFileReadPaths[1]),
  327. fs.createReadStream(localFileReadPaths[2]),
  328. ]
  329. // hack to consume the result to ensure the http request has been fully processed
  330. const resultStreams = [
  331. fs.createWriteStream('/dev/null'),
  332. fs.createWriteStream('/dev/null'),
  333. fs.createWriteStream('/dev/null'),
  334. ]
  335. return Promise.all([
  336. pipeline(readStreams[0], writeStreams[0], resultStreams[0]),
  337. pipeline(readStreams[1], writeStreams[1], resultStreams[1]),
  338. pipeline(readStreams[2], writeStreams[2], resultStreams[2]),
  339. ])
  340. })
  341. it('should get the directory size', async function () {
  342. const response = await rp.get(
  343. `${filestoreUrl}/project/${projectId}/size`
  344. )
  345. expect(parseInt(JSON.parse(response.body)['total bytes'])).to.equal(
  346. constantFileContents[0].length + constantFileContents[1].length
  347. )
  348. })
  349. it('should store the files', async function () {
  350. for (const index in fileUrls) {
  351. await expect(rp.get(fileUrls[index])).to.eventually.have.property(
  352. 'body',
  353. constantFileContents[index]
  354. )
  355. }
  356. })
  357. it('should be able to delete the project', async function () {
  358. await expect(rp.delete(projectUrl)).to.eventually.have.property(
  359. 'statusCode',
  360. 204
  361. )
  362. for (const index in fileUrls) {
  363. await expect(
  364. rp.get(fileUrls[index])
  365. ).to.eventually.be.rejected.and.have.property('statusCode', 404)
  366. }
  367. })
  368. it('should not delete files in other projects', async function () {
  369. for (const index in otherFileUrls) {
  370. await expect(
  371. rp.get(otherFileUrls[index])
  372. ).to.eventually.have.property('statusCode', 200)
  373. }
  374. })
  375. it('should not delete a partial project id', async function () {
  376. await expect(
  377. rp.delete(`${filestoreUrl}/project/5`)
  378. ).to.eventually.be.rejected.and.have.property('statusCode', 400)
  379. })
  380. })
  381. describe('with a large file', function () {
  382. let fileId, fileUrl, largeFileContent, error
  383. beforeEach(async function () {
  384. fileId = ObjectId().toString()
  385. fileUrl = `${filestoreUrl}/project/${projectId}/file/${fileId}`
  386. largeFileContent = '_wombat_'.repeat(1024 * 1024) // 8 megabytes
  387. largeFileContent += Math.random()
  388. const writeStream = request.post(fileUrl)
  389. const readStream = streamifier.createReadStream(largeFileContent)
  390. // hack to consume the result to ensure the http request has been fully processed
  391. const resultStream = fs.createWriteStream('/dev/null')
  392. try {
  393. await pipeline(readStream, writeStream, resultStream)
  394. } catch (err) {
  395. error = err
  396. }
  397. })
  398. it('should be able to get the file back', async function () {
  399. const response = await rp.get(fileUrl)
  400. expect(response.body).to.equal(largeFileContent)
  401. })
  402. it('should not throw an error', function () {
  403. expect(error).not.to.exist
  404. })
  405. it('should not leak a socket', async function () {
  406. await rp.get(fileUrl)
  407. await expectNoSockets()
  408. })
  409. it('should not leak a socket if the connection is aborted', async function () {
  410. this.timeout(20000)
  411. for (let i = 0; i < 5; i++) {
  412. // test is not 100% reliable, so repeat
  413. // create a new connection and have it time out before reading any data
  414. await new Promise(resolve => {
  415. const streamThatHangs = new Stream.PassThrough()
  416. const stream = request({ url: fileUrl, timeout: 1000 })
  417. stream.pipe(streamThatHangs)
  418. stream.on('error', () => {
  419. stream.destroy()
  420. streamThatHangs.destroy()
  421. resolve()
  422. })
  423. })
  424. await expectNoSockets()
  425. }
  426. })
  427. })
  428. if (backend === 'S3Persistor' || backend === 'FallbackGcsToS3Persistor') {
  429. describe('with a file in a specific bucket', function () {
  430. let constantFileContent, fileId, fileUrl, bucketName
  431. beforeEach(async function () {
  432. constantFileContent = `This is a file in a different S3 bucket ${Math.random()}`
  433. fileId = ObjectId().toString()
  434. bucketName = ObjectId().toString()
  435. fileUrl = `${filestoreUrl}/bucket/${bucketName}/key/${fileId}`
  436. const s3ClientSettings = {
  437. credentials: {
  438. accessKeyId: process.env.AWS_ACCESS_KEY_ID,
  439. secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
  440. },
  441. endpoint: process.env.AWS_S3_ENDPOINT,
  442. sslEnabled: false,
  443. s3ForcePathStyle: true,
  444. }
  445. const s3 = new S3(s3ClientSettings)
  446. await s3
  447. .createBucket({
  448. Bucket: bucketName,
  449. })
  450. .promise()
  451. await s3
  452. .upload({
  453. Bucket: bucketName,
  454. Key: fileId,
  455. Body: constantFileContent,
  456. })
  457. .promise()
  458. })
  459. it('should get the file from the specified bucket', async function () {
  460. const response = await rp.get(fileUrl)
  461. expect(response.body).to.equal(constantFileContent)
  462. })
  463. })
  464. }
  465. if (backend === 'GcsPersistor') {
  466. describe('when deleting a file in GCS', function () {
  467. let fileId, fileUrl, content, error, date
  468. beforeEach(async function () {
  469. date = new Date()
  470. tk.freeze(date)
  471. fileId = ObjectId()
  472. fileUrl = `${filestoreUrl}/project/${projectId}/file/${fileId}`
  473. content = '_wombat_' + Math.random()
  474. const writeStream = request.post(fileUrl)
  475. const readStream = streamifier.createReadStream(content)
  476. // hack to consume the result to ensure the http request has been fully processed
  477. const resultStream = fs.createWriteStream('/dev/null')
  478. try {
  479. await pipeline(readStream, writeStream, resultStream)
  480. await rp.delete(fileUrl)
  481. } catch (err) {
  482. error = err
  483. }
  484. })
  485. afterEach(function () {
  486. tk.reset()
  487. })
  488. it('should not throw an error', function () {
  489. expect(error).not.to.exist
  490. })
  491. it('should copy the file to the deleted-files bucket', async function () {
  492. await TestHelper.expectPersistorToHaveFile(
  493. app.persistor,
  494. `${Settings.filestore.stores.user_files}-deleted`,
  495. `${projectId}/${fileId}-${date.toISOString()}`,
  496. content
  497. )
  498. })
  499. it('should remove the file from the original bucket', async function () {
  500. await TestHelper.expectPersistorNotToHaveFile(
  501. app.persistor,
  502. Settings.filestore.stores.user_files,
  503. `${projectId}/${fileId}`
  504. )
  505. })
  506. })
  507. }
  508. if (BackendSettings[backend].fallback) {
  509. describe('with a fallback', function () {
  510. let constantFileContent,
  511. fileId,
  512. fileKey,
  513. fileUrl,
  514. bucket,
  515. fallbackBucket
  516. beforeEach(function () {
  517. constantFileContent = `This is yet more file content ${Math.random()}`
  518. fileId = ObjectId().toString()
  519. fileKey = `${projectId}/${fileId}`
  520. fileUrl = `${filestoreUrl}/project/${projectId}/file/${fileId}`
  521. bucket = Settings.filestore.stores.user_files
  522. fallbackBucket = Settings.filestore.fallback.buckets[bucket]
  523. })
  524. describe('with a file in the fallback bucket', function () {
  525. beforeEach(async function () {
  526. await TestHelper.uploadStringToPersistor(
  527. app.persistor.fallbackPersistor,
  528. fallbackBucket,
  529. fileKey,
  530. constantFileContent
  531. )
  532. })
  533. it('should not find file in the primary', async function () {
  534. await TestHelper.expectPersistorNotToHaveFile(
  535. app.persistor.primaryPersistor,
  536. bucket,
  537. fileKey
  538. )
  539. })
  540. it('should find the file in the fallback', async function () {
  541. await TestHelper.expectPersistorToHaveFile(
  542. app.persistor.fallbackPersistor,
  543. fallbackBucket,
  544. fileKey,
  545. constantFileContent
  546. )
  547. })
  548. describe('when copyOnMiss is disabled', function () {
  549. beforeEach(function () {
  550. app.persistor.settings.copyOnMiss = false
  551. })
  552. it('should fetch the file', async function () {
  553. const res = await rp.get(fileUrl)
  554. expect(res.body).to.equal(constantFileContent)
  555. })
  556. it('should not copy the file to the primary', async function () {
  557. await rp.get(fileUrl)
  558. await TestHelper.expectPersistorNotToHaveFile(
  559. app.persistor.primaryPersistor,
  560. bucket,
  561. fileKey
  562. )
  563. })
  564. })
  565. describe('when copyOnMiss is enabled', function () {
  566. beforeEach(function () {
  567. app.persistor.settings.copyOnMiss = true
  568. })
  569. it('should fetch the file', async function () {
  570. const res = await rp.get(fileUrl)
  571. expect(res.body).to.equal(constantFileContent)
  572. })
  573. it('copies the file to the primary', async function () {
  574. await rp.get(fileUrl)
  575. // wait for the file to copy in the background
  576. await msleep(1000)
  577. await TestHelper.expectPersistorToHaveFile(
  578. app.persistor.primaryPersistor,
  579. bucket,
  580. fileKey,
  581. constantFileContent
  582. )
  583. })
  584. })
  585. describe('when copying a file', function () {
  586. let newFileId, newFileUrl, newFileKey, opts
  587. beforeEach(function () {
  588. const newProjectID = ObjectId().toString()
  589. newFileId = ObjectId().toString()
  590. newFileUrl = `${filestoreUrl}/project/${newProjectID}/file/${newFileId}`
  591. newFileKey = `${newProjectID}/${newFileId}`
  592. opts = {
  593. method: 'put',
  594. uri: newFileUrl,
  595. json: {
  596. source: {
  597. project_id: projectId,
  598. file_id: fileId,
  599. },
  600. },
  601. }
  602. })
  603. describe('when copyOnMiss is false', function () {
  604. beforeEach(async function () {
  605. app.persistor.settings.copyOnMiss = false
  606. const response = await rp(opts)
  607. expect(response.statusCode).to.equal(200)
  608. })
  609. it('should leave the old file in the old bucket', async function () {
  610. await TestHelper.expectPersistorToHaveFile(
  611. app.persistor.fallbackPersistor,
  612. fallbackBucket,
  613. fileKey,
  614. constantFileContent
  615. )
  616. })
  617. it('should not create a new file in the old bucket', async function () {
  618. await TestHelper.expectPersistorNotToHaveFile(
  619. app.persistor.fallbackPersistor,
  620. fallbackBucket,
  621. newFileKey
  622. )
  623. })
  624. it('should create a new file in the new bucket', async function () {
  625. await TestHelper.expectPersistorToHaveFile(
  626. app.persistor.primaryPersistor,
  627. bucket,
  628. newFileKey,
  629. constantFileContent
  630. )
  631. })
  632. it('should not copy the old file to the primary with the old key', async function () {
  633. // wait for the file to copy in the background
  634. await msleep(1000)
  635. await TestHelper.expectPersistorNotToHaveFile(
  636. app.persistor.primaryPersistor,
  637. bucket,
  638. fileKey
  639. )
  640. })
  641. })
  642. describe('when copyOnMiss is true', function () {
  643. beforeEach(async function () {
  644. app.persistor.settings.copyOnMiss = true
  645. const response = await rp(opts)
  646. expect(response.statusCode).to.equal(200)
  647. })
  648. it('should leave the old file in the old bucket', async function () {
  649. await TestHelper.expectPersistorToHaveFile(
  650. app.persistor.fallbackPersistor,
  651. fallbackBucket,
  652. fileKey,
  653. constantFileContent
  654. )
  655. })
  656. it('should not create a new file in the old bucket', async function () {
  657. await TestHelper.expectPersistorNotToHaveFile(
  658. app.persistor.fallbackPersistor,
  659. fallbackBucket,
  660. newFileKey
  661. )
  662. })
  663. it('should create a new file in the new bucket', async function () {
  664. await TestHelper.expectPersistorToHaveFile(
  665. app.persistor.primaryPersistor,
  666. bucket,
  667. newFileKey,
  668. constantFileContent
  669. )
  670. })
  671. it('should copy the old file to the primary with the old key', async function () {
  672. // wait for the file to copy in the background
  673. await msleep(1000)
  674. await TestHelper.expectPersistorToHaveFile(
  675. app.persistor.primaryPersistor,
  676. bucket,
  677. fileKey,
  678. constantFileContent
  679. )
  680. })
  681. })
  682. })
  683. })
  684. describe('when sending a file', function () {
  685. beforeEach(async function () {
  686. const writeStream = request.post(fileUrl)
  687. const readStream =
  688. streamifier.createReadStream(constantFileContent)
  689. // hack to consume the result to ensure the http request has been fully processed
  690. const resultStream = fs.createWriteStream('/dev/null')
  691. await pipeline(readStream, writeStream, resultStream)
  692. })
  693. it('should store the file on the primary', async function () {
  694. await TestHelper.expectPersistorToHaveFile(
  695. app.persistor.primaryPersistor,
  696. bucket,
  697. fileKey,
  698. constantFileContent
  699. )
  700. })
  701. it('should not store the file on the fallback', async function () {
  702. await TestHelper.expectPersistorNotToHaveFile(
  703. app.persistor.fallbackPersistor,
  704. fallbackBucket,
  705. `${projectId}/${fileId}`
  706. )
  707. })
  708. })
  709. describe('when deleting a file', function () {
  710. describe('when the file exists on the primary', function () {
  711. beforeEach(async function () {
  712. await TestHelper.uploadStringToPersistor(
  713. app.persistor.primaryPersistor,
  714. bucket,
  715. fileKey,
  716. constantFileContent
  717. )
  718. })
  719. it('should delete the file', async function () {
  720. const response = await rp.del(fileUrl)
  721. expect(response.statusCode).to.equal(204)
  722. await expect(
  723. rp.get(fileUrl)
  724. ).to.eventually.be.rejected.and.have.property('statusCode', 404)
  725. })
  726. })
  727. describe('when the file exists on the fallback', function () {
  728. beforeEach(async function () {
  729. await TestHelper.uploadStringToPersistor(
  730. app.persistor.fallbackPersistor,
  731. fallbackBucket,
  732. fileKey,
  733. constantFileContent
  734. )
  735. })
  736. it('should delete the file', async function () {
  737. const response = await rp.del(fileUrl)
  738. expect(response.statusCode).to.equal(204)
  739. await expect(
  740. rp.get(fileUrl)
  741. ).to.eventually.be.rejected.and.have.property('statusCode', 404)
  742. })
  743. })
  744. describe('when the file exists on both the primary and the fallback', function () {
  745. beforeEach(async function () {
  746. await TestHelper.uploadStringToPersistor(
  747. app.persistor.primaryPersistor,
  748. bucket,
  749. fileKey,
  750. constantFileContent
  751. )
  752. await TestHelper.uploadStringToPersistor(
  753. app.persistor.fallbackPersistor,
  754. fallbackBucket,
  755. fileKey,
  756. constantFileContent
  757. )
  758. })
  759. it('should delete the files', async function () {
  760. const response = await rp.del(fileUrl)
  761. expect(response.statusCode).to.equal(204)
  762. await expect(
  763. rp.get(fileUrl)
  764. ).to.eventually.be.rejected.and.have.property('statusCode', 404)
  765. })
  766. })
  767. describe('when the file does not exist', function () {
  768. it('should return return 204', async function () {
  769. // S3 doesn't give us a 404 when the object doesn't exist, so to stay
  770. // consistent we merrily return 204 ourselves here as well
  771. const response = await rp.del(fileUrl)
  772. expect(response.statusCode).to.equal(204)
  773. })
  774. })
  775. })
  776. })
  777. }
  778. describe('with a pdf file', function () {
  779. let fileId, fileUrl, localFileSize
  780. const localFileReadPath = Path.resolve(
  781. __dirname,
  782. '../../fixtures/test.pdf'
  783. )
  784. beforeEach(async function () {
  785. fileId = ObjectId().toString()
  786. fileUrl = `${filestoreUrl}/project/${projectId}/file/${fileId}`
  787. const stat = await fsStat(localFileReadPath)
  788. localFileSize = stat.size
  789. const writeStream = request.post(fileUrl)
  790. const endStream = fs.createWriteStream('/dev/null')
  791. const readStream = fs.createReadStream(localFileReadPath)
  792. await pipeline(readStream, writeStream, endStream)
  793. })
  794. it('should be able get the file back', async function () {
  795. const response = await rp.get(fileUrl)
  796. expect(response.body.substring(0, 8)).to.equal('%PDF-1.5')
  797. })
  798. if (['S3Persistor', 'GcsPersistor'].includes(backend)) {
  799. it('should record an egress metric for the upload', async function () {
  800. const metric = await TestHelper.getMetric(
  801. filestoreUrl,
  802. `${metricPrefix}_egress`
  803. )
  804. expect(metric - previousEgress).to.equal(localFileSize)
  805. })
  806. }
  807. describe('getting the preview image', function () {
  808. this.timeout(1000 * 20)
  809. let previewFileUrl
  810. beforeEach(function () {
  811. previewFileUrl = `${fileUrl}?style=preview`
  812. })
  813. it('should not time out', async function () {
  814. const response = await rp.get(previewFileUrl)
  815. expect(response.statusCode).to.equal(200)
  816. })
  817. it('should respond with image data', async function () {
  818. // note: this test relies of the imagemagick conversion working
  819. const response = await rp.get(previewFileUrl)
  820. expect(response.body.length).to.be.greaterThan(400)
  821. expect(response.body.substr(1, 3)).to.equal('PNG')
  822. })
  823. })
  824. describe('warming the cache', function () {
  825. this.timeout(1000 * 20)
  826. let previewFileUrl
  827. beforeEach(function () {
  828. previewFileUrl = `${fileUrl}?style=preview&cacheWarm=true`
  829. })
  830. it('should not time out', async function () {
  831. const response = await rp.get(previewFileUrl)
  832. expect(response.statusCode).to.equal(200)
  833. })
  834. it("should respond with only an 'OK'", async function () {
  835. // note: this test relies of the imagemagick conversion working
  836. const response = await rp.get(previewFileUrl)
  837. expect(response.body).to.equal('OK')
  838. })
  839. })
  840. })
  841. })
  842. })
  843. })