HealthCheckController.js 1.9 KB

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