@whyour/qinglong 2.21.0 → 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 (279) 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 +9 -1
  7. package/back/protos/cron.proto +4 -1
  8. package/deploy/kubernetes/README.md +81 -0
  9. package/deploy/kubernetes/base/kustomization.yaml +5 -0
  10. package/deploy/kubernetes/base/qinglong.yaml +95 -0
  11. package/deploy/kubernetes/overlays/example/kustomization.yaml +10 -0
  12. package/docker/Dockerfile +31 -12
  13. package/docker/Dockerfile.310 +31 -12
  14. package/docker/Dockerfile.debian +22 -14
  15. package/docker/Dockerfile.debian310 +24 -14
  16. package/docker/build-manifest.cjs +28 -0
  17. package/docker/verify-build.cjs +49 -0
  18. package/docs/releases/2.22.0-validation.md +49 -0
  19. package/docs/releases/2.22.0.md +54 -0
  20. package/ecosystem.config.js +10 -1
  21. package/package.json +11 -6
  22. package/sample/config.sample.sh +17 -2
  23. package/sample/notify.js +118 -0
  24. package/sample/notify.py +93 -0
  25. package/scripts/benchmark-execution.cjs +96 -0
  26. package/scripts/write-build-info.cjs +27 -0
  27. package/shell/api.sh +41 -14
  28. package/shell/check.sh +59 -19
  29. package/shell/lang/en.sh +6 -0
  30. package/shell/lang/zh.sh +6 -0
  31. package/shell/node_path_cache.sh +128 -0
  32. package/shell/otask.sh +10 -1
  33. package/shell/preload/sitecustomize.js +5 -1
  34. package/shell/share.sh +26 -9
  35. package/shell/start.sh +6 -3
  36. package/shell/task.sh +13 -3
  37. package/shell/update.sh +65 -4
  38. package/static/build/api/clientIp.js +42 -0
  39. package/static/build/api/config.js +8 -16
  40. package/static/build/api/cron.js +39 -3
  41. package/static/build/api/dashboard.js +50 -6
  42. package/static/build/api/env.js +2 -2
  43. package/static/build/api/health.js +2 -2
  44. package/static/build/api/index.js +4 -0
  45. package/static/build/api/log.js +39 -19
  46. package/static/build/api/retention.js +63 -0
  47. package/static/build/api/script.js +23 -22
  48. package/static/build/api/subscription.js +16 -2
  49. package/static/build/api/system.js +31 -9
  50. package/static/build/api/user.js +75 -15
  51. package/static/build/app.js +63 -54
  52. package/static/build/bootstrap/database.js +51 -0
  53. package/static/build/config/const.js +2 -0
  54. package/static/build/config/grpcCerts.js +4 -4
  55. package/static/build/config/index.js +0 -4
  56. package/static/build/config/share.js +5 -4
  57. package/static/build/config/util.js +136 -41
  58. package/static/build/data/cron.js +1 -0
  59. package/static/build/data/notify.js +18 -1
  60. package/static/build/data/sock.js +1 -0
  61. package/static/build/loaders/app.js +8 -6
  62. package/static/build/loaders/db.js +5 -35
  63. package/static/build/loaders/deps.js +30 -22
  64. package/static/build/loaders/express.js +44 -32
  65. package/static/build/loaders/initData.js +10 -7
  66. package/static/build/loaders/initFile.js +1 -1
  67. package/static/build/loaders/initTask.js +3 -2
  68. package/static/build/loaders/server.js +1 -1
  69. package/static/build/loaders/sock.js +72 -6
  70. package/static/build/middlewares/monitoring.js +12 -33
  71. package/static/build/middlewares/protectedPathCase.js +17 -0
  72. package/static/build/protos/api.js +78 -2
  73. package/static/build/protos/cron.js +21 -4
  74. package/static/build/protos/health.js +1 -1
  75. package/static/build/schedule/addCron.js +76 -10
  76. package/static/build/schedule/api.js +5 -2
  77. package/static/build/schedule/client.js +38 -6
  78. package/static/build/schedule/delCron.js +11 -1
  79. package/static/build/schedule/health.js +72 -7
  80. package/static/build/services/config.js +5 -42
  81. package/static/build/services/cron.js +353 -164
  82. package/static/build/services/dependence.js +66 -18
  83. package/static/build/services/grpc.js +2 -2
  84. package/static/build/services/health.js +4 -7
  85. package/static/build/services/http.js +9 -3
  86. package/static/build/services/log.js +2 -3
  87. package/static/build/services/metrics.js +46 -14
  88. package/static/build/services/notify.js +73 -5
  89. package/static/build/services/retention.js +123 -0
  90. package/static/build/services/schedule.js +57 -33
  91. package/static/build/services/script.js +4 -5
  92. package/static/build/services/subscription.js +57 -34
  93. package/static/build/services/system.js +49 -11
  94. package/static/build/services/user.js +244 -31
  95. package/static/build/shared/auth.js +22 -3
  96. package/static/build/shared/authMutation.js +17 -0
  97. package/static/build/shared/childProcess.js +82 -0
  98. package/static/build/shared/clientIp.js +27 -0
  99. package/static/build/shared/errors.js +9 -0
  100. package/static/build/shared/fileAccess.js +60 -0
  101. package/static/build/shared/i18n.js +62 -4
  102. package/static/build/shared/logReader.js +85 -0
  103. package/static/build/shared/logStreamManager.js +80 -60
  104. package/static/build/shared/pLimit.js +3 -2
  105. package/static/build/shared/password.js +30 -0
  106. package/static/build/shared/retention.js +58 -0
  107. package/static/build/shared/runCron.js +28 -15
  108. package/static/build/shared/schedulerMutationLock.js +44 -0
  109. package/static/build/shared/schedulerReadiness.js +82 -0
  110. package/static/build/shared/schemaMigrations.js +58 -0
  111. package/static/build/shared/startupProcess.js +48 -0
  112. package/static/build/shared/store.js +7 -0
  113. package/static/build/shared/trustProxy.js +119 -0
  114. package/static/build/validation/schedule.js +12 -3
  115. package/static/dist/{1885.e1ea09f6.async.js → 1885.b8f427bf.async.js} +1 -1
  116. package/static/dist/2031.6af40025.async.js +1 -0
  117. package/static/dist/2693.51c2636b.async.js +1 -0
  118. package/static/dist/{2890.9e373f5b.async.js → 2890.add55e85.async.js} +1 -1
  119. package/static/dist/2901.2ca95295.async.js +1 -0
  120. package/static/dist/445.a65ff63b.async.js +1 -0
  121. package/static/dist/4736.1d2b5cb6.async.js +1 -0
  122. package/static/dist/{4859.6592cebb.async.js → 4859.97d6653c.async.js} +1 -1
  123. package/static/dist/{6013.4e38de36.async.js → 6013.db535339.async.js} +1 -1
  124. package/static/dist/6212.9e6d9913.async.js +1 -0
  125. package/static/dist/{6339.ab305e96.async.js → 6431.4603ad0e.async.js} +1 -1
  126. package/static/dist/{6872.42f939f1.async.js → 6872.a503ef55.async.js} +1 -1
  127. package/static/dist/7231.f7e5b668.async.js +1 -0
  128. package/static/dist/{7355.f9f263d8.async.js → 7355.fca746f5.async.js} +1 -1
  129. package/static/dist/{7508.7dcee91c.async.js → 7508.d90eac63.async.js} +1 -1
  130. package/static/dist/{7984.594296a5.async.js → 7984.eaac7402.async.js} +1 -1
  131. package/static/dist/8844.a0fef08e.async.js +1 -0
  132. package/static/dist/index.html +2 -2
  133. package/static/dist/layouts__index.633d3553.async.js +1 -0
  134. package/static/dist/preload_helper.cf7de3fa.js +1 -0
  135. package/static/dist/{src__pages__config__index.a22ff7dc.async.js → src__pages__config__index.9aba4054.async.js} +1 -1
  136. package/static/dist/src__pages__crontab__detail.86b2eebb.async.js +1 -0
  137. package/static/dist/src__pages__crontab__index.ae4e06f2.async.js +1 -0
  138. package/static/dist/{src__pages__crontab__logModal.0b8cce8c.async.js → src__pages__crontab__logModal.930535e2.async.js} +1 -1
  139. package/static/dist/src__pages__crontab__modal.a2c8fdcc.async.js +1 -0
  140. package/static/dist/src__pages__crontab__viewCreateModal.7b4f9cbe.async.js +1 -0
  141. package/static/dist/src__pages__crontab__viewManageModal.cd454ea0.async.js +1 -0
  142. package/static/dist/src__pages__dashboard__index.243c5a35.async.js +1 -0
  143. package/static/dist/src__pages__dashboard__taskResultModal.7795d6e1.async.js +1 -0
  144. package/static/dist/src__pages__dependence__index.874d501f.async.js +1 -0
  145. package/static/dist/src__pages__dependence__logModal.154efe7a.async.js +1 -0
  146. package/static/dist/src__pages__dependence__modal.a29c1a0f.async.js +1 -0
  147. package/static/dist/{src__pages__diff__index.013b7c75.async.js → src__pages__diff__index.1714b941.async.js} +1 -1
  148. package/static/dist/src__pages__env__editNameModal.c13d47d2.async.js +1 -0
  149. package/static/dist/src__pages__env__index.fd6fd2b0.async.js +1 -0
  150. package/static/dist/src__pages__env__modal.4d71adb3.async.js +1 -0
  151. package/static/dist/src__pages__error__index.aae50c94.async.js +1 -0
  152. package/static/dist/src__pages__initialization__index.82a2e967.async.js +1 -0
  153. package/static/dist/src__pages__log__index.71250e0d.async.js +1 -0
  154. package/static/dist/{src__pages__login__index.8c813eb1.async.js → src__pages__login__index.a0fd5ed8.async.js} +1 -1
  155. package/static/dist/src__pages__script__editModal.22acdf7c.async.js +1 -0
  156. package/static/dist/src__pages__script__editNameModal.1a521cc0.async.js +1 -0
  157. package/static/dist/src__pages__script__index.a18b2692.async.js +1 -0
  158. package/static/dist/src__pages__script__renameModal.0ab029e7.async.js +1 -0
  159. package/static/dist/src__pages__script__saveModal.8965b74c.async.js +1 -0
  160. package/static/dist/src__pages__script__setting.35ad4f02.async.js +1 -0
  161. package/static/dist/src__pages__setting__appModal.7eaeb9d3.async.js +1 -0
  162. package/static/dist/src__pages__setting__checkUpdate.d175b154.async.js +1 -0
  163. package/static/dist/src__pages__setting__clientIp.3a8711ed.async.js +1 -0
  164. package/static/dist/src__pages__setting__dependence.9c0f749b.async.js +1 -0
  165. package/static/dist/src__pages__setting__index.cb397741.async.js +1 -0
  166. package/static/dist/src__pages__setting__loginLog.e0a1f54d.async.js +1 -0
  167. package/static/dist/src__pages__setting__notification.2ffe4e5a.async.js +1 -0
  168. package/static/dist/src__pages__setting__other.3d0b8492.async.js +1 -0
  169. package/static/dist/{src__pages__setting__progress.8823ac90.async.js → src__pages__setting__progress.2ccae3d7.async.js} +1 -1
  170. package/static/dist/src__pages__setting__security.e2d71ebb.async.js +1 -0
  171. package/static/dist/src__pages__setting__systemLog.b3046955.async.js +1 -0
  172. package/static/dist/src__pages__subscription__index.43086a06.async.js +1 -0
  173. package/static/dist/src__pages__subscription__logModal.cdba5139.async.js +1 -0
  174. package/static/dist/src__pages__subscription__modal.38991e1e.async.js +1 -0
  175. package/static/dist/{umi.ca04a019.js → umi.fc019050.js} +1 -1
  176. package/test/back/auth-security.test.cjs +74 -0
  177. package/test/back/build-provenance.test.cjs +150 -0
  178. package/test/back/cron-log-name.test.cjs +110 -0
  179. package/test/back/cron-validation.test.cjs +45 -0
  180. package/test/back/dashboard-failures.test.cjs +173 -0
  181. package/test/back/database-bootstrap.test.cjs +193 -0
  182. package/test/back/dependence-cache-status.test.cjs +125 -0
  183. package/test/back/deprecated-file-routes.test.cjs +82 -0
  184. package/test/back/ecosystem.test.cjs +28 -0
  185. package/test/back/env-name-parsing.test.cjs +96 -0
  186. package/test/back/execution-lifecycle.test.cjs +236 -0
  187. package/test/back/file-access-security.test.cjs +47 -0
  188. package/test/back/fileTreeListing.test.cjs +57 -0
  189. package/test/back/grpc-cron-response.test.cjs +60 -0
  190. package/test/back/http-exclusive-listen.test.cjs +31 -0
  191. package/test/back/http-security.test.cjs +213 -0
  192. package/test/back/listen-security.test.cjs +67 -0
  193. package/test/back/log-path-security.test.cjs +158 -0
  194. package/test/back/logReader.test.cjs +72 -0
  195. package/test/back/manual-execution.test.cjs +85 -0
  196. package/test/back/manual-stop-claim.test.cjs +220 -0
  197. package/test/back/metrics.test.cjs +34 -0
  198. package/test/back/monitoring.test.cjs +73 -0
  199. package/test/back/node-path-cache.test.cjs +173 -0
  200. package/test/back/node-path-lock.test.cjs +178 -0
  201. package/test/back/npm-publication.test.cjs +70 -0
  202. package/test/back/primary-apm.test.cjs +24 -0
  203. package/test/back/process-exit-state.test.cjs +81 -0
  204. package/test/back/process-stop-signal.test.cjs +77 -0
  205. package/test/back/protected-path-case.test.cjs +58 -0
  206. package/test/back/qlServiceLogCommand.test.cjs +128 -0
  207. package/test/back/retention.test.cjs +131 -0
  208. package/test/back/role-loading.test.cjs +118 -0
  209. package/test/back/schedule-health.test.cjs +86 -0
  210. package/test/back/scheduler-file-lock.test.cjs +51 -0
  211. package/test/back/scheduler-mutation.test.cjs +312 -0
  212. package/test/back/scheduler-readiness.test.cjs +85 -0
  213. package/test/back/scheduler-reconciliation.test.cjs +152 -0
  214. package/test/back/scheduler-rpc-timeout.test.cjs +49 -0
  215. package/test/back/schema-migrations.test.cjs +127 -0
  216. package/test/back/shell-api-parsing.test.cjs +184 -0
  217. package/test/back/sock-polling.test.cjs +297 -0
  218. package/test/back/sock-security.test.cjs +72 -0
  219. package/test/back/start-env-preservation.test.cjs +53 -0
  220. package/test/back/stop-failure-feedback.test.cjs +158 -0
  221. package/test/back/stop-race.test.cjs +167 -0
  222. package/test/back/subscription-cleanup.test.cjs +53 -0
  223. package/test/back/subscription-stop-state.test.cjs +66 -0
  224. package/test/back/system-dependence-cache.test.cjs +126 -0
  225. package/test/back/task-time.test.cjs +116 -0
  226. package/test/back/user-api.test.cjs +99 -0
  227. package/test/back/user-security.test.cjs +248 -0
  228. package/test/back/worker-apm.test.cjs +84 -0
  229. package/test/back/wpush-grpc.test.cjs +115 -0
  230. package/test/front/cron-log-pagination.test.cjs +214 -0
  231. package/test/front/http-auth.test.cjs +152 -0
  232. package/test/front/http-error.test.cjs +29 -0
  233. package/test/helpers/load-security-module.cjs +42 -0
  234. package/version.yaml +19 -34
  235. package/CLAUDE.md +0 -43
  236. package/static/dist/1147.c420132e.async.js +0 -1
  237. package/static/dist/134.54df9e38.async.js +0 -1
  238. package/static/dist/2208.f7ba3dfa.async.js +0 -1
  239. package/static/dist/2286.164bb089.async.js +0 -1
  240. package/static/dist/3191.63263871.async.js +0 -1
  241. package/static/dist/4902.555f92ab.async.js +0 -1
  242. package/static/dist/5520.ff2cfd6b.async.js +0 -1
  243. package/static/dist/6431.c50479be.async.js +0 -1
  244. package/static/dist/8826.2447a104.async.js +0 -1
  245. package/static/dist/layouts__index.a7a2bfe0.async.js +0 -1
  246. package/static/dist/preload_helper.0431c0f3.js +0 -1
  247. package/static/dist/src__pages__crontab__detail.b9c36808.async.js +0 -1
  248. package/static/dist/src__pages__crontab__index.fed99fd0.async.js +0 -1
  249. package/static/dist/src__pages__crontab__modal.f7041c7c.async.js +0 -1
  250. package/static/dist/src__pages__crontab__viewCreateModal.4d589f66.async.js +0 -1
  251. package/static/dist/src__pages__crontab__viewManageModal.0e317746.async.js +0 -1
  252. package/static/dist/src__pages__dashboard__index.b30f2f47.async.js +0 -1
  253. package/static/dist/src__pages__dependence__index.3d87ceac.async.js +0 -1
  254. package/static/dist/src__pages__dependence__logModal.0681830b.async.js +0 -1
  255. package/static/dist/src__pages__dependence__modal.11124896.async.js +0 -1
  256. package/static/dist/src__pages__env__editNameModal.5d264b25.async.js +0 -1
  257. package/static/dist/src__pages__env__index.baa27d4e.async.js +0 -1
  258. package/static/dist/src__pages__env__modal.7f2ef1bc.async.js +0 -1
  259. package/static/dist/src__pages__error__index.f156b45e.async.js +0 -1
  260. package/static/dist/src__pages__initialization__index.e96d4ba8.async.js +0 -1
  261. package/static/dist/src__pages__log__index.e0978bae.async.js +0 -1
  262. package/static/dist/src__pages__script__editModal.cbf4ec0e.async.js +0 -1
  263. package/static/dist/src__pages__script__editNameModal.3e7e100d.async.js +0 -1
  264. package/static/dist/src__pages__script__index.2765d1b8.async.js +0 -1
  265. package/static/dist/src__pages__script__renameModal.5e987ef5.async.js +0 -1
  266. package/static/dist/src__pages__script__saveModal.3f9d23d6.async.js +0 -1
  267. package/static/dist/src__pages__script__setting.a535793a.async.js +0 -1
  268. package/static/dist/src__pages__setting__appModal.251cd14f.async.js +0 -1
  269. package/static/dist/src__pages__setting__checkUpdate.46efe057.async.js +0 -1
  270. package/static/dist/src__pages__setting__dependence.8a7a9529.async.js +0 -1
  271. package/static/dist/src__pages__setting__index.cc85fdfb.async.js +0 -1
  272. package/static/dist/src__pages__setting__loginLog.cea6056c.async.js +0 -1
  273. package/static/dist/src__pages__setting__notification.390fc905.async.js +0 -1
  274. package/static/dist/src__pages__setting__other.b22d2165.async.js +0 -1
  275. package/static/dist/src__pages__setting__security.598720a8.async.js +0 -1
  276. package/static/dist/src__pages__setting__systemLog.67406721.async.js +0 -1
  277. package/static/dist/src__pages__subscription__index.d0ab2abc.async.js +0 -1
  278. package/static/dist/src__pages__subscription__logModal.3864b37f.async.js +0 -1
  279. package/static/dist/src__pages__subscription__modal.3562c670.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,59 +102,100 @@ 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 (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;
112
+ }
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
+ }
132
+ }
133
+ await this.setCrontab();
105
134
  return doc;
