HealthCheckController.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. const fs = require('fs')
  2. const path = require('path')
  3. const Settings = require('settings-sharelatex')
  4. const streamBuffers = require('stream-buffers')
  5. const { promisify } = require('util')
  6. const Stream = require('stream')
  7. const pipeline = promisify(Stream.pipeline)
  8. const fsCopy = promisify(fs.copyFile)
  9. const fsUnlink = promisify(fs.unlink)
  10. const { HealthCheckError } = require('./Errors')
  11. const FileConverter = require('./FileConverter').promises
  12. const FileHandler = require('./FileHandler').promises
  13. async function checkCanGetFiles() {
  14. if (!Settings.health_check) {
  15. return
  16. }
  17. const projectId = Settings.health_check.project_id
  18. const fileId = Settings.health_check.file_id
  19. const key = `${projectId}/${fileId}`
  20. const bucket = Settings.filestore.stores.user_files
  21. const buffer = new streamBuffers.WritableStreamBuffer({
  22. initialSize: 100
  23. })
  24. const sourceStream = await FileHandler.getFile(bucket, key, {})
  25. try {
  26. await pipeline(sourceStream, buffer)
  27. } catch (err) {
  28. throw new HealthCheckError('failed to get health-check file', {}, err)
  29. }
  30. if (!buffer.size()) {
  31. throw new HealthCheckError('no bytes written to download stream')
  32. }
  33. }
  34. async function checkFileConvert() {
  35. if (!Settings.enableConversions) {
  36. return
  37. }
  38. const imgPath = path.join(Settings.path.uploadFolder, '/tiny.pdf')
  39. let resultPath
  40. try {
  41. await fsCopy('./tiny.pdf', imgPath)
  42. resultPath = await FileConverter.thumbnail(imgPath)
  43. } finally {
  44. if (resultPath) {
  45. await fsUnlink(resultPath)
  46. }
  47. await fsUnlink(imgPath)
  48. }
  49. }
  50. module.exports = {
  51. check(req, res, next) {
  52. Promise.all([checkCanGetFiles(), checkFileConvert()])
  53. .then(() => res.sendStatus(200))
  54. .catch(err => {
  55. next(err)
  56. })
  57. }
  58. }