@whyour/qinglong 2.21.0-8 → 2.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (265) hide show
  1. package/.dockerignore +13 -0
  2. package/.env.example +7 -0
  3. package/AGENTS.md +2 -2
  4. package/README-en.md +24 -0
  5. package/README.md +24 -0
  6. package/back/protos/api.proto +6 -1
  7. package/back/protos/cron.proto +4 -1
  8. package/docker/Dockerfile +31 -12
  9. package/docker/Dockerfile.310 +31 -12
  10. package/docker/Dockerfile.debian +22 -14
  11. package/docker/Dockerfile.debian310 +24 -14
  12. package/docker/build-manifest.cjs +28 -0
  13. package/docker/verify-build.cjs +49 -0
  14. package/docs/releases/2.22.0-validation.md +49 -0
  15. package/docs/releases/2.22.0.md +54 -0
  16. package/ecosystem.config.js +10 -1
  17. package/package.json +11 -6
  18. package/sample/config.sample.sh +10 -0
  19. package/sample/notify.js +54 -0
  20. package/sample/notify.py +37 -0
  21. package/scripts/benchmark-execution.cjs +96 -0
  22. package/scripts/write-build-info.cjs +27 -0
  23. package/shell/api.sh +34 -13
  24. package/shell/check.sh +59 -19
  25. package/shell/lang/en.sh +6 -0
  26. package/shell/lang/zh.sh +6 -0
  27. package/shell/node_path_cache.sh +128 -0
  28. package/shell/otask.sh +7 -1
  29. package/shell/preload/sitecustomize.js +5 -1
  30. package/shell/share.sh +25 -8
  31. package/shell/start.sh +6 -3
  32. package/shell/task.sh +13 -3
  33. package/shell/update.sh +65 -4
  34. package/static/build/api/clientIp.js +42 -0
  35. package/static/build/api/config.js +8 -16
  36. package/static/build/api/cron.js +38 -2
  37. package/static/build/api/dashboard.js +37 -0
  38. package/static/build/api/health.js +2 -2
  39. package/static/build/api/index.js +4 -0
  40. package/static/build/api/log.js +30 -19
  41. package/static/build/api/retention.js +63 -0
  42. package/static/build/api/script.js +23 -22
  43. package/static/build/api/subscription.js +16 -2
  44. package/static/build/api/system.js +25 -2
  45. package/static/build/api/user.js +75 -15
  46. package/static/build/app.js +54 -45
  47. package/static/build/bootstrap/database.js +51 -0
  48. package/static/build/config/const.js +1 -0
  49. package/static/build/config/share.js +5 -4
  50. package/static/build/config/util.js +133 -38
  51. package/static/build/data/cron.js +1 -0
  52. package/static/build/data/notify.js +11 -1
  53. package/static/build/loaders/app.js +2 -0
  54. package/static/build/loaders/db.js +3 -33
  55. package/static/build/loaders/deps.js +29 -0
  56. package/static/build/loaders/express.js +30 -21
  57. package/static/build/loaders/initData.js +10 -7
  58. package/static/build/loaders/sock.js +72 -6
  59. package/static/build/middlewares/monitoring.js +12 -33
  60. package/static/build/middlewares/protectedPathCase.js +17 -0
  61. package/static/build/protos/api.js +56 -2
  62. package/static/build/protos/cron.js +21 -4
  63. package/static/build/protos/health.js +1 -1
  64. package/static/build/schedule/addCron.js +9 -0
  65. package/static/build/schedule/api.js +5 -2
  66. package/static/build/schedule/client.js +38 -6
  67. package/static/build/schedule/health.js +72 -7
  68. package/static/build/services/config.js +5 -42
  69. package/static/build/services/cron.js +338 -199
  70. package/static/build/services/dependence.js +47 -0
  71. package/static/build/services/grpc.js +1 -1
  72. package/static/build/services/health.js +4 -7
  73. package/static/build/services/http.js +8 -2
  74. package/static/build/services/log.js +2 -3
  75. package/static/build/services/metrics.js +46 -14
  76. package/static/build/services/notify.js +26 -0
  77. package/static/build/services/retention.js +123 -0
  78. package/static/build/services/schedule.js +57 -33
  79. package/static/build/services/script.js +4 -5
  80. package/static/build/services/subscription.js +55 -34
  81. package/static/build/services/system.js +37 -9
  82. package/static/build/services/user.js +213 -25
  83. package/static/build/shared/auth.js +18 -5
  84. package/static/build/shared/authMutation.js +17 -0
  85. package/static/build/shared/childProcess.js +82 -0
  86. package/static/build/shared/clientIp.js +27 -0
  87. package/static/build/shared/errors.js +9 -0
  88. package/static/build/shared/fileAccess.js +60 -0
  89. package/static/build/shared/i18n.js +12 -5
  90. package/static/build/shared/logReader.js +85 -0
  91. package/static/build/shared/logStreamManager.js +80 -60
  92. package/static/build/shared/password.js +30 -0
  93. package/static/build/shared/retention.js +58 -0
  94. package/static/build/shared/runCron.js +28 -15
  95. package/static/build/shared/schedulerMutationLock.js +44 -0
  96. package/static/build/shared/schedulerReadiness.js +82 -0
  97. package/static/build/shared/schemaMigrations.js +58 -0
  98. package/static/build/shared/startupProcess.js +48 -0
  99. package/static/build/shared/store.js +7 -0
  100. package/static/build/shared/trustProxy.js +119 -0
  101. package/static/build/validation/schedule.js +3 -3
  102. package/static/dist/{1885.e1ea09f6.async.js → 1885.b8f427bf.async.js} +1 -1
  103. package/static/dist/2031.6af40025.async.js +1 -0
  104. package/static/dist/2693.51c2636b.async.js +1 -0
  105. package/static/dist/{2890.9e373f5b.async.js → 2890.add55e85.async.js} +1 -1
  106. package/static/dist/2901.2ca95295.async.js +1 -0
  107. package/static/dist/445.a65ff63b.async.js +1 -0
  108. package/static/dist/4736.1d2b5cb6.async.js +1 -0
  109. package/static/dist/{4859.6592cebb.async.js → 4859.97d6653c.async.js} +1 -1
  110. package/static/dist/{6013.4e38de36.async.js → 6013.db535339.async.js} +1 -1
  111. package/static/dist/6212.9e6d9913.async.js +1 -0
  112. package/static/dist/{6339.ab305e96.async.js → 6431.4603ad0e.async.js} +1 -1
  113. package/static/dist/{6872.42f939f1.async.js → 6872.a503ef55.async.js} +1 -1
  114. package/static/dist/7231.f7e5b668.async.js +1 -0
  115. package/static/dist/{7355.f9f263d8.async.js → 7355.fca746f5.async.js} +1 -1
  116. package/static/dist/{7508.7dcee91c.async.js → 7508.d90eac63.async.js} +1 -1
  117. package/static/dist/{7984.594296a5.async.js → 7984.eaac7402.async.js} +1 -1
  118. package/static/dist/8844.a0fef08e.async.js +1 -0
  119. package/static/dist/index.html +2 -2
  120. package/static/dist/layouts__index.633d3553.async.js +1 -0
  121. package/static/dist/preload_helper.cf7de3fa.js +1 -0
  122. package/static/dist/{src__pages__config__index.a22ff7dc.async.js → src__pages__config__index.9aba4054.async.js} +1 -1
  123. package/static/dist/src__pages__crontab__detail.86b2eebb.async.js +1 -0
  124. package/static/dist/src__pages__crontab__index.ae4e06f2.async.js +1 -0
  125. package/static/dist/{src__pages__crontab__logModal.831d5e4b.async.js → src__pages__crontab__logModal.930535e2.async.js} +1 -1
  126. package/static/dist/src__pages__crontab__modal.a2c8fdcc.async.js +1 -0
  127. package/static/dist/src__pages__crontab__viewCreateModal.7b4f9cbe.async.js +1 -0
  128. package/static/dist/src__pages__crontab__viewManageModal.cd454ea0.async.js +1 -0
  129. package/static/dist/src__pages__dashboard__index.243c5a35.async.js +1 -0
  130. package/static/dist/src__pages__dashboard__taskResultModal.7795d6e1.async.js +1 -0
  131. package/static/dist/src__pages__dependence__index.874d501f.async.js +1 -0
  132. package/static/dist/src__pages__dependence__logModal.154efe7a.async.js +1 -0
  133. package/static/dist/src__pages__dependence__modal.a29c1a0f.async.js +1 -0
  134. package/static/dist/{src__pages__diff__index.013b7c75.async.js → src__pages__diff__index.1714b941.async.js} +1 -1
  135. package/static/dist/src__pages__env__editNameModal.c13d47d2.async.js +1 -0
  136. package/static/dist/src__pages__env__index.fd6fd2b0.async.js +1 -0
  137. package/static/dist/src__pages__env__modal.4d71adb3.async.js +1 -0
  138. package/static/dist/src__pages__error__index.aae50c94.async.js +1 -0
  139. package/static/dist/src__pages__initialization__index.82a2e967.async.js +1 -0
  140. package/static/dist/src__pages__log__index.71250e0d.async.js +1 -0
  141. package/static/dist/{src__pages__login__index.8c813eb1.async.js → src__pages__login__index.a0fd5ed8.async.js} +1 -1
  142. package/static/dist/src__pages__script__editModal.22acdf7c.async.js +1 -0
  143. package/static/dist/src__pages__script__editNameModal.1a521cc0.async.js +1 -0
  144. package/static/dist/src__pages__script__index.a18b2692.async.js +1 -0
  145. package/static/dist/src__pages__script__renameModal.0ab029e7.async.js +1 -0
  146. package/static/dist/src__pages__script__saveModal.8965b74c.async.js +1 -0
  147. package/static/dist/src__pages__script__setting.35ad4f02.async.js +1 -0
  148. package/static/dist/src__pages__setting__appModal.7eaeb9d3.async.js +1 -0
  149. package/static/dist/{src__pages__setting__checkUpdate.34d773f2.async.js → src__pages__setting__checkUpdate.d175b154.async.js} +1 -1
  150. package/static/dist/src__pages__setting__clientIp.3a8711ed.async.js +1 -0
  151. package/static/dist/src__pages__setting__dependence.9c0f749b.async.js +1 -0
  152. package/static/dist/src__pages__setting__index.cb397741.async.js +1 -0
  153. package/static/dist/src__pages__setting__loginLog.e0a1f54d.async.js +1 -0
  154. package/static/dist/src__pages__setting__notification.2ffe4e5a.async.js +1 -0
  155. package/static/dist/src__pages__setting__other.3d0b8492.async.js +1 -0
  156. package/static/dist/{src__pages__setting__progress.8823ac90.async.js → src__pages__setting__progress.2ccae3d7.async.js} +1 -1
  157. package/static/dist/src__pages__setting__security.e2d71ebb.async.js +1 -0
  158. package/static/dist/src__pages__setting__systemLog.b3046955.async.js +1 -0
  159. package/static/dist/src__pages__subscription__index.43086a06.async.js +1 -0
  160. package/static/dist/src__pages__subscription__logModal.cdba5139.async.js +1 -0
  161. package/static/dist/src__pages__subscription__modal.38991e1e.async.js +1 -0
  162. package/static/dist/{umi.a54a59f6.js → umi.fc019050.js} +1 -1
  163. package/test/back/auth-security.test.cjs +74 -0
  164. package/test/back/build-provenance.test.cjs +150 -0
  165. package/test/back/cron-log-name.test.cjs +110 -0
  166. package/test/back/cron-validation.test.cjs +45 -0
  167. package/test/back/dashboard-failures.test.cjs +173 -0
  168. package/test/back/database-bootstrap.test.cjs +193 -0
  169. package/test/back/dependence-cache-status.test.cjs +125 -0
  170. package/test/back/deprecated-file-routes.test.cjs +82 -0
  171. package/test/back/ecosystem.test.cjs +28 -0
  172. package/test/back/env-name-parsing.test.cjs +96 -0
  173. package/test/back/execution-lifecycle.test.cjs +236 -0
  174. package/test/back/file-access-security.test.cjs +47 -0
  175. package/test/back/fileTreeListing.test.cjs +57 -0
  176. package/test/back/grpc-cron-response.test.cjs +60 -0
  177. package/test/back/http-exclusive-listen.test.cjs +31 -0
  178. package/test/back/http-security.test.cjs +213 -0
  179. package/test/back/listen-security.test.cjs +67 -0
  180. package/test/back/log-path-security.test.cjs +158 -0
  181. package/test/back/logReader.test.cjs +72 -0
  182. package/test/back/manual-execution.test.cjs +85 -0
  183. package/test/back/manual-stop-claim.test.cjs +220 -0
  184. package/test/back/metrics.test.cjs +34 -0
  185. package/test/back/monitoring.test.cjs +73 -0
  186. package/test/back/node-path-cache.test.cjs +173 -0
  187. package/test/back/node-path-lock.test.cjs +178 -0
  188. package/test/back/npm-publication.test.cjs +70 -0
  189. package/test/back/primary-apm.test.cjs +24 -0
  190. package/test/back/process-exit-state.test.cjs +81 -0
  191. package/test/back/process-stop-signal.test.cjs +77 -0
  192. package/test/back/protected-path-case.test.cjs +58 -0
  193. package/test/back/qlServiceLogCommand.test.cjs +128 -0
  194. package/test/back/retention.test.cjs +131 -0
  195. package/test/back/role-loading.test.cjs +118 -0
  196. package/test/back/schedule-health.test.cjs +86 -0
  197. package/test/back/scheduler-file-lock.test.cjs +51 -0
  198. package/test/back/scheduler-mutation.test.cjs +312 -0
  199. package/test/back/scheduler-readiness.test.cjs +85 -0
  200. package/test/back/scheduler-reconciliation.test.cjs +152 -0
  201. package/test/back/scheduler-rpc-timeout.test.cjs +49 -0
  202. package/test/back/schema-migrations.test.cjs +127 -0
  203. package/test/back/shell-api-parsing.test.cjs +184 -0
  204. package/test/back/sock-polling.test.cjs +297 -0
  205. package/test/back/sock-security.test.cjs +72 -0
  206. package/test/back/start-env-preservation.test.cjs +53 -0
  207. package/test/back/stop-failure-feedback.test.cjs +158 -0
  208. package/test/back/stop-race.test.cjs +167 -0
  209. package/test/back/subscription-cleanup.test.cjs +53 -0
  210. package/test/back/subscription-stop-state.test.cjs +66 -0
  211. package/test/back/system-dependence-cache.test.cjs +126 -0
  212. package/test/back/task-time.test.cjs +116 -0
  213. package/test/back/user-api.test.cjs +99 -0
  214. package/test/back/user-security.test.cjs +248 -0
  215. package/test/back/worker-apm.test.cjs +84 -0
  216. package/test/back/wpush-grpc.test.cjs +115 -0
  217. package/test/front/cron-log-pagination.test.cjs +214 -0
  218. package/test/front/http-auth.test.cjs +152 -0
  219. package/test/front/http-error.test.cjs +29 -0
  220. package/test/helpers/load-security-module.cjs +42 -0
  221. package/version.yaml +19 -34
  222. package/CLAUDE.md +0 -43
  223. package/static/dist/1147.62793604.async.js +0 -1
  224. package/static/dist/134.54df9e38.async.js +0 -1
  225. package/static/dist/2208.85285476.async.js +0 -1
  226. package/static/dist/2286.f371c743.async.js +0 -1
  227. package/static/dist/3191.545ab873.async.js +0 -1
  228. package/static/dist/4902.555f92ab.async.js +0 -1
  229. package/static/dist/5520.ff2cfd6b.async.js +0 -1
  230. package/static/dist/6431.c50479be.async.js +0 -1
  231. package/static/dist/8826.db34ad8d.async.js +0 -1
  232. package/static/dist/layouts__index.a7a2bfe0.async.js +0 -1
  233. package/static/dist/preload_helper.3048fe5b.js +0 -1
  234. package/static/dist/src__pages__crontab__detail.b98f0084.async.js +0 -1
  235. package/static/dist/src__pages__crontab__index.68e78a33.async.js +0 -1
  236. package/static/dist/src__pages__crontab__modal.f7041c7c.async.js +0 -1
  237. package/static/dist/src__pages__crontab__viewCreateModal.4d589f66.async.js +0 -1
  238. package/static/dist/src__pages__crontab__viewManageModal.0e317746.async.js +0 -1
  239. package/static/dist/src__pages__dashboard__index.58177357.async.js +0 -1
  240. package/static/dist/src__pages__dependence__index.b7bbc795.async.js +0 -1
  241. package/static/dist/src__pages__dependence__logModal.0681830b.async.js +0 -1
  242. package/static/dist/src__pages__dependence__modal.f7bb47ba.async.js +0 -1
  243. package/static/dist/src__pages__env__editNameModal.48715576.async.js +0 -1
  244. package/static/dist/src__pages__env__index.452cdc47.async.js +0 -1
  245. package/static/dist/src__pages__env__modal.e1234834.async.js +0 -1
  246. package/static/dist/src__pages__error__index.dedb2b90.async.js +0 -1
  247. package/static/dist/src__pages__initialization__index.22620a77.async.js +0 -1
  248. package/static/dist/src__pages__log__index.9c66639f.async.js +0 -1
  249. package/static/dist/src__pages__script__editModal.cbf4ec0e.async.js +0 -1
  250. package/static/dist/src__pages__script__editNameModal.532a3044.async.js +0 -1
  251. package/static/dist/src__pages__script__index.1fc20f22.async.js +0 -1
  252. package/static/dist/src__pages__script__renameModal.5cdde919.async.js +0 -1
  253. package/static/dist/src__pages__script__saveModal.5ffed35f.async.js +0 -1
  254. package/static/dist/src__pages__script__setting.1a82c6d7.async.js +0 -1
  255. package/static/dist/src__pages__setting__appModal.43b7758a.async.js +0 -1
  256. package/static/dist/src__pages__setting__dependence.9c04c79a.async.js +0 -1
  257. package/static/dist/src__pages__setting__index.7e070838.async.js +0 -1
  258. package/static/dist/src__pages__setting__loginLog.cea6056c.async.js +0 -1
  259. package/static/dist/src__pages__setting__notification.bac481c2.async.js +0 -1
  260. package/static/dist/src__pages__setting__other.707cfafe.async.js +0 -1
  261. package/static/dist/src__pages__setting__security.b7235753.async.js +0 -1
  262. package/static/dist/src__pages__setting__systemLog.b81a8c1d.async.js +0 -1
  263. package/static/dist/src__pages__subscription__index.d0ab2abc.async.js +0 -1
  264. package/static/dist/src__pages__subscription__logModal.3864b37f.async.js +0 -1
  265. package/static/dist/src__pages__subscription__modal.562448e2.async.js +0 -1
