@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
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.t = exports.getLang = exports.setLang = void 0;
3
+ exports.tf = exports.t = exports.systemLang = exports.setLang = void 0;
4
+ const store_1 = require("./store");
4
5
  const messages = {
5
6
  zh: {},
6
7
  en: {
@@ -82,18 +83,71 @@ const messages = {
82
83
  'client_id 或 client_seret 有误': 'Invalid client_id or client_secret',
83
84
  '订阅执行完成': 'Subscription completed',
84
85
  'wxPusher 服务的 TopicIds 和 Uids 至少配置一个才行': 'wxPusher requires at least one of TopicIds or Uids',
86
+ 'wxPusher SPT 不能为空': 'wxPusher SPT cannot be empty',
87
+ 'wxPusher SPT 最多支持 10 个': 'wxPusher SPT supports at most 10 tokens',
85
88
  'Url 或者 Body 中必须包含 $title': 'Url or Body must contain $title',
89
+ '绝对路径必须在日志目录内或使用 /dev/null': 'Absolute path must be within log directory or use /dev/null',
90
+ '请先登录': 'Please login first',
91
+ '运行中...': 'Running...',
92
+ '日志不存在...': 'Log does not exist...',
93
+ '未分类': 'Uncategorized',
94
+ '任务重复运行': 'Duplicate task execution',
95
+ '日志设置为忽略': 'Log set to ignore',
96
+ '定时规则不能为空': 'Schedule rule cannot be empty',
97
+ '无效的定时规则': 'Invalid schedule rule',
98
+ '日志名称只能包含中文、字母、数字、下划线、连字符、点和路径分隔符': 'Log name can only contain Chinese characters, letters, numbers, underscores, hyphens, dots, and path separators',
99
+ '日志名称不能超过100个字符': 'Log name cannot exceed 100 characters',
100
+ '错误的用户名密码,请重试': 'Incorrect username or password, please try again',
101
+ '该 IP 已被列入黑名单': 'This IP address has been blocked',
102
+ '已加入 IP 黑名单': 'IP address added to the blacklist',
103
+ '已移出 IP 黑名单': 'IP address removed from the blacklist',
104
+ '青龙快讯': 'QingLong',
105
+ '登录通知': 'Login Notification',
106
+ '你于': 'You at ',
107
+ '在': ' in ',
108
+ 端: '',
109
+ 登录失败: 'login failed',
110
+ ',ip地址': ', IP: ',
111
+ '任务#%s': 'Task#%s',
112
+ 安装: 'Install',
113
+ 删除: 'Uninstall',
114
+ 成功: 'Succeeded',
115
+ 失败: 'Failed',
116
+ '失败次数过多,请%s秒后重试': 'Too many failed attempts, please retry in %s seconds',
117
+ 智能助手: 'Smart Assistant',
118
+ 更多: 'More',
119
+ '开始%s依赖 %s,开始时间 %s\n\n当前系统不支持\n\n依赖%s失败,结束时间 %s,耗时 %s 秒': 'Start %s dependency %s, start time %s\n\nCurrent system not supported\n\nDependency %s failed, end time %s, elapsed %s seconds',
120
+ '检测到已经安装 %s\n\n%s\n\n跳过安装\n\n依赖%s成功,结束时间 %s,耗时 %s 秒': 'Already installed %s\n\n%s\n\nSkipping install\n\nDependency %s succeeded, end time %s, elapsed %s seconds',
121
+ '开始%s依赖 %s,开始时间 %s\n\n': 'Start %s dependency %s, start time %s\n\n',
122
+ '依赖%s%s,结束时间 %s,耗时 %s 秒': 'Dependency %s%s, end time %s, elapsed %s seconds',
123
+ '任务:%s,命令:%s,定时:%s,处于运行中的超过 %d 个,请检查定时设置': 'Task: %s, command: %s, schedule: %s, more than %d instances running, please check schedule settings',
124
+ 青龙: 'QingLong',
125
+ '【蛟龙】测试通知 https://t.me/jiao_long': '[JiaoLong] Test notification https://t.me/jiao_long',
126
+ '生成token': 'Generate token',
127
+ '删除日志': 'Delete logs',
128
+ '## 开始执行... %s\n': '## Start executing... %s\n',
129
+ '执行before命令...': 'Execute before command...',
130
+ '执行after命令...': 'Execute after command...',
131
+ '## 执行结束... %s 耗时 %s 秒': '## Execution finished... %s elapsed %s seconds',
132
+ '调度器注册失败,任务创建已回滚': 'Scheduler registration failed, task creation rolled back',
133
+ '调度器注册失败,任务更新已回滚': 'Scheduler registration failed, task update rolled back',
134
+ '调度器注册失败,任务启用已回滚': 'Scheduler registration failed, task enable rolled back',
135
+ '任务ID %s: 无效的 cron 表达式 "%s"(不支持裸 /N 步长和 ? 字符)': 'Task ID %s: invalid cron expression "%s" (bare /N steps and ? character not supported)',
136
+ '任务ID %s (extra_schedule): 无效的 cron 表达式 "%s"(不支持裸 /N 步长和 ? 字符)': 'Task ID %s (extra_schedule): invalid cron expression "%s" (bare /N steps and ? character not supported)',
86
137
  },
87
138
  };
88
139
  let currentLang = 'zh';
89
140
  function setLang(lang) {
90
141
  currentLang = lang || 'zh';
142
+ store_1.shareStore.setLang(currentLang);
91
143
  }
92
144
  exports.setLang = setLang;
93
- function getLang() {
94
- return currentLang;
145
+ /** 系统默认语言:Intl 检测 → 'zh'(仅返回 zh/en) */
146
+ function systemLang() {
147
+ const prefix = Intl.DateTimeFormat().resolvedOptions().locale.split('-')[0];
148
+ return prefix === 'en' ? 'en' : 'zh';
95
149
  }
96
- exports.getLang = getLang;
150
+ exports.systemLang = systemLang;
97
151
  function t(key, lang) {
98
152
  const effectiveLang = lang || currentLang;
99
153
  if (effectiveLang === 'en' && messages.en[key]) {
@@ -102,4 +156,8 @@ function t(key, lang) {
102
156
  return key;
103
157
  }
104
158
  exports.t = t;
159
+ function tf(key, ...args) {
160
+ return args.reduce((str, arg) => str.replace(/%s|%d/, String(arg)), t(key));
161
+ }
162
+ exports.tf = tf;
105
163
  //# sourceMappingURL=i18n.js.map
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.readLogChunk = exports.MAX_LOG_CHUNK_BYTES = exports.DEFAULT_LOG_CHUNK_BYTES = void 0;
7
+ const promises_1 = __importDefault(require("fs/promises"));
8
+ exports.DEFAULT_LOG_CHUNK_BYTES = 256 * 1024;
9
+ exports.MAX_LOG_CHUNK_BYTES = 1024 * 1024;
10
+ function normalizeLimit(limit) {
11
+ if (!Number.isFinite(limit))
12
+ return exports.DEFAULT_LOG_CHUNK_BYTES;
13
+ return Math.min(Math.max(Math.trunc(limit), 4), exports.MAX_LOG_CHUNK_BYTES);
14
+ }
15
+ function isUtf8ContinuationByte(byte) {
16
+ return (byte & 0xc0) === 0x80;
17
+ }
18
+ function completeUtf8End(buffer, start, end) {
19
+ if (end <= start)
20
+ return start;
21
+ let sequenceStart = end - 1;
22
+ while (sequenceStart > start &&
23
+ isUtf8ContinuationByte(buffer[sequenceStart])) {
24
+ sequenceStart--;
25
+ }
26
+ const firstByte = buffer[sequenceStart];
27
+ const expectedLength = firstByte < 0x80
28
+ ? 1
29
+ : firstByte < 0xe0
30
+ ? 2
31
+ : firstByte < 0xf0
32
+ ? 3
33
+ : 4;
34
+ return end - sequenceStart < expectedLength ? sequenceStart : end;
35
+ }
36
+ async function readLogChunk(filePath, options = {}) {
37
+ let handle;
38
+ try {
39
+ handle = await promises_1.default.open(filePath, 'r');
40
+ const { size: total } = await handle.stat();
41
+ const limit = normalizeLimit(options.limit);
42
+ const requestedOffset = Number.isFinite(options.offset)
43
+ ? Math.trunc(options.offset)
44
+ : undefined;
45
+ const requestedStart = options.tail || requestedOffset === undefined
46
+ ? Math.max(total - limit, 0)
47
+ : Math.min(Math.max(requestedOffset, 0), total);
48
+ const length = Math.min(limit + 3, total - requestedStart);
49
+ const buffer = Buffer.allocUnsafe(length);
50
+ const { bytesRead } = await handle.read(buffer, 0, length, requestedStart);
51
+ let leadingBytes = 0;
52
+ while (leadingBytes < bytesRead &&
53
+ isUtf8ContinuationByte(buffer[leadingBytes])) {
54
+ leadingBytes++;
55
+ }
56
+ const offset = requestedStart + leadingBytes;
57
+ const candidateEnd = Math.min(leadingBytes + limit, bytesRead);
58
+ const contentEnd = completeUtf8End(buffer, leadingBytes, candidateEnd);
59
+ const nextOffset = requestedStart + contentEnd;
60
+ return {
61
+ content: buffer.subarray(leadingBytes, contentEnd).toString('utf8'),
62
+ offset,
63
+ nextOffset,
64
+ total,
65
+ truncated: offset > 0 || nextOffset < total,
66
+ };
67
+ }
68
+ catch (error) {
69
+ if ((error === null || error === void 0 ? void 0 : error.code) === 'ENOENT') {
70
+ return {
71
+ content: '',
72
+ offset: 0,
73
+ nextOffset: 0,
74
+ total: 0,
75
+ truncated: false,
76
+ };
77
+ }
78
+ throw error;
79
+ }
80
+ finally {
81
+ await (handle === null || handle === void 0 ? void 0 : handle.close());
82
+ }
83
+ }
84
+ exports.readLogChunk = readLogChunk;
85
+ //# sourceMappingURL=logReader.js.map
@@ -1,94 +1,114 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.logStreamManager = exports.LogStreamManager = void 0;
4
7
  const fs_1 = require("fs");
5
8
  const events_1 = require("events");
9
+ const path_1 = __importDefault(require("path"));
10
+ const config_1 = __importDefault(require("../config"));
11
+ const fileAccess_1 = require("./fileAccess");
6
12
  /**
7
13
  * Manages write streams for log files to improve performance by avoiding repeated file opens
8
14
  */
9
15
  class LogStreamManager extends events_1.EventEmitter {
10
- constructor() {
11
- super(...arguments);
16
+ constructor(logRoot = config_1.default.logPath) {
17
+ super();
18
+ this.logRoot = logRoot;
12
19
  this.streams = new Map();
13
20
  this.pendingWrites = new Map();
21
+ this.closingStreams = new Map();
22
+ this.closedStreams = new WeakSet();
23
+ this.streamErrors = new Map();
14
24
  }
15
- /**
16
- * Write data to a log file using a managed stream
17
- * @param filePath - Absolute path to the log file
18
- * @param data - Data to write to the log file
19
- */
25
+ /** Register each write synchronously, so concurrent callers cannot lose the tail. */
20
26
  async write(filePath, data) {
21
- // Wait for any pending writes to this file to complete
22
- const pending = this.pendingWrites.get(filePath);
23
- if (pending) {
24
- await pending;
27
+ if (this.closingStreams.has(filePath)) {
28
+ throw new Error(`Log stream is closing: ${filePath}`);
25
29
  }
26
- // Create a new promise for this write operation
27
- const writePromise = new Promise((resolve, reject) => {
30
+ const previous = this.pendingWrites.get(filePath) || Promise.resolve();
31
+ const pending = previous.then(() => new Promise((resolve, reject) => {
32
+ const failure = this.streamErrors.get(filePath);
33
+ if (failure)
34
+ return reject(failure);
28
35
  let stream = this.streams.get(filePath);
29
36
  if (!stream) {
30
- // Create a new write stream if one doesn't exist
31
- stream = (0, fs_1.createWriteStream)(filePath, { flags: 'a' });
37
+ // Validate only when opening: subsequent chunks reuse the same descriptor.
38
+ const root = path_1.default.resolve(this.logRoot);
39
+ const target = path_1.default.resolve(filePath);
40
+ if (!target.startsWith(root + path_1.default.sep) ||
41
+ !(0, fileAccess_1.resolveFileAccess)(root, [target])) {
42
+ return reject(new Error('Log path is outside the log directory'));
43
+ }
44
+ stream = (0, fs_1.createWriteStream)(target, { flags: 'a' });
32
45
  this.streams.set(filePath, stream);
33
- // Handle stream errors
46
+ const current = stream;
47
+ stream.once('close', () => this.closedStreams.add(current));
34
48
  stream.on('error', (error) => {
35
- this.emit('error', { filePath, error });
36
- // Remove the stream from the map on error
37
- this.streams.delete(filePath);
38
- reject(error);
49
+ this.streamErrors.set(filePath, error);
50
+ // EventEmitter's unobserved "error" event would crash the caller.
51
+ if (this.listenerCount('error') > 0)
52
+ this.emit('error', { filePath, error });
39
53
  });
40
54
  }
41
- // Write the data
42
- const canContinue = stream.write(data, 'utf8', (error) => {
43
- if (error) {
44
- reject(error);
45
- }
46
- else {
47
- resolve();
55
+ stream.write(data, 'utf8', (error) => error ? reject(error) : resolve());
56
+ }));
57
+ this.pendingWrites.set(filePath, pending);
58
+ // Keep the tail until close, including failures; never reopen a failed log mid-run.
59
+ return pending;
60
+ }
61
+ async closeStream(filePath) {
62
+ const closing = this.closingStreams.get(filePath);
63
+ if (closing)
64
+ return closing;
65
+ const pending = this.pendingWrites.get(filePath);
66
+ const result = (async () => {
67
+ let failure;
68
+ try {
69
+ await pending;
70
+ }
71
+ catch (error) {
72
+ failure = error;
73
+ }
74
+ const stream = this.streams.get(filePath);
75
+ try {
76
+ if (stream && !this.closedStreams.has(stream)) {
77
+ await new Promise((resolve) => {
78
+ stream.once('close', resolve);
79
+ if (failure || stream.destroyed)
80
+ stream.destroy();
81
+ else
82
+ stream.end();
83
+ });
48
84
  }
49
- });
50
- // Handle backpressure
51
- if (!canContinue) {
52
- stream.once('drain', () => {
53
- // Stream is ready for more data
54
- });
85
+ failure || (failure = this.streamErrors.get(filePath));
86
+ if (failure)
87
+ throw failure;
88
+ }
89
+ finally {
90
+ this.streams.delete(filePath);
91
+ this.pendingWrites.delete(filePath);
92
+ this.streamErrors.delete(filePath);
55
93
  }
56
- });
57
- this.pendingWrites.set(filePath, writePromise);
94
+ })();
95
+ this.closingStreams.set(filePath, result);
58
96
  try {
59
- await writePromise;
97
+ await result;
60
98
  }
61
99
  finally {
62
- this.pendingWrites.delete(filePath);
63
- }
64
- }
65
- /**
66
- * Close the stream for a specific file path
67
- * @param filePath - Absolute path to the log file
68
- */
69
- async closeStream(filePath) {
70
- // Wait for any pending writes to complete
71
- const pending = this.pendingWrites.get(filePath);
72
- if (pending) {
73
- await pending.catch(() => {
74
- // Ignore errors on pending writes during close
75
- });
76
- }
77
- const stream = this.streams.get(filePath);
78
- if (stream) {
79
- return new Promise((resolve) => {
80
- stream.end(() => {
81
- this.streams.delete(filePath);
82
- resolve();
83
- });
84
- });
100
+ this.closingStreams.delete(filePath);
85
101
  }
86
102
  }
87
103
  /**
88
104
  * Close all open streams
89
105
  */
90
106
  async closeAll() {
91
- const closePromises = Array.from(this.streams.keys()).map((filePath) => this.closeStream(filePath));
107
+ const paths = new Set([
108
+ ...this.streams.keys(),
109
+ ...this.pendingWrites.keys(),
110
+ ]);
111
+ const closePromises = Array.from(paths).map((filePath) => this.closeStream(filePath));
92
112
  await Promise.all(closePromises);
93
113
  }
94
114
  /**
@@ -8,6 +8,7 @@ const os_1 = __importDefault(require("os"));
8
8
  const system_1 = require("../data/system");
9
9
  const logger_1 = __importDefault(require("../loaders/logger"));
10
10
  const notify_1 = __importDefault(require("../services/notify"));
11
+ const i18n_1 = require("../shared/i18n");
11
12
  const config_1 = __importDefault(require("../config"));
12
13
  const grpc_js_1 = require("@grpc/grpc-js");
13
14
  const api_1 = require("../protos/api");
@@ -117,8 +118,8 @@ class TaskLimit {
117
118
  if (repeatTimes < 3) {
118
119
  this.repeatCronNotifyMap.set(cron.id, repeatTimes + 1);
119
120
  this.client.systemNotify({
120
- title: '任务重复运行',
121
- content: `任务:${cron.name},命令:${cron.command},定时:${cron.schedule},处于运行中的超过 5 个,请检查定时设置`,
121
+ title: (0, i18n_1.t)('任务重复运行'),
122
+ content: (0, i18n_1.tf)('任务:%s,命令:%s,定时:%s,处于运行中的超过 %d 个,请检查定时设置', cron.name || '', cron.command || '', cron.schedule || '', 5),
122
123
  }, (err, res) => {
123
124
  if (err) {
124
125
  logger_1.default.error(`[schedule][任务重复运行] 通知失败 ${JSON.stringify(err)}`);
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.verifyPassword = exports.isPasswordHash = exports.hashPassword = void 0;
4
+ const crypto_1 = require("crypto");
5
+ const util_1 = require("util");
6
+ const deriveKey = (0, util_1.promisify)(crypto_1.scrypt);
7
+ const HASH_PREFIX = 'scrypt$';
8
+ async function hashPassword(password) {
9
+ const salt = (0, crypto_1.randomBytes)(16).toString('hex');
10
+ const key = (await deriveKey(password, salt, 64));
11
+ return `${HASH_PREFIX}${salt}$${key.toString('hex')}`;
12
+ }
13
+ exports.hashPassword = hashPassword;
14
+ function isPasswordHash(password) {
15
+ return /^scrypt\$[a-f0-9]{32}\$[a-f0-9]{128}$/.test(password);
16
+ }
17
+ exports.isPasswordHash = isPasswordHash;
18
+ async function verifyPassword(password, stored) {
19
+ if (!isPasswordHash(stored)) {
20
+ // Existing installations migrate after a successful password check.
21
+ const input = Buffer.from(password);
22
+ const expected = Buffer.from(stored);
23
+ return input.length === expected.length && (0, crypto_1.timingSafeEqual)(input, expected);
24
+ }
25
+ const [, salt, hash] = stored.split('$');
26
+ const key = (await deriveKey(password, salt, 64));
27
+ return (0, crypto_1.timingSafeEqual)(key, Buffer.from(hash, 'hex'));
28
+ }
29
+ exports.verifyPassword = verifyPassword;
30
+ //# sourceMappingURL=password.js.map
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getDirectorySize = exports.isDependenceCacheType = exports.normalizeRetentionPolicy = exports.normalizeRetentionDays = exports.DEPENDENCE_CACHE_TYPES = exports.MAX_RETENTION_DAYS = void 0;
7
+ const promises_1 = __importDefault(require("fs/promises"));
8
+ const path_1 = __importDefault(require("path"));
9
+ exports.MAX_RETENTION_DAYS = 3650;
10
+ exports.DEPENDENCE_CACHE_TYPES = ['node', 'python3'];
11
+ function normalizeRetentionDays(value) {
12
+ const days = Number(value);
13
+ if (!Number.isFinite(days))
14
+ return 0;
15
+ return Math.min(Math.max(Math.trunc(days), 0), exports.MAX_RETENTION_DAYS);
16
+ }
17
+ exports.normalizeRetentionDays = normalizeRetentionDays;
18
+ function normalizeRetentionPolicy(policy) {
19
+ return {
20
+ runningInstanceRetentionDays: normalizeRetentionDays(policy.runningInstanceRetentionDays),
21
+ cronStatRetentionDays: normalizeRetentionDays(policy.cronStatRetentionDays),
22
+ };
23
+ }
24
+ exports.normalizeRetentionPolicy = normalizeRetentionPolicy;
25
+ function isDependenceCacheType(value) {
26
+ return exports.DEPENDENCE_CACHE_TYPES.includes(value);
27
+ }
28
+ exports.isDependenceCacheType = isDependenceCacheType;
29
+ async function getDirectorySize(rootPath) {
30
+ const pending = [rootPath];
31
+ let total = 0;
32
+ while (pending.length > 0) {
33
+ const currentPath = pending.pop();
34
+ let entries;
35
+ try {
36
+ entries = await promises_1.default.readdir(currentPath, { withFileTypes: true });
37
+ }
38
+ catch (error) {
39
+ if ((error === null || error === void 0 ? void 0 : error.code) === 'ENOENT')
40
+ continue;
41
+ throw error;
42
+ }
43
+ for (const entry of entries) {
44
+ if (entry.isSymbolicLink())
45
+ continue;
46
+ const entryPath = path_1.default.join(currentPath, entry.name);
47
+ if (entry.isDirectory()) {
48
+ pending.push(entryPath);
49
+ }
50
+ else if (entry.isFile()) {
51
+ total += (await promises_1.default.stat(entryPath)).size;
52
+ }
53
+ }
54
+ }
55
+ return total;
56
+ }
57
+ exports.getDirectorySize = getDirectorySize;
58
+ //# sourceMappingURL=retention.js.map
@@ -11,9 +11,10 @@ const cron_1 = require("../data/cron");
11
11
  const util_1 = require("../config/util");
12
12
  const runningInstance_1 = require("../data/runningInstance");
13
13
  const dayjs_1 = __importDefault(require("dayjs"));
14
+ const childProcess_1 = require("./childProcess");
14
15
  function runCron(cmd, cron) {
15
- return pLimit_1.default.runWithCronLimit(cron, () => {
16
- return new Promise(async (resolve) => {
16
+ return pLimit_1.default.runWithCronLimit(cron, async () => {
17
+ try {
17
18
  // Check if the cron is already running and stop it (only if multiple instances are not allowed)
18
19
  try {
19
20
  const existingCron = await cron_1.CrontabModel.findOne({
@@ -27,31 +28,43 @@ function runCron(cmd, cron) {
27
28
  (existingCron.status === cron_1.CrontabStatus.running ||
28
29
  existingCron.status === cron_1.CrontabStatus.queued)) {
29
30
  logger_1.default.info(`[schedule][停止已运行任务] 任务ID: ${cron.id}, PID: ${existingCron.pid}`);
30
- await (0, util_1.killTask)(existingCron.pid);
31
+ await (0, util_1.killTask)(existingCron.pid, true);
31
32
  // Mark old running instances as stopped
32
33
  const stoppedAt = (0, dayjs_1.default)().unix();
33
- await runningInstance_1.RunningInstanceModel.update({ status: runningInstance_1.InstanceStatus.stopped, finished_at: stoppedAt }, { where: { cron_id: Number(cron.id), status: runningInstance_1.InstanceStatus.running } });
34
+ await runningInstance_1.RunningInstanceModel.update({ status: runningInstance_1.InstanceStatus.stopped, finished_at: stoppedAt }, {
35
+ where: {
36
+ cron_id: Number(cron.id),
37
+ status: runningInstance_1.InstanceStatus.running,
38
+ },
39
+ });
34
40
  // Update the status to idle after killing
35
41
  await cron_1.CrontabModel.update({ status: cron_1.CrontabStatus.idle, pid: undefined }, { where: { id: Number(cron.id) } });
36
42
  }
37
43
  }
38
44
  catch (error) {
39
45
  logger_1.default.error(`[schedule][检查已运行任务失败] 任务ID: ${cron.id}, 错误: ${error}`);
46
+ throw error;
40
47
  }
41
48
  logger_1.default.info(`[schedule][开始执行任务] 参数 ${JSON.stringify(Object.assign(Object.assign({}, cron), { command: cmd }))}`);
42
49
  const cp = (0, cross_spawn_1.spawn)(cmd, { shell: '/bin/bash' });
43
- cp.stderr.on('data', (data) => {
44
- logger_1.default.info('[schedule][执行任务失败] 命令: %s, 错误信息: %j', cmd, data.toString());
50
+ const { completed } = (0, childProcess_1.observeChildProcess)(cp, {
51
+ onStderr: async (message) => {
52
+ logger_1.default.info('[schedule][任务标准错误] 命令: %s, 信息: %s', cmd, message);
53
+ },
45
54
  });
46
- cp.on('error', (err) => {
47
- logger_1.default.error('[schedule][创建任务失败] 命令: %s, 错误信息: %j', cmd, err);
48
- });
49
- cp.on('exit', async (code) => {
50
- pLimit_1.default.removeQueuedCron(cron.id);
51
- logger_1.default.info('[schedule][执行任务结束] 参数: %s, 退出码: %j', JSON.stringify(Object.assign(Object.assign({}, cron), { command: cmd })), code);
52
- resolve(Object.assign(Object.assign({}, cron), { command: cmd, pid: cp.pid, code }));
53
- });
54
- });
55
+ const result = await completed;
56
+ if (result.error) {
57
+ logger_1.default.error('[schedule][执行任务失败] 命令: %s, 错误: %s', cmd, result.error.message);
58
+ }
59
+ logger_1.default.info('[schedule][执行任务结束] 任务ID: %s, 退出码: %j', cron.id, result.code);
60
+ return Object.assign(Object.assign(Object.assign({}, cron), { command: cmd, pid: cp.pid }), result);
61
+ }
62
+ catch (error) {
63
+ logger_1.default.error('[schedule][创建任务失败] 命令: %s, 错误: %s', cmd, (0, childProcess_1.asError)(error).message);
64
+ }
65
+ finally {
66
+ pLimit_1.default.removeQueuedCron(cron.id);
67
+ }
55
68
  });
56
69
  }
57
70
  exports.runCron = runCron;
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.schedulerRegistrationError = exports.withSchedulerMutation = void 0;
7
+ const proper_lockfile_1 = __importDefault(require("proper-lockfile"));
8
+ const config_1 = __importDefault(require("../config"));
9
+ // HTTP and gRPC both mutate cron definitions. Hold one shared lock from the
10
+ // initial DB read/write through scheduler registration (including rollback).
11
+ // Recovery takes the same lock before reading its replacement snapshot.
12
+ async function withSchedulerMutation(operation) {
13
+ let release;
14
+ try {
15
+ // proper-lockfile indexes held locks by target, not lockfilePath. Keep
16
+ // this identity separate from nested writeFileWithLock(crontabFile).
17
+ release = await proper_lockfile_1.default.lock(`${config_1.default.crontabFile}.scheduler`, {
18
+ realpath: false,
19
+ lockfilePath: `${config_1.default.crontabFile}.scheduler.lock`,
20
+ stale: 30000,
21
+ update: 10000,
22
+ retries: { retries: 50, factor: 1, minTimeout: 100, maxTimeout: 100 },
23
+ });
24
+ }
25
+ catch (cause) {
26
+ throw Object.assign(new Error('Scheduler configuration is busy', { cause }), {
27
+ status: 503,
28
+ });
29
+ }
30
+ try {
31
+ return await operation();
32
+ }
33
+ finally {
34
+ await release();
35
+ }
36
+ }
37
+ exports.withSchedulerMutation = withSchedulerMutation;
38
+ function schedulerRegistrationError(message, cause) {
39
+ return Object.assign(new Error(message, { cause }), {
40
+ status: (cause === null || cause === void 0 ? void 0 : cause.status) === 503 ? 503 : 500,
41
+ });
42
+ }
43
+ exports.schedulerRegistrationError = schedulerRegistrationError;
44
+ //# sourceMappingURL=schedulerMutationLock.js.map
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SchedulerReadiness = void 0;
4
+ // Recovery is single-flight and retried only while unavailable, never at idle.
5
+ class SchedulerReadiness {
6
+ constructor(probe, retryMs = 1000) {
7
+ this.probe = probe;
8
+ this.retryMs = retryMs;
9
+ this.ready = false;
10
+ this.generation = 0;
11
+ }
12
+ configure(restore) {
13
+ this.restore = restore;
14
+ }
15
+ invalidate() {
16
+ this.ready = false;
17
+ this.generation++;
18
+ void this.recover();
19
+ }
20
+ recover() {
21
+ if (this.pending)
22
+ return this.pending;
23
+ if (!this.restore)
24
+ return Promise.resolve(false);
25
+ clearTimeout(this.retry);
26
+ const generation = this.generation;
27
+ this.ready = false;
28
+ this.pending = (async () => {
29
+ try {
30
+ await this.probe();
31
+ await this.restore();
32
+ await this.probe();
33
+ this.ready = generation === this.generation;
34
+ }
35
+ catch (_a) {
36
+ this.ready = false;
37
+ }
38
+ return this.ready;
39
+ })().finally(() => {
40
+ this.pending = undefined;
41
+ if (!this.ready) {
42
+ this.retry = setTimeout(() => void this.recover(), this.retryMs);
43
+ this.retry.unref();
44
+ }
45
+ });
46
+ return this.pending;
47
+ }
48
+ async check() {
49
+ if (!this.ready)
50
+ return false;
51
+ const generation = this.generation;
52
+ try {
53
+ await this.probe();
54
+ return this.ready && generation === this.generation;
55
+ }
56
+ catch (_a) {
57
+ this.invalidate();
58
+ return false;
59
+ }
60
+ }
61
+ async ensureReady(timeoutMs = 2000) {
62
+ let timer;
63
+ try {
64
+ const available = await Promise.race([
65
+ (async () => (await this.check()) || (await this.recover()))(),
66
+ new Promise((resolve) => {
67
+ timer = setTimeout(() => resolve(false), timeoutMs);
68
+ }),
69
+ ]);
70
+ if (!available) {
71
+ throw Object.assign(new Error('Scheduler is recovering; try again later'), {
72
+ status: 503,
73
+ });
74
+ }
75
+ }
76
+ finally {
77
+ clearTimeout(timer);
78
+ }
79
+ }
80
+ }
81
+ exports.SchedulerReadiness = SchedulerReadiness;
82
+ //# sourceMappingURL=schedulerReadiness.js.map