106
- }
107
- if (this.shouldUseCronClient(doc)) {
108
- await client_1.default.addCron([
109
- {
110
- name: doc.name || '',
111
- id: String(doc.id),
112
- schedule: doc.schedule,
113
- command: this.makeCommand(doc),
114
- extra_schedules: doc.extra_schedules || [],
115
- },
116
- ]);
117
- }
118
- await this.setCrontab();
119
- return doc;
135
+ });
120
136
  }
121
137
  async insert(payload) {
122
138
  return await cron_1.CrontabModel.create(payload, { returning: true });
123
139
  }
124
140
  async update(payload) {
125
- const doc = await this.getDb({ id: payload.id });
126
- const tab = new cron_1.Crontab(Object.assign(Object.assign({}, doc), payload));
127
- tab.saved = false;
128
- tab.log_name = await this.getLogName(tab);
129
- const newDoc = await this.updateDb(tab);
130
- if (doc.isDisabled === 1 || (0, util_1.isDemoEnv)()) {
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);
148
+ }
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
+ }
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);
188
+ }
189
+ }
190
+ await this.setCrontab();
131
191
  return newDoc;
132
- }
133
- await client_1.default.delCron([String(newDoc.id)]);
134
- if (this.shouldUseCronClient(newDoc)) {
135
- await client_1.default.addCron([
136
- {
137
- name: doc.name || '',
138
- id: String(newDoc.id),
139
- schedule: newDoc.schedule,
140
- command: this.makeCommand(newDoc),
141
- extra_schedules: newDoc.extra_schedules || [],
142
- },
143
- ]);
144
- }
145
- await this.setCrontab();
146
- return newDoc;
192
+ });
147
193
  }