@@ -15,6 +15,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
15
15
  return (mod && mod.__esModule) ? mod : { "default": mod };
16
16
  };
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
+ const crypto_1 = require("crypto");
19
+ const schedulerMutationLock_1 = require("../shared/schedulerMutationLock");
18
20
  const typedi_1 = require("typedi");
19
21
  const winston_1 = __importDefault(require("winston"));
20
22
  const config_1 = __importDefault(require("../config"));
@@ -37,7 +39,10 @@ const utils_1 = require("../shared/utils");
37
39
  const i18n_1 = require("../shared/i18n");
38
40
  const schedule_1 = require("../interface/schedule");
39
41
  const logStreamManager_1 = require("../shared/logStreamManager");
42
+ const childProcess_1 = require("../shared/childProcess");
40
43
  const lodash_1 = require("lodash");
44
+ const logReader_1 = require("../shared/logReader");
45
+ const fileAccess_1 = require("../shared/fileAccess");
41
46
  let CronService = class CronService {
42
47
  constructor(logger) {
43
48
  this.logger = logger;
@@ -97,91 +102,94 @@ let CronService = class CronService {
97
102
  return uniqPath;
98
103
  }
99
104
  async create(payload) {
100
- const tab = new cron_1.Crontab(payload);
101
- tab.saved = false;
102
- tab.log_name = await this.getLogName(tab);
103
- const doc = await this.insert(tab);
104
- if ((0, util_1.isDemoEnv)()) {
105
- return doc;
106
- }
107
- if (this.shouldUseCronClient(doc)) {
108
- try {
109
- await client_1.default.addCron([
110
- {
111
- name: doc.name || '',
112
- id: String(doc.id),
113
- schedule: doc.schedule,
114
- command: this.makeCommand(doc),
115
- extra_schedules: doc.extra_schedules || [],
116
- },
117
- ]);
105
+ return (0, schedulerMutationLock_1.withSchedulerMutation)(async () => {
106
+ const tab = new cron_1.Crontab(payload);
107
+ tab.saved = false;
108
+ tab.log_name = await this.getLogName(tab);
109
+ const doc = await this.insert(tab);
110
+ if ((0, util_1.isDemoEnv)()) {
111
+ return doc;
118
112
  }
119
- catch (error) {
120
- // gRPC 注册失败时回滚 DB 记录,避免产生"僵尸任务"
121
- // (DB 和 crontab.list 有记录但调度器永远不会执行)
122
- await cron_1.CrontabModel.destroy({ where: { id: doc.id } });
123
- this.logger.error('[crontab] Failed to register cron job in scheduler, task creation rolled back:', (error === null || error === void 0 ? void 0 : error.message) || error);
124
- throw new Error(`${(0, i18n_1.t)('调度器注册失败,任务创建已回滚')}: ${(error === null || error === void 0 ? void 0 : error.details) || (error === null || error === void 0 ? void 0 : error.message)}`);
113
+ if (this.shouldUseCronClient(doc)) {
114
+ try {
115
+ await client_1.default.addCron([
116
+ {
117
+ name: doc.name || '',
118
+ id: String(doc.id),
119
+ schedule: doc.schedule,
120
+ command: this.makeCommand(doc),
121
+ extra_schedules: doc.extra_schedules || [],
122
+ },
123
+ ]);
124
+ }
125
+ catch (error) {
126
+ // gRPC 注册失败时回滚 DB 记录,避免产生"僵尸任务"
127
+ // (DB 和 crontab.list 有记录但调度器永远不会执行)
128
+ await cron_1.CrontabModel.destroy({ where: { id: doc.id } });
129
+ this.logger.error('[crontab] Failed to register cron job in scheduler, task creation rolled back:', (error === null || error === void 0 ? void 0 : error.message) || error);
130
+ throw (0, schedulerMutationLock_1.schedulerRegistrationError)(`${(0, i18n_1.t)('调度器注册失败,任务创建已回滚')}: ${(error === null || error === void 0 ? void 0 : error.details) || (error === null || error === void 0 ? void 0 : error.message)}`, error);
131
+ }
125
132
  }
126
- }
127
- await this.setCrontab();
128
- return doc;
133
+ await this.setCrontab();
134
+ return doc;
135
+ });
129
136
  }
130
137
  async insert(payload) {
131
138
  return await cron_1.CrontabModel.create(payload, { returning: true });
132
139
  }
133
140
  async update(payload) {
134
- const doc = await this.getDb({ id: payload.id });
135
- const tab = new cron_1.Crontab(Object.assign(Object.assign({}, doc), payload));
136
- tab.saved = false;
137
- tab.log_name = await this.getLogName(tab);
138
- const newDoc = await this.updateDb(tab);
139
- if (doc.isDisabled === 1 || (0, util_1.isDemoEnv)()) {
140
- return newDoc;
141
- }
142
- try {
143
- await client_1.default.delCron([String(newDoc.id)]);
144
- }
145
- catch (error) {
146
- this.logger.warn('[crontab] Failed to unregister cron job in scheduler:', (error === null || error === void 0 ? void 0 : error.message) || error);
147
- }
148
- if (this.shouldUseCronClient(newDoc)) {
149
- try {
150
- await client_1.default.addCron([
151
- {
152
- name: doc.name || '',
153
- id: String(newDoc.id),
154
- schedule: newDoc.schedule,
155
- command: this.makeCommand(newDoc),
156
- extra_schedules: newDoc.extra_schedules || [],
157
- },
158
- ]);
141
+ return (0, schedulerMutationLock_1.withSchedulerMutation)(async () => {
142
+ const doc = await this.getDb({ id: payload.id });
143
+ const tab = new cron_1.Crontab(Object.assign(Object.assign({}, doc), payload));
144
+ tab.saved = false;
145
+ tab.log_name = await this.getLogName(tab);
146
+ if (doc.isDisabled === 1 || (0, util_1.isDemoEnv)()) {
147
+ return await this.updateDb(tab);
159
148
  }
160
- catch (error) {
161
- // gRPC 注册新任务失败 → 回滚 DB 到旧数据,并尝试恢复旧调度注册
162
- await cron_1.CrontabModel.update(doc, { where: { id: doc.id } });
163
- if (this.shouldUseCronClient(doc)) {
164
- try {
165
- await client_1.default.addCron([
166
- {
167
- name: doc.name || '',
168
- id: String(doc.id),
169
- schedule: doc.schedule,
170
- command: this.makeCommand(doc),
171
- extra_schedules: doc.extra_schedules || [],
172
- },
173
- ]);
174
- }
175
- catch (_recoveryError) {
176
- this.logger.warn('[crontab] Failed to restore old cron job in scheduler after rollback:', (_recoveryError === null || _recoveryError === void 0 ? void 0 : _recoveryError.message) || _recoveryError);
149
+ // Keep the DB snapshot unchanged if deletion has an uncertain outcome.
150
+ // Recovery uses that snapshot after this mutation releases its lock.
151
+ await client_1.default.delCron([String(doc.id)]);
152
+ const newDoc = await this.updateDb(tab);
153
+ if (this.shouldUseCronClient(newDoc)) {
154
+ try {
155
+ await client_1.default.addCron([
156
+ {
157
+ name: doc.name || '',
158
+ id: String(newDoc.id),
159
+ schedule: newDoc.schedule,
160
+ command: this.makeCommand(newDoc),
161
+ extra_schedules: newDoc.extra_schedules || [],
162
+ },
163
+ ]);
164
+ }
165
+ catch (error) {
166
+ // gRPC 注册新任务失败 → 回滚 DB 到旧数据,并尝试恢复旧调度注册
167
+ await cron_1.CrontabModel.update((0, omit_1.default)(doc, ['queued_token']), {
168
+ where: { id: doc.id },
169
+ });
170
+ if (this.shouldUseCronClient(doc)) {
171
+ try {
172
+ await client_1.default.addCron([
173
+ {
174
+ name: doc.name || '',
175
+ id: String(doc.id),
176
+ schedule: doc.schedule,
177
+ command: this.makeCommand(doc),
178
+ extra_schedules: doc.extra_schedules || [],
179
+ },
180
+ ]);
181
+ }
182
+ catch (_recoveryError) {
183
+ this.logger.warn('[crontab] Failed to restore old cron job in scheduler after rollback:', (_recoveryError === null || _recoveryError === void 0 ? void 0 : _recoveryError.message) || _recoveryError);
184
+ }
177
185
  }
186
+ this.logger.error('[crontab] Failed to register updated cron job in scheduler, update rolled back:', (error === null || error === void 0 ? void 0 : error.message) || error);
187
+ throw (0, schedulerMutationLock_1.schedulerRegistrationError)(`${(0, i18n_1.t)('调度器注册失败,任务更新已回滚')}: ${(error === null || error === void 0 ? void 0 : error.details) || (error === null || error === void 0 ? void 0 : error.message)}`, error);
178
188
  }
179
- this.logger.error('[crontab] Failed to register updated cron job in scheduler, update rolled back:', (error === null || error === void 0 ? void 0 : error.message) || error);
180
- throw new Error(`${(0, i18n_1.t)('调度器注册失败,任务更新已回滚')}: ${(error === null || error === void 0 ? void 0 : error.details) || (error === null || error === void 0 ? void 0 : error.message)}`);
181
189
  }
182
- }
183
- await this.setCrontab();
184
- return newDoc;
190
+ await this.setCrontab();
191
+ return newDoc;
192
+ });
185
193
  }
186
194
  async updateDb(payload) {
187
195
  await cron_1.CrontabModel.update(payload, { where: { id: payload.id } });
@@ -242,14 +250,11 @@ let CronService = class CronService {
242
250
  }
243
251
  }
244
252
  async remove(ids) {
245
- await cron_1.CrontabModel.destroy({ where: { id: ids } });
246
- try {
253
+ return (0, schedulerMutationLock_1.withSchedulerMutation)(async () => {
247
254
  await client_1.default.delCron(ids.map(String));
248
- }
249
- catch (error) {
250
- this.logger.warn('[crontab] Failed to unregister cron job in scheduler:', (error === null || error === void 0 ? void 0 : error.message) || error);
251
- }
252
- await this.setCrontab();
255
+ await cron_1.CrontabModel.destroy({ where: { id: ids } });
256
+ await this.setCrontab();
257
+ });
253
258
  }
254
259
  async pin(ids) {
255
260
  await cron_1.CrontabModel.update({ isPinned: 1 }, { where: { id: ids } });
@@ -492,31 +497,82 @@ let CronService = class CronService {
492
497
  return doc.get({ plain: true });
493
498
  }
494
499
  async run(ids) {
495
- await cron_1.CrontabModel.update({ status: cron_1.CrontabStatus.queued }, { where: { id: ids } });
500
+ const queuedToken = (0, crypto_1.randomUUID)();
501
+ await cron_1.CrontabModel.update({ status: cron_1.CrontabStatus.queued, queued_token: queuedToken }, { where: { id: ids } });
496
502
  ids.forEach((id) => {
497
- this.runSingle(id);
503
+ this.runSingle(id, queuedToken);
498
504
  });
499
505
  }
500
506
  async stop(ids) {
507
+ var _a, _b, _c, _d, _e;
501
508
  const docs = await cron_1.CrontabModel.findAll({ where: { id: ids } });
509
+ // Cancel the queued snapshot first, so a late spawn cannot claim it.
502
510
  for (const doc of docs) {
503
- // Kill all running instances of this task
511
+ if (doc.status === cron_1.CrontabStatus.queued) {
512
+ const [cancelled] = await cron_1.CrontabModel.update({ status: cron_1.CrontabStatus.idle, pid: null, queued_token: null }, {
513
+ where: {
514
+ id: doc.id,
515
+ status: cron_1.CrontabStatus.queued,
516
+ [sequelize_1.Op.and]: [
517
+ (0, sequelize_1.where)((0, sequelize_1.col)('log_path'), { [sequelize_1.Op.eq]: (_a = doc.log_path) !== null && _a !== void 0 ? _a : null }),
518
+ (0, sequelize_1.where)((0, sequelize_1.col)('queued_token'), {
519
+ [sequelize_1.Op.eq]: (_b = doc.queued_token) !== null && _b !== void 0 ? _b : null,
520
+ }),
521
+ ],
522
+ },
523
+ });
524
+ // A concurrent claim may have won; capture its PID before signalling.
525
+ if (!cancelled)
526
+ await doc.reload();
527
+ }
528
+ }
529
+ const stoppingInstances = await runningInstance_1.RunningInstanceModel.findAll({
530
+ attributes: ['id', 'pid', 'cron_id'],
531
+ where: { cron_id: ids, status: runningInstance_1.InstanceStatus.running },
532
+ });
533
+ const targets = new Set([
534
+ ...stoppingInstances.map((instance) => instance.pid),
535
+ ...docs
536
+ .filter((doc) => doc.status === cron_1.CrontabStatus.running)
537
+ .map((doc) => doc.pid),
538
+ ].filter((pid) => typeof pid === 'number' && pid > 0));
539
+ const stopped = new Set();
540
+ for (const pid of targets) {
504
541
  try {
505
- if (doc.pid) {
506
- await (0, util_1.killTask)(doc.pid);
507
- }
508
- const command = doc.command.replace(/\s+/g, ' ').trim();
509
- await (0, util_1.killAllTasks)(command);
510
- this.logger.info(`[panel][停止所有运行中的任务实例] 任务ID: ${doc.id}, 命令: ${command}`);
542
+ await (0, util_1.killTask)(pid, true);
543
+ stopped.add(pid);
511
544
  }
512
545
  catch (error) {
513
- this.logger.error(`[panel][停止任务失败] 任务ID: ${doc.id}, 错误: ${error}`);
546
+ this.logger.error('[panel][停止任务失败] PID: %s, 错误: %s', pid, (0, childProcess_1.asError)(error).message);
514
547
  }
515
548
  }
516
- // Mark all running instances as stopped
517
- const finishedAt = (0, dayjs_1.default)().unix();
518
- await runningInstance_1.RunningInstanceModel.update({ status: runningInstance_1.InstanceStatus.stopped, finished_at: finishedAt }, { where: { cron_id: ids, status: runningInstance_1.InstanceStatus.running } });
519
- await cron_1.CrontabModel.update({ status: cron_1.CrontabStatus.idle, pid: undefined }, { where: { id: ids } });
549
+ const stoppedIds = stoppingInstances
550
+ .filter((instance) => instance.pid && stopped.has(instance.pid))
551
+ .map((instance) => instance.id);
552
+ if (stoppedIds.length) {
553
+ await runningInstance_1.RunningInstanceModel.update({ status: runningInstance_1.InstanceStatus.stopped, finished_at: (0, dayjs_1.default)().unix() }, { where: { id: stoppedIds } });
554
+ }
555
+ for (const doc of docs) {
556
+ if (doc.status !== cron_1.CrontabStatus.running ||
557
+ (doc.pid && !stopped.has(doc.pid)))
558
+ continue;
559
+ const remaining = await runningInstance_1.RunningInstanceModel.count({
560
+ where: { cron_id: doc.id, status: runningInstance_1.InstanceStatus.running },
561
+ });
562
+ if (remaining)
563
+ continue;
564
+ await cron_1.CrontabModel.update({ status: cron_1.CrontabStatus.idle, pid: null, queued_token: null }, {
565
+ where: {
566
+ id: doc.id,
567
+ status: cron_1.CrontabStatus.running,
568
+ [sequelize_1.Op.and]: [
569
+ (0, sequelize_1.where)((0, sequelize_1.col)('queued_token'), { [sequelize_1.Op.eq]: (_c = doc.queued_token) !== null && _c !== void 0 ? _c : null }),
570
+ (0, sequelize_1.where)((0, sequelize_1.col)('pid'), { [sequelize_1.Op.eq]: (_d = doc.pid) !== null && _d !== void 0 ? _d : null }),
571
+ (0, sequelize_1.where)((0, sequelize_1.col)('log_path'), { [sequelize_1.Op.eq]: (_e = doc.log_path) !== null && _e !== void 0 ? _e : null }),
572
+ ],
573
+ },
574
+ });
575
+ }
520
576
  }
521
577
  async stopInstance(instanceId) {
522
578
  const instance = await runningInstance_1.RunningInstanceModel.findOne({
@@ -543,108 +599,190 @@ let CronService = class CronService {
543
599
  }
544
600
  return { code: 200, message: (0, i18n_1.t)('实例已停止') };
545
601
  }
546
- async runSingle(cronId) {
547
- return pLimit_1.default.manualRunWithCronLimit(() => {
548
- return new Promise(async (resolve) => {
602
+ async runSingle(cronId, expectedToken) {
603
+ return pLimit_1.default.manualRunWithCronLimit(async () => {
604
+ var _a, _b;
605
+ let absolutePath;
606
+ let logPath;
607
+ let queuedLogPath;
608
+ let queuedToken = null;
609
+ let claimed = false;
610
+ try {
549
611
  const cron = await this.getDb({ id: cronId });
550
- const params = {
551
- name: cron.name,
552
- command: cron.command,
553
- schedule: cron.schedule,
554
- extra_schedules: cron.extra_schedules,
555
- };
556
- if (cron.status !== cron_1.CrontabStatus.queued) {
557
- resolve(params);
612
+ if (cron.status !== cron_1.CrontabStatus.queued ||
613
+ (expectedToken !== undefined && cron.queued_token !== expectedToken))
558
614
  return;
559
- }
560
- this.logger.info(`[panel][开始执行任务] 参数: ${JSON.stringify(params)}`);
561
- let { id, command, log_name } = cron;
615
+ queuedToken = (_a = cron.queued_token) !== null && _a !== void 0 ? _a : null;
616
+ queuedLogPath = (_b = cron.log_path) !== null && _b !== void 0 ? _b : null;
617
+ const { id, command, log_name } = cron;
562
618
  const uniqPath = log_name === '/dev/null' || !log_name
563
619
  ? await (0, util_1.getUniqPath)(command, `${id}`)
564
620
  : log_name;
565
621
  const logTime = (0, dayjs_1.default)().format('YYYY-MM-DD-HH-mm-ss-SSS');
566
- const logDirPath = path_1.default.resolve(config_1.default.logPath, `${uniqPath}`);
567
- await promises_1.default.mkdir(logDirPath, { recursive: true });
568
- const logPath = `${uniqPath}/${logTime}.log`;
569
- const absolutePath = path_1.default.resolve(config_1.default.logPath, `${logPath}`);
622
+ logPath = `${uniqPath}/${logTime}.log`;
623
+ absolutePath = (0, fileAccess_1.resolveFileAccess)(config_1.default.logPath, [logPath]);
624
+ if (!absolutePath)
625
+ throw new Error('Log path is outside the log directory');
626
+ await promises_1.default.mkdir(path_1.default.dirname(absolutePath), { recursive: true });
627
+ const outputPath = absolutePath;
570
628
  const cp = (0, cross_spawn_1.spawn)(`real_log_path=${logPath} no_delay=true ${this.makeCommand(cron, true)}`, { shell: '/bin/bash' });
571
- await cron_1.CrontabModel.update({ status: cron_1.CrontabStatus.running, pid: cp.pid, log_path: logPath }, { where: { id } });
572
- cp.stdout.on('data', async (data) => {
573
- await logStreamManager_1.logStreamManager.write(absolutePath, data.toString());
574
- });
575
- cp.stderr.on('data', async (data) => {
576
- this.logger.info('[panel][执行任务失败] 命令: %s, 错误信息: %j', command, data.toString());
577
- await logStreamManager_1.logStreamManager.write(absolutePath, data.toString());
578
- });
579
- cp.on('error', async (err) => {
580
- this.logger.error('[panel][创建任务失败] 命令: %s, 错误信息: %j', command, err);
581
- await logStreamManager_1.logStreamManager.write(absolutePath, JSON.stringify(err));
582
- });
583
- cp.on('exit', async (code) => {
584
- this.logger.info('[panel][执行任务结束] 参数: %s, 退出码: %j', JSON.stringify(params), code);
585
- await logStreamManager_1.logStreamManager.closeStream(absolutePath);
586
- resolve(Object.assign(Object.assign({}, params), { pid: cp.pid, code }));
629
+ // Install observers before the first await: very short children may already exit.
630
+ const { completed } = (0, childProcess_1.observeChildProcess)(cp, {
631
+ onStart: async () => {
632
+ try {
633
+ const [count] = await cron_1.CrontabModel.update({
634
+ status: cron_1.CrontabStatus.running,
635
+ pid: cp.pid,
636
+ log_path: logPath,
637
+ }, {
638
+ where: {
639
+ id,
640
+ status: cron_1.CrontabStatus.queued,
641
+ [sequelize_1.Op.and]: [
642
+ (0, sequelize_1.where)((0, sequelize_1.col)('queued_token'), { [sequelize_1.Op.eq]: queuedToken }),
643
+ (0, sequelize_1.where)((0, sequelize_1.col)('log_path'), { [sequelize_1.Op.eq]: queuedLogPath }),
644
+ ],
645
+ },
646
+ });
647
+ if (count !== 1)
648
+ throw new Error('Task was stopped or superseded before startup');
649
+ claimed = true;
650
+ }
651
+ catch (error) {
652
+ if (cp.pid)
653
+ await (0, util_1.killTask)(cp.pid, true);
654
+ throw error;
655
+ }
656
+ },
657
+ onStdout: (message) => logStreamManager_1.logStreamManager.write(outputPath, message),
658
+ onStderr: (message) => logStreamManager_1.logStreamManager.write(outputPath, message),
587
659
  });
588
- });
660
+ const result = await completed;
661
+ if (result.error) {
662
+ this.logger.error('[panel][执行任务失败] 任务ID: %s, 错误: %s', id, result.error.message);
663
+ }
664
+ this.logger.info('[panel][执行任务结束] 任务ID: %s, 退出码: %j', id, result.code);
665
+ return Object.assign(Object.assign(Object.assign({}, cron), { pid: cp.pid }), result);
666
+ }
667
+ catch (error) {
668
+ this.logger.error('[panel][创建任务失败] 任务ID: %s, 错误: %s', cronId, (0, childProcess_1.asError)(error).message);
669
+ }
670
+ finally {
671
+ try {
672
+ if (absolutePath)
673
+ await logStreamManager_1.logStreamManager.closeStream(absolutePath);
674
+ }
675
+ catch (error) {
676
+ this.logger.error('[panel][关闭任务日志失败] %s', (0, childProcess_1.asError)(error).message);
677
+ }
678
+ try {
679
+ // Do not overwrite a newer run's state or its script-reported exit code.
680
+ await cron_1.CrontabModel.update({ status: cron_1.CrontabStatus.idle, pid: null, queued_token: null }, {
681
+ where: {
682
+ id: cronId,
683
+ [sequelize_1.Op.and]: (0, sequelize_1.where)((0, sequelize_1.col)('queued_token'), { [sequelize_1.Op.eq]: queuedToken }),
684
+ [sequelize_1.Op.or]: [
685
+ ...(queuedLogPath !== undefined && !claimed
686
+ ? [
687
+ {
688
+ status: cron_1.CrontabStatus.queued,
689
+ [sequelize_1.Op.and]: (0, sequelize_1.where)((0, sequelize_1.col)('log_path'), {
690
+ [sequelize_1.Op.eq]: queuedLogPath,
691
+ }),
692
+ },
693
+ ]
694
+ : []),
695
+ ...(claimed && logPath
696
+ ? [{ log_path: logPath, status: cron_1.CrontabStatus.running }]
697
+ : []),
698
+ ],
699
+ },
700
+ });
701
+ }
702
+ catch (error) {
703
+ this.logger.error('[panel][清理任务状态失败] %s', (0, childProcess_1.asError)(error).message);
704
+ }
705
+ }
589
706
  });
590
707
  }
591
708
  async disabled(ids) {
592
- await cron_1.CrontabModel.update({ isDisabled: 1 }, { where: { id: ids } });
593
- try {
709
+ return (0, schedulerMutationLock_1.withSchedulerMutation)(async () => {
594
710
  await client_1.default.delCron(ids.map(String));
595
- }
596
- catch (error) {
597
- this.logger.warn('[crontab] Failed to unregister cron job in scheduler:', (error === null || error === void 0 ? void 0 : error.message) || error);
598
- }
599
- await this.setCrontab();
711
+ await cron_1.CrontabModel.update({ isDisabled: 1 }, { where: { id: ids } });
712
+ await this.setCrontab();
713
+ });
600
714
  }
601
715
  async enabled(ids) {
602
- await cron_1.CrontabModel.update({ isDisabled: 0 }, { where: { id: ids } });
603
- const docs = await cron_1.CrontabModel.findAll({ where: { id: ids } });
604
- const crons = docs
605
- .filter((x) => this.shouldUseCronClient(x))
606
- .map((doc) => ({
607
- name: doc.name || '',
608
- id: String(doc.id),
609
- schedule: doc.schedule,
610
- command: this.makeCommand(doc),
611
- extra_schedules: doc.extra_schedules || [],
612
- }));
613
- if ((0, util_1.isDemoEnv)()) {
614
- return;
615
- }
616
- try {
617
- await client_1.default.addCron(crons);
618
- }
619
- catch (error) {
620
- // gRPC 注册失败 → 回滚启用状态,避免 DB 显示已启用但调度器未注册
621
- await cron_1.CrontabModel.update({ isDisabled: 1 }, { where: { id: ids } });
622
- this.logger.error('[crontab] Failed to register cron job in scheduler, enable rolled back:', (error === null || error === void 0 ? void 0 : error.message) || error);
623
- throw new Error(`${(0, i18n_1.t)('调度器注册失败,任务启用已回滚')}: ${(error === null || error === void 0 ? void 0 : error.details) || (error === null || error === void 0 ? void 0 : error.message)}`);
624
- }
625
- await this.setCrontab();
716
+ return (0, schedulerMutationLock_1.withSchedulerMutation)(async () => {
717
+ await cron_1.CrontabModel.update({ isDisabled: 0 }, { where: { id: ids } });
718
+ const docs = await cron_1.CrontabModel.findAll({ where: { id: ids } });
719
+ const crons = docs
720
+ .filter((x) => this.shouldUseCronClient(x))
721
+ .map((doc) => ({
722
+ name: doc.name || '',
723
+ id: String(doc.id),
724
+ schedule: doc.schedule,
725
+ command: this.makeCommand(doc),
726
+ extra_schedules: doc.extra_schedules || [],
727
+ }));
728
+ if ((0, util_1.isDemoEnv)()) {
729
+ return;
730
+ }
731
+ try {
732
+ await client_1.default.addCron(crons);
733
+ }
734
+ catch (error) {
735
+ // gRPC 注册失败 → 回滚启用状态,避免 DB 显示已启用但调度器未注册
736
+ await cron_1.CrontabModel.update({ isDisabled: 1 }, { where: { id: ids } });
737
+ this.logger.error('[crontab] Failed to register cron job in scheduler, enable rolled back:', (error === null || error === void 0 ? void 0 : error.message) || error);
738
+ throw (0, schedulerMutationLock_1.schedulerRegistrationError)(`${(0, i18n_1.t)('调度器注册失败,任务启用已回滚')}: ${(error === null || error === void 0 ? void 0 : error.details) || (error === null || error === void 0 ? void 0 : error.message)}`, error);
739
+ }
740
+ await this.setCrontab();
741
+ });
626
742
  }
627
- async log(id) {
743
+ async log(id, options = {}) {
628
744
  const doc = await this.getDb({ id });
629
745
  if (!doc) {
630
- return { content: '', status: 'empty' };
746
+ return {
747
+ content: '',
748
+ status: 'empty',
749
+ offset: 0,
750
+ nextOffset: 0,
751
+ total: 0,
752
+ truncated: false,
753
+ };
631
754
  }
632
755
  if (doc.log_name === '/dev/null') {
633
- return { content: (0, i18n_1.t)('日志设置为忽略'), status: 'ignored' };
756
+ return {
757
+ content: (0, i18n_1.t)('日志设置为忽略'),
758
+ status: 'ignored',
759
+ offset: 0,
760
+ nextOffset: 0,
761
+ total: 0,
762
+ truncated: false,
763
+ };
634
764
  }
635
765
  const absolutePath = path_1.default.resolve(config_1.default.logPath, `${doc.log_path}`);
636
766
  const logFileExist = doc.log_path && (await (0, util_1.fileExist)(absolutePath));
637
767
  if (logFileExist) {
638
- const content = await (0, util_1.getFileContentByName)(`${absolutePath}`);
768
+ const chunk = await (0, logReader_1.readLogChunk)(`${absolutePath}`, options);
639
769
  const isRunning = typeof doc.status === 'number' &&
640
770
  [cron_1.CrontabStatus.running, cron_1.CrontabStatus.queued].includes(doc.status);
641
- return { content, status: isRunning ? 'running' : 'completed' };
771
+ return Object.assign(Object.assign({}, chunk), { status: isRunning ? 'running' : 'completed' });
642
772
  }
643
773
  else {
644
- return typeof doc.status === 'number' &&
774
+ const status = typeof doc.status === 'number' &&
645
775
  [cron_1.CrontabStatus.queued, cron_1.CrontabStatus.running].includes(doc.status)
646
- ? { content: (0, i18n_1.t)('运行中...'), status: 'running' }
647
- : { content: (0, i18n_1.t)('日志不存在...'), status: 'notFound' };
776
+ ? 'running'
777
+ : 'notFound';
778
+ return {
779
+ content: status === 'running' ? (0, i18n_1.t)('运行中...') : (0, i18n_1.t)('日志不存在...'),
780
+ status,
781
+ offset: 0,
782
+ nextOffset: 0,
783
+ total: 0,
784
+ truncated: false,
785
+ };
648
786
  }
649
787
  }
650
788
  async logs(id) {
@@ -759,41 +897,42 @@ let CronService = class CronService {
759
897
  });
760
898
  });
761
899
  }
762
- async autosave_crontab() {
763
- const tabs = await this.crontabs();
764
- const regularCrons = tabs.data
765
- .filter((x) => x.isDisabled !== 1 &&
766
- this.shouldUseCronClient(x))
767
- .map((doc) => ({
768
- name: doc.name || '',
769
- id: String(doc.id),
770
- schedule: doc.schedule,
771
- command: this.makeCommand(doc),
772
- extra_schedules: doc.extra_schedules || [],
773
- }));
774
- if ((0, util_1.isDemoEnv)()) {
775
- await (0, utils_1.writeFileWithLock)(config_1.default.crontabFile, '');
776
- return;
777
- }
778
- // 先同步 crontab.list 与系统 crontab,确保其始终反映数据库真实状态。
779
- // gRPC 调度注册为尽力而为:失败时不阻断文件同步,调度器重启后会重新注册。
780
- // 这避免了因调度器短暂不可用导致 crontab.list 与数据库脱节(订阅更新误判任务已存在)。
781
- await this.setCrontab(tabs);
782
- try {
783
- await client_1.default.addCron(regularCrons);
784
- }
785
- catch (error) {
786
- this.logger.warn('[crontab] Failed to register cron job in scheduler:', (error === null || error === void 0 ? void 0 : error.message) || error);
787
- }
900
+ async autosave_crontab(requireScheduler = false) {
901
+ return (0, schedulerMutationLock_1.withSchedulerMutation)(async () => {
902
+ const tabs = await this.crontabs();
903
+ const regularCrons = tabs.data
904
+ .filter((x) => x.isDisabled !== 1 &&
905
+ this.shouldUseCronClient(x))
906
+ .map((doc) => ({
907
+ name: doc.name || '',
908
+ id: String(doc.id),
909
+ schedule: doc.schedule,
910
+ command: this.makeCommand(doc),
911
+ extra_schedules: doc.extra_schedules || [],
912
+ }));
913
+ if ((0, util_1.isDemoEnv)()) {
914
+ await (0, utils_1.writeFileWithLock)(config_1.default.crontabFile, '');
915
+ return;
916
+ }
917
+ // 先同步 crontab.list 与系统 crontab,确保其始终反映数据库真实状态。
918
+ // gRPC 调度注册为尽力而为:失败时不阻断文件同步,调度器重启后会重新注册。
919
+ // 这避免了因调度器短暂不可用导致 crontab.list 与数据库脱节(订阅更新误判任务已存在)。
920
+ await this.setCrontab(tabs);
921
+ try {
922
+ await client_1.default.addCron(regularCrons, requireScheduler);
923
+ }
924
+ catch (error) {
925
+ this.logger.warn('[crontab] Failed to register cron job in scheduler:', (error === null || error === void 0 ? void 0 : error.message) || error);
926
+ if (requireScheduler)
927
+ throw error;
928
+ }
929
+ });
788
930
  }
789
931
  async bootTask() {
790
932
  const tabs = await this.crontabs();
791
933
  const bootTasks = tabs.data.filter((x) => !x.isDisabled && this.isBootSchedule(x.schedule));
792
934
  if (bootTasks.length > 0) {
793
- await cron_1.CrontabModel.update({ status: cron_1.CrontabStatus.queued }, { where: { id: bootTasks.map((t) => t.id) } });
794
- for (const task of bootTasks) {
795
- this.runSingle(task.id);
796
- }
935
+ await this.run(bootTasks.map((task) => task.id));
797
936
  }
798
937
  }
799
938
  };