ScriptRunner.mjs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { ScriptLog } from '../../app/src/models/ScriptLog.mjs'
  2. import Settings from '@overleaf/settings'
  3. async function beforeScriptExecution(canonicalName, vars, scriptPath) {
  4. let log = new ScriptLog({
  5. canonicalName,
  6. filePathAtVersion: scriptPath,
  7. podName: process.env.OL_POD_NAME,
  8. username: process.env.OL_USERNAME,
  9. imageVersion: process.env.OL_IMAGE_VERSION,
  10. vars,
  11. })
  12. log = await log.save()
  13. console.log(
  14. '\n==================================' +
  15. '\n✨ Your script is running!' +
  16. '\n📊 Track progress at:' +
  17. `\n${Settings.adminUrl}/admin/script-log/${log._id}` +
  18. '\n==================================\n'
  19. )
  20. return log._id
  21. }
  22. async function afterScriptExecution(logId, status) {
  23. await ScriptLog.findByIdAndUpdate(logId, { status, endTime: new Date() })
  24. }
  25. /**
  26. * @param {(trackProgress: (progress: string) => Promise<void>) => Promise<any>} main - Main function for the script
  27. * @param {Object} vars - Variables to be used in the script
  28. * @param {string} canonicalName - The canonical name of the script, default to filename
  29. * @param {string} scriptPath - The file path of the script, default to process.argv[1]
  30. * @returns {Promise<void>}
  31. * @async
  32. */
  33. export async function scriptRunner(
  34. main,
  35. vars = {},
  36. canonicalName = process.argv[1].split('/').pop().split('.')[0],
  37. scriptPath = process.argv[1]
  38. ) {
  39. const isSaaS = Boolean(Settings.overleaf)
  40. if (!isSaaS) {
  41. await main(async message => {
  42. console.warn(message)
  43. })
  44. return
  45. }
  46. const logId = await beforeScriptExecution(canonicalName, vars, scriptPath)
  47. async function trackProgress(message) {
  48. try {
  49. console.warn(message)
  50. await ScriptLog.findByIdAndUpdate(logId, {
  51. $push: {
  52. progressLogs: {
  53. timestamp: new Date(),
  54. message,
  55. },
  56. },
  57. })
  58. } catch (error) {
  59. console.error('Error tracking progress:', error)
  60. }
  61. }
  62. try {
  63. await main(trackProgress)
  64. } catch (error) {
  65. await afterScriptExecution(logId, 'error')
  66. throw error
  67. }
  68. await afterScriptExecution(logId, 'success')
  69. }