148
194
  async updateDb(payload) {
149
195
  await cron_1.CrontabModel.update(payload, { where: { id: payload.id } });
150
196
  return await this.getDb({ id: payload.id });
151
197
  }
152
- async status({ ids, status, pid, log_path, last_running_time = 0, last_execution_time = 0, }) {
198
+ async status({ ids, status, pid, log_path, last_running_time = 0, last_execution_time = 0, exit_code, }) {
153
199
  let options = {
154
200
  status,
155
201
  pid,
@@ -185,9 +231,13 @@ let CronService = class CronService {
185
231
  else if (status === cron_1.CrontabStatus.idle) {
186
232
  // Mark the matching running instance as finished
187
233
  const finishedAt = (0, dayjs_1.default)().unix();
234
+ const instanceStatus = exit_code !== undefined && exit_code !== null && exit_code !== 0
235
+ ? runningInstance_1.InstanceStatus.error
236
+ : runningInstance_1.InstanceStatus.finished;
188
237
  await runningInstance_1.RunningInstanceModel.update({
189
238
  finished_at: finishedAt,
190
- status: runningInstance_1.InstanceStatus.finished,
239
+ status: instanceStatus,
240
+ exit_code: exit_code !== null && exit_code !== void 0 ? exit_code : undefined,
191
241
  }, {
192
242
  where: {
193
243
  cron_id: id,
@@ -200,9 +250,11 @@ let CronService = class CronService {
200
250
  }
201
251
  }
202
252
  async remove(ids) {
203
- await cron_1.CrontabModel.destroy({ where: { id: ids } });
204
- await client_1.default.delCron(ids.map(String));
205
- await this.setCrontab();
253
+ return (0, schedulerMutationLock_1.withSchedulerMutation)(async () => {
254
+ await client_1.default.delCron(ids.map(String));
255
+ await cron_1.CrontabModel.destroy({ where: { id: ids } });
256
+ await this.setCrontab();
257
+ });
206
258
  }
207
259
  async pin(ids) {
208
260
  await cron_1.CrontabModel.update({ isPinned: 1 }, { where: { id: ids } });
@@ -445,31 +497,82 @@ let CronService = class CronService {
445
497
  return doc.get({ plain: true });
446
498
  }
447
499
  async run(ids) {
448
- 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 } });
449
502
  ids.forEach((id) => {
450
- this.runSingle(id);
503
+ this.runSingle(id, queuedToken);
451
504
  });
452
505
  }
453
506
  async stop(ids) {
507
+ var _a, _b, _c, _d, _e;
454
508
  const docs = await cron_1.CrontabModel.findAll({ where: { id: ids } });
509
+ // Cancel the queued snapshot first, so a late spawn cannot claim it.
455
510
  for (const doc of docs) {
456
- // 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) {
457
541
  try {
458
- if (doc.pid) {
459
- await (0, util_1.killTask)(doc.pid);
460
- }
461
- const command = doc.command.replace(/\s+/g, ' ').trim();
462
- await (0, util_1.killAllTasks)(command);
463
- this.logger.info(`[panel][停止所有运行中的任务实例] 任务ID: ${doc.id}, 命令: ${command}`);
542
+ await (0, util_1.killTask)(pid, true);
543
+ stopped.add(pid);
464
544
  }
465
545
  catch (error) {
466
- this.logger.error(`[panel][停止任务失败] 任务ID: ${doc.id}, 错误: ${error}`);
546
+ this.logger.error('[panel][停止任务失败] PID: %s, 错误: %s', pid, (0, childProcess_1.asError)(error).message);
467
547
  }
468
548
  }
469
- // Mark all running instances as stopped
470
- const finishedAt = (0, dayjs_1.default)().unix();
471
- await runningInstance_1.RunningInstanceModel.update({ status: runningInstance_1.InstanceStatus.stopped, finished_at: finishedAt }, { where: { cron_id: ids, status: runningInstance_1.InstanceStatus.running } });
472
- 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
+ }
473
576
  }
474
577
  async stopInstance(instanceId) {
475
578
  const instance = await runningInstance_1.RunningInstanceModel.findOne({
@@ -486,7 +589,7 @@ let CronService = class CronService {
486
589
  this.logger.error(`[panel][停止实例失败] 实例ID: ${instanceId}, PID: ${instance.pid}, 错误: ${error}`);
487
590
  }
488
591
  }
489
- await runningInstance_1.RunningInstanceModel.update({ status: runningInstance_1.InstanceStatus.stopped, finished_at: (0, dayjs_1.default)().unix() }, { where: { id: instanceId } });
592
+ await runningInstance_1.RunningInstanceModel.update({ status: runningInstance_1.InstanceStatus.stopped, finished_at: (0, dayjs_1.default)().unix(), exit_code: 143 }, { where: { id: instanceId } });
490
593
  // Check if there are still other running instances for this cron
491
594
  const otherRunning = await runningInstance_1.RunningInstanceModel.count({
492
595
  where: { cron_id: instance.cron_id, status: runningInstance_1.InstanceStatus.running },
@@ -496,113 +599,190 @@ let CronService = class CronService {
496
599
  }
497
600
  return { code: 200, message: (0, i18n_1.t)('实例已停止') };
498
601
  }
499
- async runSingle(cronId) {
500
- return pLimit_1.default.manualRunWithCronLimit(() => {
501
- 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 {
502
611
  const cron = await this.getDb({ id: cronId });
503
- const params = {
504
- name: cron.name,
505
- command: cron.command,
506
- schedule: cron.schedule,
507
- extra_schedules: cron.extra_schedules,
508
- };
509
- if (cron.status !== cron_1.CrontabStatus.queued) {
510
- resolve(params);
612
+ if (cron.status !== cron_1.CrontabStatus.queued ||
613
+ (expectedToken !== undefined && cron.queued_token !== expectedToken))
511
614
  return;
512
- }
513
- this.logger.info(`[panel][开始执行任务] 参数: ${JSON.stringify(params)}`);
514
- 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;
515
618
  const uniqPath = log_name === '/dev/null' || !log_name
516
619
  ? await (0, util_1.getUniqPath)(command, `${id}`)
517
620
  : log_name;
518
621
  const logTime = (0, dayjs_1.default)().format('YYYY-MM-DD-HH-mm-ss-SSS');
519
- const logDirPath = path_1.default.resolve(config_1.default.logPath, `${uniqPath}`);
520
- await promises_1.default.mkdir(logDirPath, { recursive: true });
521
- const logPath = `${uniqPath}/${logTime}.log`;
522
- 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;
523
628
  const cp = (0, cross_spawn_1.spawn)(`real_log_path=${logPath} no_delay=true ${this.makeCommand(cron, true)}`, { shell: '/bin/bash' });
524
- const startedAt = (0, dayjs_1.default)().unix();
525
- const instance = await runningInstance_1.RunningInstanceModel.create({
526
- cron_id: id,
527
- pid: cp.pid,
528
- log_path: logPath,
529
- started_at: startedAt,
530
- status: runningInstance_1.InstanceStatus.running,
531
- });
532
- await cron_1.CrontabModel.update({ status: cron_1.CrontabStatus.running, pid: cp.pid, log_path: logPath }, { where: { id } });
533
- cp.stdout.on('data', async (data) => {
534
- await logStreamManager_1.logStreamManager.write(absolutePath, data.toString());
535
- });
536
- cp.stderr.on('data', async (data) => {
537
- this.logger.info('[panel][执行任务失败] 命令: %s, 错误信息: %j', command, data.toString());
538
- await logStreamManager_1.logStreamManager.write(absolutePath, data.toString());
539
- });
540
- cp.on('error', async (err) => {
541
- this.logger.error('[panel][创建任务失败] 命令: %s, 错误信息: %j', command, err);
542
- await logStreamManager_1.logStreamManager.write(absolutePath, JSON.stringify(err));
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),
543
659
  });
544
- cp.on('exit', async (code) => {
545
- this.logger.info('[panel][执行任务结束] 参数: %s, 退出码: %j', JSON.stringify(params), code);
546
- await logStreamManager_1.logStreamManager.closeStream(absolutePath);
547
- const finishedAt = (0, dayjs_1.default)().unix();
548
- await runningInstance_1.RunningInstanceModel.update({
549
- finished_at: finishedAt,
550
- status: code === 0 ? runningInstance_1.InstanceStatus.finished : runningInstance_1.InstanceStatus.error,
551
- exit_code: code !== null && code !== void 0 ? code : undefined,
552
- }, { where: { id: instance.id } });
553
- // Only set cron to idle if no other running instances exist
554
- const otherRunning = await runningInstance_1.RunningInstanceModel.count({
555
- where: { cron_id: id, status: runningInstance_1.InstanceStatus.running },
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
+ },
556
700
  });
557
- if (otherRunning === 0) {
558
- await cron_1.CrontabModel.update({ status: cron_1.CrontabStatus.idle, pid: undefined }, { where: { id } });
559
- }
560
- resolve(Object.assign(Object.assign({}, params), { pid: cp.pid, code }));
561
- });
562
- });
701
+ }
702
+ catch (error) {
703
+ this.logger.error('[panel][清理任务状态失败] %s', (0, childProcess_1.asError)(error).message);
704
+ }
705
+ }
563
706
  });
564
707
  }
565
708
  async disabled(ids) {
566
- await cron_1.CrontabModel.update({ isDisabled: 1 }, { where: { id: ids } });
567
- await client_1.default.delCron(ids.map(String));
568
- await this.setCrontab();
709
+ return (0, schedulerMutationLock_1.withSchedulerMutation)(async () => {
710
+ await client_1.default.delCron(ids.map(String));
711
+ await cron_1.CrontabModel.update({ isDisabled: 1 }, { where: { id: ids } });
712
+ await this.setCrontab();
713
+ });
569
714
  }
570
715
  async enabled(ids) {
571
- await cron_1.CrontabModel.update({ isDisabled: 0 }, { where: { id: ids } });
572
- const docs = await cron_1.CrontabModel.findAll({ where: { id: ids } });
573
- const crons = docs
574
- .filter((x) => this.shouldUseCronClient(x))
575
- .map((doc) => ({
576
- name: doc.name || '',
577
- id: String(doc.id),
578
- schedule: doc.schedule,
579
- command: this.makeCommand(doc),
580
- extra_schedules: doc.extra_schedules || [],
581
- }));
582
- if ((0, util_1.isDemoEnv)()) {
583
- return;
584
- }
585
- await client_1.default.addCron(crons);
586
- await this.setCrontab();
587
- }
588
- async log(id) {
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
+ });
742
+ }
743
+ async log(id, options = {}) {
589
744
  const doc = await this.getDb({ id });
590
745
  if (!doc) {
591
- return '';
746
+ return {
747
+ content: '',
748
+ status: 'empty',
749
+ offset: 0,
750
+ nextOffset: 0,
751
+ total: 0,
752
+ truncated: false,
753
+ };
592
754
  }
593
755
  if (doc.log_name === '/dev/null') {
594
- return '日志设置为忽略';
756
+ return {
757
+ content: (0, i18n_1.t)('日志设置为忽略'),
758
+ status: 'ignored',
759
+ offset: 0,
760
+ nextOffset: 0,
761
+ total: 0,
762
+ truncated: false,
763
+ };
595
764
  }
596
765
  const absolutePath = path_1.default.resolve(config_1.default.logPath, `${doc.log_path}`);
597
766
  const logFileExist = doc.log_path && (await (0, util_1.fileExist)(absolutePath));
598
767
  if (logFileExist) {
599
- return await (0, util_1.getFileContentByName)(`${absolutePath}`);
768
+ const chunk = await (0, logReader_1.readLogChunk)(`${absolutePath}`, options);
769
+ const isRunning = typeof doc.status === 'number' &&
770
+ [cron_1.CrontabStatus.running, cron_1.CrontabStatus.queued].includes(doc.status);
771
+ return Object.assign(Object.assign({}, chunk), { status: isRunning ? 'running' : 'completed' });
600
772
  }
601
773
  else {
602
- return typeof doc.status === 'number' &&
774
+ const status = typeof doc.status === 'number' &&
603
775
  [cron_1.CrontabStatus.queued, cron_1.CrontabStatus.running].includes(doc.status)
604
- ? '运行中...'
605
- : '日志不存在...';
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
+ };
606
786
  }
607
787
  }
608
788
  async logs(id) {
@@ -717,33 +897,42 @@ let CronService = class CronService {
717
897
  });
718
898
  });
719
899
  }
720
- async autosave_crontab() {
721
- const tabs = await this.crontabs();
722
- const regularCrons = tabs.data
723
- .filter((x) => x.isDisabled !== 1 &&
724
- this.shouldUseCronClient(x))
725
- .map((doc) => ({
726
- name: doc.name || '',
727
- id: String(doc.id),
728
- schedule: doc.schedule,
729
- command: this.makeCommand(doc),
730
- extra_schedules: doc.extra_schedules || [],
731
- }));
732
- if ((0, util_1.isDemoEnv)()) {
733
- await (0, utils_1.writeFileWithLock)(config_1.default.crontabFile, '');
734
- return;
735
- }
736
- await client_1.default.addCron(regularCrons);
737
- this.setCrontab(tabs);
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
+ });
738
930
  }
739
931
  async bootTask() {
740
932
  const tabs = await this.crontabs();
741
933
  const bootTasks = tabs.data.filter((x) => !x.isDisabled && this.isBootSchedule(x.schedule));
742
934
  if (bootTasks.length > 0) {
743
- await cron_1.CrontabModel.update({ status: cron_1.CrontabStatus.queued }, { where: { id: bootTasks.map((t) => t.id) } });
744
- for (const task of bootTasks) {
745
- this.runSingle(task.id);
746
- }
935
+ await this.run(bootTasks.map((task) => task.id));
747
936
  }
748
937
  }
749
938
  };